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
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/nullness/RedundantNullCheckTest.java
|
{
"start": 11174,
"end": 11803
}
|
class ____ {
String getString() {
return "foo";
}
void process() {
// BUG: Diagnostic contains: RedundantNullCheck
if (getString() == null) {}
}
}
""")
.doTest();
}
@Test
public void negative_methodCall_inNullMarkedScope_explicitlyNullableReturn() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
|
Test
|
java
|
quarkusio__quarkus
|
test-framework/junit5-component/src/test/java/io/quarkus/test/component/mockito/MockitoExtensionTest.java
|
{
"start": 1197,
"end": 1279
}
|
class ____ {
boolean pong() {
return true;
}
}
}
|
Foo
|
java
|
apache__camel
|
core/camel-management/src/main/java/org/apache/camel/management/mbean/ManagedTaskManagerRegistry.java
|
{
"start": 1612,
"end": 3598
}
|
class ____ extends ManagedService implements ManagedTaskManagerRegistryMBean {
private final TaskManagerRegistry registry;
public ManagedTaskManagerRegistry(CamelContext context, TaskManagerRegistry registry) {
super(context, registry);
this.registry = registry;
}
@Override
public Integer getSize() {
return registry.getSize();
}
@Override
public TabularData listTasks() {
try {
TabularData answer = new TabularDataSupport(CamelOpenMBeanTypes.listInternalTaskTabularType());
for (Task task : registry.getTasks()) {
String name = task.getName();
String kind = task instanceof BackgroundTask ? "background" : "foreground";
String status = task.getStatus().name();
long attempts = task.iteration();
long delay = task.getCurrentDelay();
long elapsed = task.getCurrentElapsedTime();
long firstTime = task.getFirstAttemptTime();
long lastTime = task.getLastAttemptTime();
long nextTime = task.getNextAttemptTime();
String failure = task.getException() != null ? task.getException().getMessage() : null;
CompositeType ct = CamelOpenMBeanTypes.listInternalTaskCompositeType();
CompositeData data = new CompositeDataSupport(
ct,
new String[] {
"name", "kind", "status", "attempts", "delay", "elapsed", "firstTime", "lastTime", "nextTime",
"failure" },
new Object[] { name, kind, status, attempts, delay, elapsed, firstTime, lastTime, nextTime, failure });
answer.put(data);
}
return answer;
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
}
}
}
|
ManagedTaskManagerRegistry
|
java
|
apache__logging-log4j2
|
log4j-1.2-api/src/test/java/org/apache/log4j/pattern/FormattingInfoTest.java
|
{
"start": 945,
"end": 2797
}
|
class ____ extends TestCase {
/**
* Create a new instance.
*
* @param name test name
*/
public FormattingInfoTest(final String name) {
super(name);
}
/**
* Check constructor
*
*/
public void testConstructor() {
final FormattingInfo field = new FormattingInfo(true, 3, 6);
assertNotNull(field);
assertEquals(3, field.getMinLength());
assertEquals(6, field.getMaxLength());
assertTrue(field.isLeftAligned());
}
/**
* Check that getDefault does not return null.
*
*/
public void testGetDefault() {
final FormattingInfo field = FormattingInfo.getDefault();
assertNotNull(field);
assertEquals(0, field.getMinLength());
assertEquals(Integer.MAX_VALUE, field.getMaxLength());
assertFalse(field.isLeftAligned());
}
/**
* Add padding to left since field is not minimum width.
*/
public void testPadLeft() {
final StringBuffer buf = new StringBuffer("foobar");
final FormattingInfo field = new FormattingInfo(false, 5, 10);
field.format(2, buf);
assertEquals("fo obar", buf.toString());
}
/**
* Add padding to right since field is not minimum width.
*/
public void testPadRight() {
final StringBuffer buf = new StringBuffer("foobar");
final FormattingInfo field = new FormattingInfo(true, 5, 10);
field.format(2, buf);
assertEquals("foobar ", buf.toString());
}
/**
* Field exceeds maximum width
*/
public void testTruncate() {
final StringBuffer buf = new StringBuffer("foobar");
final FormattingInfo field = new FormattingInfo(true, 0, 3);
field.format(2, buf);
assertEquals("fobar", buf.toString());
}
}
|
FormattingInfoTest
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/main/java/io/vertx/core/http/impl/http1x/Http1xServerConnection.java
|
{
"start": 3218,
"end": 6507
}
|
class ____ extends Http1xConnection implements HttpServerConnection {
private final String serverOrigin;
private final Supplier<ContextInternal> streamContextSupplier;
private final TracingPolicy tracingPolicy;
private final boolean eagerCreateRequestQueue;
private Http1xServerRequest requestInProgress;
private Http1xServerRequest responseInProgress;
private boolean wantClose;
private Handler<HttpServerRequest> requestHandler;
private Handler<HttpServerRequest> invalidRequestHandler;
final HttpServerMetrics metrics;
final boolean handle100ContinueAutomatically;
final HttpServerOptions options;
final SslContextManager sslContextManager;
final boolean strictThreadMode;
public Http1xServerConnection(ThreadingModel threadingModel,
Supplier<ContextInternal> streamContextSupplier,
SslContextManager sslContextManager,
HttpServerOptions options,
ChannelHandlerContext chctx,
ContextInternal context,
String serverOrigin,
HttpServerMetrics metrics) {
super(context, chctx, options.getStrictThreadMode() && threadingModel == ThreadingModel.EVENT_LOOP);
this.serverOrigin = serverOrigin;
this.streamContextSupplier = streamContextSupplier;
this.options = options;
this.sslContextManager = sslContextManager;
this.metrics = metrics;
this.handle100ContinueAutomatically = options.isHandle100ContinueAutomatically();
this.tracingPolicy = options.getTracingPolicy();
this.wantClose = false;
this.strictThreadMode = options.getStrictThreadMode() && threadingModel == ThreadingModel.EVENT_LOOP;
this.eagerCreateRequestQueue = threadingModel != ThreadingModel.EVENT_LOOP;
}
@Override
protected void handleShutdown(Duration timeout, ChannelPromise promise) {
super.handleShutdown(timeout, promise);
if (!timeout.isZero() && responseInProgress == null) {
closeInternal();
}
}
@Override
public Headers<CharSequence, CharSequence, ?> newHeaders() {
throw new UnsupportedOperationException();
}
@Override
public boolean supportsSendFile() {
return true;
}
TracingPolicy tracingPolicy() {
return tracingPolicy;
}
@Override
public HttpServerConnection streamHandler(Handler<HttpServerStream> handler) {
// This feature is not available for HTTP/1.1
return this;
}
public HttpServerConnection handler(Handler<HttpServerRequest> handler) {
requestHandler = handler;
return this;
}
public HttpServerConnection invalidRequestHandler(Handler<HttpServerRequest> handler) {
invalidRequestHandler = handler;
return this;
}
@Override
public HttpServerMetrics metrics() {
return metrics;
}
public void handleMessage(Object msg) {
assert msg != null;
if (requestInProgress == null && (shutdownInitiated != null || wantClose)) {
ReferenceCountUtil.release(msg);
return;
}
// fast-path first
if (msg == LastHttpContent.EMPTY_LAST_CONTENT) {
onEnd();
} else if (msg instanceof DefaultHttpRequest) {
// fast path type check vs concrete
|
Http1xServerConnection
|
java
|
spring-projects__spring-security
|
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/event/OAuth2AuthorizedClientRefreshedEvent.java
|
{
"start": 1203,
"end": 2374
}
|
class ____ extends ApplicationEvent {
@Serial
private static final long serialVersionUID = -2178028089321556476L;
private final OAuth2AuthorizedClient authorizedClient;
/**
* Creates a new instance with the provided parameters.
* @param accessTokenResponse the {@link OAuth2AccessTokenResponse} that triggered the
* event
* @param authorizedClient the refreshed {@link OAuth2AuthorizedClient}
*/
public OAuth2AuthorizedClientRefreshedEvent(OAuth2AccessTokenResponse accessTokenResponse,
OAuth2AuthorizedClient authorizedClient) {
super(accessTokenResponse);
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
this.authorizedClient = authorizedClient;
}
/**
* Returns the {@link OAuth2AccessTokenResponse} that triggered the event.
* @return the access token response
*/
public OAuth2AccessTokenResponse getAccessTokenResponse() {
return (OAuth2AccessTokenResponse) this.getSource();
}
/**
* Returns the refreshed {@link OAuth2AuthorizedClient}.
* @return the authorized client
*/
public OAuth2AuthorizedClient getAuthorizedClient() {
return this.authorizedClient;
}
}
|
OAuth2AuthorizedClientRefreshedEvent
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MllpEndpointBuilderFactory.java
|
{
"start": 57329,
"end": 67102
}
|
interface ____
extends
MllpEndpointConsumerBuilder,
MllpEndpointProducerBuilder {
default AdvancedMllpEndpointBuilder advanced() {
return (AdvancedMllpEndpointBuilder) this;
}
/**
* Enable/Disable the automatic generation of a MLLP Acknowledgement
* MLLP Consumers only.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param autoAck the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder autoAck(boolean autoAck) {
doSetProperty("autoAck", autoAck);
return this;
}
/**
* Enable/Disable the automatic generation of a MLLP Acknowledgement
* MLLP Consumers only.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param autoAck the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder autoAck(String autoAck) {
doSetProperty("autoAck", autoAck);
return this;
}
/**
* Sets the default charset to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param charsetName the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder charsetName(String charsetName) {
doSetProperty("charsetName", charsetName);
return this;
}
/**
* Enable/Disable the automatic generation of message headers from the
* HL7 Message MLLP Consumers only.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param hl7Headers the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder hl7Headers(boolean hl7Headers) {
doSetProperty("hl7Headers", hl7Headers);
return this;
}
/**
* Enable/Disable the automatic generation of message headers from the
* HL7 Message MLLP Consumers only.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param hl7Headers the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder hl7Headers(String hl7Headers) {
doSetProperty("hl7Headers", hl7Headers);
return this;
}
/**
* Enable/Disable strict compliance to the MLLP standard. The MLLP
* standard specifies START_OF_BLOCKhl7 payloadEND_OF_BLOCKEND_OF_DATA,
* however, some systems do not send the final END_OF_DATA byte. This
* setting controls whether or not the final END_OF_DATA byte is
* required or optional.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param requireEndOfData the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder requireEndOfData(boolean requireEndOfData) {
doSetProperty("requireEndOfData", requireEndOfData);
return this;
}
/**
* Enable/Disable strict compliance to the MLLP standard. The MLLP
* standard specifies START_OF_BLOCKhl7 payloadEND_OF_BLOCKEND_OF_DATA,
* however, some systems do not send the final END_OF_DATA byte. This
* setting controls whether or not the final END_OF_DATA byte is
* required or optional.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param requireEndOfData the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder requireEndOfData(String requireEndOfData) {
doSetProperty("requireEndOfData", requireEndOfData);
return this;
}
/**
* Enable/Disable converting the payload to a String. If enabled, HL7
* Payloads received from external systems will be validated converted
* to a String. If the charsetName property is set, that character set
* will be used for the conversion. If the charsetName property is not
* set, the value of MSH-18 will be used to determine th appropriate
* character set. If MSH-18 is not set, then the default ISO-8859-1
* character set will be use.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param stringPayload the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder stringPayload(boolean stringPayload) {
doSetProperty("stringPayload", stringPayload);
return this;
}
/**
* Enable/Disable converting the payload to a String. If enabled, HL7
* Payloads received from external systems will be validated converted
* to a String. If the charsetName property is set, that character set
* will be used for the conversion. If the charsetName property is not
* set, the value of MSH-18 will be used to determine th appropriate
* character set. If MSH-18 is not set, then the default ISO-8859-1
* character set will be use.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param stringPayload the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder stringPayload(String stringPayload) {
doSetProperty("stringPayload", stringPayload);
return this;
}
/**
* Enable/Disable the validation of HL7 Payloads If enabled, HL7
* Payloads received from external systems will be validated (see
* Hl7Util.generateInvalidPayloadExceptionMessage for details on the
* validation). If and invalid payload is detected, a
* MllpInvalidMessageException (for consumers) or a
* MllpInvalidAcknowledgementException will be thrown.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param validatePayload the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder validatePayload(boolean validatePayload) {
doSetProperty("validatePayload", validatePayload);
return this;
}
/**
* Enable/Disable the validation of HL7 Payloads If enabled, HL7
* Payloads received from external systems will be validated (see
* Hl7Util.generateInvalidPayloadExceptionMessage for details on the
* validation). If and invalid payload is detected, a
* MllpInvalidMessageException (for consumers) or a
* MllpInvalidAcknowledgementException will be thrown.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param validatePayload the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder validatePayload(String validatePayload) {
doSetProperty("validatePayload", validatePayload);
return this;
}
/**
* Sets the SSLContextParameters for securing TCP connections. If set,
* the MLLP component will use SSL/TLS for securing both producer and
* consumer TCP connections. This allows the configuration of trust
* stores, key stores, protocols, and other SSL/TLS settings. If not
* set, the MLLP component will use plain TCP communication.
*
* The option is a:
* <code>org.apache.camel.support.jsse.SSLContextParameters</code> type.
*
* Group: security
*
* @param sslContextParameters the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder sslContextParameters(org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) {
doSetProperty("sslContextParameters", sslContextParameters);
return this;
}
/**
* Sets the SSLContextParameters for securing TCP connections. If set,
* the MLLP component will use SSL/TLS for securing both producer and
* consumer TCP connections. This allows the configuration of trust
* stores, key stores, protocols, and other SSL/TLS settings. If not
* set, the MLLP component will use plain TCP communication.
*
* The option will be converted to a
* <code>org.apache.camel.support.jsse.SSLContextParameters</code> type.
*
* Group: security
*
* @param sslContextParameters the value to set
* @return the dsl builder
*/
default MllpEndpointBuilder sslContextParameters(String sslContextParameters) {
doSetProperty("sslContextParameters", sslContextParameters);
return this;
}
}
/**
* Advanced builder for endpoint for the MLLP component.
*/
public
|
MllpEndpointBuilder
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/co/LegacyKeyedCoProcessOperatorTest.java
|
{
"start": 19393,
"end": 20519
}
|
class ____
extends CoProcessFunction<Integer, String, String> {
private static final long serialVersionUID = 1L;
@Override
public void processElement1(Integer value, Context ctx, Collector<String> out)
throws Exception {
out.collect(
value
+ "PT:"
+ ctx.timerService().currentProcessingTime()
+ " TS:"
+ ctx.timestamp());
}
@Override
public void processElement2(String value, Context ctx, Collector<String> out)
throws Exception {
out.collect(
value
+ "PT:"
+ ctx.timerService().currentProcessingTime()
+ " TS:"
+ ctx.timestamp());
}
@Override
public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out)
throws Exception {}
}
private static
|
ProcessingTimeQueryingProcessFunction
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ProcessTableFunctionTestUtils.java
|
{
"start": 42568,
"end": 42885
}
|
class ____ {
public String s;
public Integer i;
public User(String s, Integer i) {
this.s = s;
this.i = i;
}
@Override
public String toString() {
return String.format("User(s='%s', i=%s)", s, i);
}
}
public static
|
User
|
java
|
apache__camel
|
components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/legacy/UseSeveralPropertyPlaceholderLocationsTest.java
|
{
"start": 1658,
"end": 2116
}
|
class
____.addConfiguration(MyConfiguration.class);
}
@Test
void shouldApplyAllPropertyPlaceholderLocations() throws Exception {
MockEndpoint mock = context.getEndpoint("mock:out", MockEndpoint.class);
mock.expectedBodiesReceived("Hello Jack!");
String result = template.requestBody("direct:in", null, String.class);
mock.assertIsSatisfied();
assertEquals("Hello Jack!", result);
}
}
|
configuration
|
java
|
spring-projects__spring-framework
|
spring-beans/src/main/java/org/springframework/beans/factory/support/GenericTypeAwareAutowireCandidateResolver.java
|
{
"start": 1822,
"end": 4196
}
|
class ____ extends SimpleAutowireCandidateResolver
implements BeanFactoryAware, Cloneable {
private @Nullable BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
protected final @Nullable BeanFactory getBeanFactory() {
return this.beanFactory;
}
@Override
public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
if (!super.isAutowireCandidate(bdHolder, descriptor)) {
// If explicitly false, do not proceed with any other checks...
return false;
}
return checkGenericTypeMatch(bdHolder, descriptor);
}
/**
* Match the given dependency type with its generic type information against the given
* candidate bean definition.
*/
@SuppressWarnings("NullAway") // Dataflow analysis limitation
protected boolean checkGenericTypeMatch(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
ResolvableType dependencyType = descriptor.getResolvableType();
if (dependencyType.getType() instanceof Class) {
// No generic type -> we know it's a Class type-match, so no need to check again.
return true;
}
ResolvableType targetType = null;
boolean cacheType = false;
RootBeanDefinition rbd = null;
if (bdHolder.getBeanDefinition() instanceof RootBeanDefinition rootBeanDef) {
rbd = rootBeanDef;
}
if (rbd != null) {
targetType = rbd.targetType;
if (targetType == null) {
cacheType = true;
// First, check factory method return type, if applicable
targetType = getReturnTypeForFactoryMethod(rbd, descriptor);
if (targetType == null) {
RootBeanDefinition dbd = getResolvedDecoratedDefinition(rbd);
if (dbd != null) {
targetType = dbd.targetType;
if (targetType == null) {
targetType = getReturnTypeForFactoryMethod(dbd, descriptor);
}
}
}
}
}
if (targetType == null) {
// Regular case: straight bean instance, with BeanFactory available.
if (this.beanFactory != null) {
Class<?> beanType = this.beanFactory.getType(bdHolder.getBeanName());
if (beanType != null) {
targetType = ResolvableType.forClass(ClassUtils.getUserClass(beanType));
}
}
// Fallback: no BeanFactory set, or no type resolvable through it
// -> best-effort match against the target
|
GenericTypeAwareAutowireCandidateResolver
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-documentstore/src/test/java/org/apache/hadoop/yarn/server/timelineservice/documentstore/writer/cosmosdb/MockedCosmosDBDocumentStoreWriter.java
|
{
"start": 1341,
"end": 1777
}
|
class ____
extends CosmosDBDocumentStoreWriter {
public MockedCosmosDBDocumentStoreWriter(Configuration conf) {
super(conf);
}
@Override
TimelineDocument fetchLatestDoc(CollectionType collectionType,
String documentId, StringBuilder eTagStrBuilder) {
try {
return DocumentStoreTestUtils.bakeTimelineEntityDoc();
} catch (IOException e) {
return null;
}
}
}
|
MockedCosmosDBDocumentStoreWriter
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/android/FragmentNotInstantiableTest.java
|
{
"start": 16509,
"end": 16711
}
|
class ____ extends CustomFragment {
private int a;
public int value() {
return a;
}
}
public static
|
MyFragment
|
java
|
spring-projects__spring-framework
|
spring-test/src/main/java/org/springframework/test/web/servlet/client/StatusAssertions.java
|
{
"start": 1008,
"end": 1465
}
|
class ____ extends AbstractStatusAssertions<ExchangeResult, RestTestClient.ResponseSpec> {
StatusAssertions(ExchangeResult exchangeResult, ResponseSpec responseSpec) {
super(exchangeResult, responseSpec);
}
@Override
protected HttpStatusCode getStatus() {
return getExchangeResult().getStatus();
}
@Override
protected void assertWithDiagnostics(Runnable assertion) {
getExchangeResult().assertWithDiagnostics(assertion);
}
}
|
StatusAssertions
|
java
|
apache__camel
|
components/camel-smb/src/main/java/org/apache/camel/component/smb/SmbComponent.java
|
{
"start": 1301,
"end": 3427
}
|
class ____ extends GenericFileComponent<FileIdBothDirectoryInformation> {
private static final Logger LOG = LoggerFactory.getLogger(SmbComponent.class);
public static final String SMB_FILE_INPUT_STREAM = "CamelSmbFileInputStream";
public SmbComponent() {
}
public SmbComponent(CamelContext context) {
super(context);
}
@Override
protected GenericFileEndpoint<FileIdBothDirectoryInformation> buildFileEndpoint(
String uri, String remaining, Map<String, Object> parameters)
throws Exception {
String baseUri = getBaseUri(uri);
// lets make sure we create a new configuration as each endpoint can
// customize its own version
// must pass on baseUri to the configuration (see above)
SmbConfiguration config = new SmbConfiguration(new URI(baseUri));
// backwards compatible when path was query parameter
String path = getAndRemoveParameter(parameters, "path", String.class);
if (path != null) {
config.setPath(path);
LOG.warn(
"The path option should be specified in the context-path. Instead of using ?path=/mypath then specify this in the context-path in uri: "
+ uri);
}
if (config.getShareName() == null) {
throw new IllegalArgumentException("ShareName must be configured");
}
SmbEndpoint endpoint = new SmbEndpoint(uri, this, config);
setProperties(endpoint, parameters);
return endpoint;
}
@Override
protected void afterPropertiesSet(GenericFileEndpoint<FileIdBothDirectoryInformation> endpoint) throws Exception {
// noop
}
/**
* Get the base uri part before the options as they can be non URI valid such as the expression using $ chars and
* the URI constructor will regard $ as an illegal character, and we don't want to enforce end users to escape the $
* for the expression (file language)
*/
protected String getBaseUri(String uri) {
return StringHelper.before(uri, "?", uri);
}
}
|
SmbComponent
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java
|
{
"start": 62248,
"end": 62432
}
|
class ____ {
@Bean public Foo foo() {
return new Foo();
}
@Bean public Bar bar() {
return new Bar(foo());
}
}
@Configuration
static final
|
NonEnhancedSingletonBeanConfig
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java
|
{
"start": 40602,
"end": 40691
}
|
class ____ {
@Hourly
void generateReport() {
}
}
static
|
MetaAnnotationCronTestBean
|
java
|
apache__flink
|
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/TypeInferenceExtractorTest.java
|
{
"start": 98851,
"end": 99257
}
|
class ____ implements Procedure {
@ProcedureHint(
input = @DataTypeHint("INT"),
argumentNames = "b",
output = @DataTypeHint("BIGINT"))
public Number[] call(Object procedureContext, Integer i) {
return null;
}
}
@ProcedureHint(input = @DataTypeHint("INT"))
private static
|
InvalidFullOutputProcedureWithArgNamesHint
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/common/requests/GetTelemetrySubscriptionsResponse.java
|
{
"start": 1125,
"end": 2380
}
|
class ____ extends AbstractResponse {
private final GetTelemetrySubscriptionsResponseData data;
public GetTelemetrySubscriptionsResponse(GetTelemetrySubscriptionsResponseData data) {
super(ApiKeys.GET_TELEMETRY_SUBSCRIPTIONS);
this.data = data;
}
@Override
public GetTelemetrySubscriptionsResponseData data() {
return data;
}
@Override
public Map<Errors, Integer> errorCounts() {
Map<Errors, Integer> counts = new EnumMap<>(Errors.class);
updateErrorCounts(counts, Errors.forCode(data.errorCode()));
return counts;
}
@Override
public int throttleTimeMs() {
return data.throttleTimeMs();
}
@Override
public void maybeSetThrottleTimeMs(int throttleTimeMs) {
data.setThrottleTimeMs(throttleTimeMs);
}
public boolean hasError() {
return error() != Errors.NONE;
}
public Errors error() {
return Errors.forCode(data.errorCode());
}
public static GetTelemetrySubscriptionsResponse parse(Readable readable, short version) {
return new GetTelemetrySubscriptionsResponse(new GetTelemetrySubscriptionsResponseData(
readable, version));
}
}
|
GetTelemetrySubscriptionsResponse
|
java
|
spring-projects__spring-security
|
crypto/src/main/java/org/springframework/security/crypto/password/Digester.java
|
{
"start": 1019,
"end": 2102
}
|
class ____ {
private final String algorithm;
private int iterations;
/**
* Create a new Digester.
* @param algorithm the digest algorithm; for example, "SHA-1" or "SHA-256".
* @param iterations the number of times to apply the digest algorithm to the input
*/
Digester(String algorithm, int iterations) {
// eagerly validate the algorithm
createDigest(algorithm);
this.algorithm = algorithm;
setIterations(iterations);
}
byte[] digest(byte[] value) {
MessageDigest messageDigest = createDigest(this.algorithm);
for (int i = 0; i < this.iterations; i++) {
value = messageDigest.digest(value);
}
return value;
}
void setIterations(int iterations) {
if (iterations <= 0) {
throw new IllegalArgumentException("Iterations value must be greater than zero");
}
this.iterations = iterations;
}
private static MessageDigest createDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("No such hashing algorithm", ex);
}
}
}
|
Digester
|
java
|
alibaba__nacos
|
config/src/test/java/com/alibaba/nacos/config/server/constant/ConstantsTest.java
|
{
"start": 1664,
"end": 2482
}
|
class ____ {
@Test
void testControllerPathsDefaultValues() {
assertEquals("/v1/cs/ops", OPS_CONTROLLER_PATH);
assertEquals("/v1/cs/capacity", CAPACITY_CONTROLLER_PATH);
assertEquals("/v1/cs/communication", COMMUNICATION_CONTROLLER_PATH);
assertEquals("/v1/cs/configs", CONFIG_CONTROLLER_PATH);
assertEquals("/v1/cs/health", HEALTH_CONTROLLER_PATH);
assertEquals("/v1/cs/history", HISTORY_CONTROLLER_PATH);
assertEquals("/v1/cs/listener", LISTENER_CONTROLLER_PATH);
assertEquals("/v1/cs/namespaces", NAMESPACE_CONTROLLER_PATH);
assertEquals("/v1/cs/metrics", METRICS_CONTROLLER_PATH);
}
@Test
void testRecvWaitTimeoutDefaultValue() {
assertEquals(10000, RECV_WAIT_TIMEOUT);
}
}
|
ConstantsTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/autoscaling/src/test/java/org/elasticsearch/xpack/autoscaling/capacity/nodeinfo/AutoscalingNodesInfoServiceTests.java
|
{
"start": 3693,
"end": 22021
}
|
class ____ extends AutoscalingTestCase {
private TestThreadPool threadPool;
private NodeStatsClient client;
private AutoscalingNodeInfoService service;
private TimeValue fetchTimeout;
private AutoscalingMetadata autoscalingMetadata;
private Metadata metadata;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
threadPool = createThreadPool();
client = new NodeStatsClient(threadPool);
final ClusterService clusterService = mock(ClusterService.class);
Settings settings;
if (randomBoolean()) {
fetchTimeout = TimeValue.timeValueSeconds(15);
settings = Settings.EMPTY;
} else {
fetchTimeout = TimeValue.timeValueMillis(randomLongBetween(1, 10000));
settings = Settings.builder().put(FETCH_TIMEOUT.getKey(), fetchTimeout).build();
}
when(clusterService.getSettings()).thenReturn(settings);
Set<Setting<?>> settingsSet = Sets.union(ClusterSettings.BUILT_IN_CLUSTER_SETTINGS, Set.of(FETCH_TIMEOUT));
ClusterSettings clusterSettings = new ClusterSettings(settings, settingsSet);
when(clusterService.getClusterSettings()).thenReturn(clusterSettings);
service = new AutoscalingNodeInfoService(clusterService, client);
autoscalingMetadata = randomAutoscalingMetadataOfPolicyCount(between(1, 8));
metadata = Metadata.builder().putCustom(AutoscalingMetadata.NAME, autoscalingMetadata).build();
}
@After
@Override
public void tearDown() throws Exception {
threadPool.close();
super.tearDown();
}
public void testAddRemoveNode() {
if (randomBoolean()) {
service.onClusterChanged(new ClusterChangedEvent("test", ClusterState.EMPTY_STATE, ClusterState.EMPTY_STATE));
}
ClusterState previousState = ClusterState.EMPTY_STATE;
Set<DiscoveryNode> previousNodes = new HashSet<>();
Set<DiscoveryNode> previousSucceededNodes = new HashSet<>();
for (int i = 0; i < 5; ++i) {
Set<DiscoveryNode> newNodes = IntStream.range(0, between(1, 10))
.mapToObj(n -> newNode("test_" + n))
.collect(Collectors.toSet());
Set<DiscoveryNode> nodes = Sets.union(newNodes, new HashSet<>(randomSubsetOf(previousNodes)));
ClusterState state = ClusterState.builder(ClusterName.DEFAULT)
.metadata(metadata)
.nodes(discoveryNodesBuilder(nodes, true))
.build();
Set<DiscoveryNode> missingNodes = Sets.difference(nodes, previousSucceededNodes);
Set<DiscoveryNode> failingNodes = new HashSet<>(randomSubsetOf(missingNodes));
Set<DiscoveryNode> succeedingNodes = Sets.difference(missingNodes, failingNodes);
List<FailedNodeException> failures = failingNodes.stream()
.map(node -> new FailedNodeException(node.getId(), randomAlphaOfLength(10), new Exception()))
.collect(Collectors.toList());
NodesStatsResponse response = new NodesStatsResponse(
ClusterName.DEFAULT,
succeedingNodes.stream()
.map(n -> statsForNode(n, randomLongBetween(0, Long.MAX_VALUE / 1000)))
.collect(Collectors.toList()),
failures
);
NodesInfoResponse responseInfo = new NodesInfoResponse(
ClusterName.DEFAULT,
succeedingNodes.stream().map(n -> infoForNode(n, randomIntBetween(1, 64))).collect(Collectors.toList()),
List.of()
);
client.respondStats(response, () -> {
Sets.union(missingNodes, Sets.difference(previousNodes, nodes))
.forEach(n -> assertThat(service.snapshot().get(n), isEmpty()));
Sets.intersection(previousSucceededNodes, nodes).forEach(n -> assertThat(service.snapshot().get(n), isPresent()));
});
client.respondInfo(responseInfo, () -> {
});
service.onClusterChanged(new ClusterChangedEvent("test", state, previousState));
client.assertNoResponder();
assertMatchesResponse(succeedingNodes, response, responseInfo);
failingNodes.forEach(n -> assertThat(service.snapshot().get(n), isEmpty()));
previousNodes.clear();
previousNodes.addAll(nodes);
previousSucceededNodes.retainAll(nodes);
previousSucceededNodes.addAll(succeedingNodes);
previousState = state;
}
}
public void testNotMaster() {
Set<DiscoveryNode> nodes = IntStream.range(0, between(1, 10)).mapToObj(n -> newNode("test_" + n)).collect(Collectors.toSet());
DiscoveryNodes.Builder nodesBuilder = discoveryNodesBuilder(nodes, false);
ClusterState state = ClusterState.builder(ClusterName.DEFAULT).nodes(nodesBuilder).metadata(metadata).build();
// client throws if called.
service.onClusterChanged(new ClusterChangedEvent("test", state, ClusterState.EMPTY_STATE));
nodes.forEach(n -> assertThat(service.snapshot().get(n), isEmpty()));
}
public void testNoLongerMaster() {
Set<DiscoveryNode> nodes = IntStream.range(0, between(1, 10)).mapToObj(n -> newNode("test_" + n)).collect(Collectors.toSet());
ClusterState masterState = ClusterState.builder(ClusterName.DEFAULT)
.nodes(discoveryNodesBuilder(nodes, true))
.metadata(metadata)
.build();
NodesStatsResponse response = new NodesStatsResponse(
ClusterName.DEFAULT,
nodes.stream().map(n -> statsForNode(n, randomLongBetween(0, Long.MAX_VALUE / 1000))).collect(Collectors.toList()),
List.of()
);
NodesInfoResponse responseInfo = new NodesInfoResponse(
ClusterName.DEFAULT,
nodes.stream().map(n -> infoForNode(n, randomIntBetween(1, 64))).collect(Collectors.toList()),
List.of()
);
client.respondStats(response, () -> {});
client.respondInfo(responseInfo, () -> {});
service.onClusterChanged(new ClusterChangedEvent("test", masterState, ClusterState.EMPTY_STATE));
client.assertNoResponder();
assertMatchesResponse(nodes, response, responseInfo);
ClusterState notMasterState = ClusterState.builder(masterState).nodes(masterState.nodes().withMasterNodeId(null)).build();
// client throws if called.
service.onClusterChanged(new ClusterChangedEvent("test", notMasterState, masterState));
nodes.forEach(n -> assertThat(service.snapshot().get(n), isEmpty()));
}
public void testStatsFails() {
Set<DiscoveryNode> nodes = IntStream.range(0, between(1, 10)).mapToObj(n -> newNode("test_" + n)).collect(Collectors.toSet());
ClusterState state = ClusterState.builder(ClusterName.DEFAULT).nodes(discoveryNodesBuilder(nodes, true)).metadata(metadata).build();
client.respondStats((r, listener) -> listener.onFailure(randomFrom(new IllegalStateException(), new RejectedExecutionException())));
service.onClusterChanged(new ClusterChangedEvent("test", state, ClusterState.EMPTY_STATE));
nodes.forEach(n -> assertThat(service.snapshot().get(n), isEmpty()));
NodesStatsResponse response = new NodesStatsResponse(
ClusterName.DEFAULT,
nodes.stream().map(n -> statsForNode(n, randomLongBetween(0, Long.MAX_VALUE / 1000))).collect(Collectors.toList()),
List.of()
);
NodesInfoResponse responseInfo = new NodesInfoResponse(
ClusterName.DEFAULT,
nodes.stream().map(n -> infoForNode(n, randomIntBetween(1, 64))).collect(Collectors.toList()),
List.of()
);
// implicit retry on cluster state update.
client.respondStats(response, () -> {});
client.respondInfo(responseInfo, () -> {});
service.onClusterChanged(new ClusterChangedEvent("test", state, state));
client.assertNoResponder();
}
public void testInfoFails() {
Set<DiscoveryNode> nodes = IntStream.range(0, between(1, 10)).mapToObj(n -> newNode("test_" + n)).collect(Collectors.toSet());
ClusterState state = ClusterState.builder(ClusterName.DEFAULT).nodes(discoveryNodesBuilder(nodes, true)).metadata(metadata).build();
NodesStatsResponse response = new NodesStatsResponse(
ClusterName.DEFAULT,
nodes.stream().map(n -> statsForNode(n, randomLongBetween(0, Long.MAX_VALUE / 1000))).collect(Collectors.toList()),
List.of()
);
client.respondStats(response, () -> {});
client.respondInfo((r, listener) -> listener.onFailure(randomFrom(new IllegalStateException(), new RejectedExecutionException())));
service.onClusterChanged(new ClusterChangedEvent("test", state, ClusterState.EMPTY_STATE));
nodes.forEach(n -> assertThat(service.snapshot().get(n), isEmpty()));
NodesInfoResponse responseInfo = new NodesInfoResponse(
ClusterName.DEFAULT,
nodes.stream().map(n -> infoForNode(n, randomIntBetween(1, 64))).collect(Collectors.toList()),
List.of()
);
// implicit retry on cluster state update.
client.respondStats(response, () -> {});
client.respondInfo(responseInfo, () -> {});
service.onClusterChanged(new ClusterChangedEvent("test", state, state));
client.assertNoResponder();
}
public void testRestartNode() {
Set<DiscoveryNode> nodes = IntStream.range(0, between(1, 10)).mapToObj(n -> newNode("test_" + n)).collect(Collectors.toSet());
ClusterState state = ClusterState.builder(ClusterName.DEFAULT).nodes(discoveryNodesBuilder(nodes, true)).metadata(metadata).build();
NodesStatsResponse response = new NodesStatsResponse(
ClusterName.DEFAULT,
nodes.stream().map(n -> statsForNode(n, randomLongBetween(0, Long.MAX_VALUE / 1000))).collect(Collectors.toList()),
List.of()
);
NodesInfoResponse responseInfo = new NodesInfoResponse(
ClusterName.DEFAULT,
nodes.stream().map(n -> infoForNode(n, randomIntBetween(1, 64))).collect(Collectors.toList()),
List.of()
);
client.respondStats(response, () -> {});
client.respondInfo(responseInfo, () -> {});
service.onClusterChanged(new ClusterChangedEvent("test", state, ClusterState.EMPTY_STATE));
client.assertNoResponder();
assertMatchesResponse(nodes, response, responseInfo);
Set<DiscoveryNode> restartedNodes = randomValueOtherThan(
nodes,
() -> nodes.stream().map(n -> randomBoolean() ? restartNode(n) : n).collect(Collectors.toSet())
);
ClusterState restartedState = ClusterState.builder(state).nodes(discoveryNodesBuilder(restartedNodes, true)).build();
NodesStatsResponse restartedStatsResponse = new NodesStatsResponse(
ClusterName.DEFAULT,
Sets.difference(restartedNodes, nodes)
.stream()
.map(n -> statsForNode(n, randomLongBetween(0, Long.MAX_VALUE / 1000)))
.collect(Collectors.toList()),
List.of()
);
NodesInfoResponse restartedInfoResponse = new NodesInfoResponse(
ClusterName.DEFAULT,
Sets.difference(restartedNodes, nodes).stream().map(n -> infoForNode(n, randomIntBetween(1, 64))).collect(Collectors.toList()),
List.of()
);
client.respondStats(restartedStatsResponse, () -> {});
client.respondInfo(restartedInfoResponse, () -> {});
service.onClusterChanged(new ClusterChangedEvent("test", restartedState, state));
client.assertNoResponder();
assertMatchesResponse(Sets.intersection(restartedNodes, nodes), response, responseInfo);
assertMatchesResponse(Sets.difference(restartedNodes, nodes), restartedStatsResponse, restartedInfoResponse);
Sets.difference(nodes, restartedNodes).forEach(n -> assertThat(service.snapshot().get(n), isEmpty()));
}
public void testConcurrentStateUpdate() throws Exception {
Set<DiscoveryNode> nodes = IntStream.range(0, between(1, 10)).mapToObj(n -> newNode("test_" + n)).collect(Collectors.toSet());
ClusterState state = ClusterState.builder(ClusterName.DEFAULT).nodes(discoveryNodesBuilder(nodes, true)).metadata(metadata).build();
NodesStatsResponse response = new NodesStatsResponse(
ClusterName.DEFAULT,
nodes.stream().map(n -> statsForNode(n, randomLongBetween(0, Long.MAX_VALUE / 1000))).collect(Collectors.toList()),
List.of()
);
NodesInfoResponse nodesInfoResponse = new NodesInfoResponse(
ClusterName.DEFAULT,
nodes.stream().map(n -> infoForNode(n, randomIntBetween(1, 64))).collect(Collectors.toList()),
List.of()
);
List<Thread> threads = new ArrayList<>();
client.respondStats((request, listener) -> {
CountDownLatch latch = new CountDownLatch(1);
threads.add(startThread(() -> {
safeAwait(latch);
listener.onResponse(response);
}));
threads.add(startThread(() -> {
// we do not register a new responder, so this will fail if it calls anything on client.
service.onClusterChanged(new ClusterChangedEvent("test_concurrent", state, state));
latch.countDown();
}));
});
client.respondInfo((r, l) -> l.onResponse(nodesInfoResponse));
service.onClusterChanged(new ClusterChangedEvent("test", state, ClusterState.EMPTY_STATE));
for (Thread thread : threads) {
thread.join(10000);
}
client.assertNoResponder();
threads.forEach(t -> assertThat(t.isAlive(), is(false)));
}
public void testRelevantNodes() {
Set<DiscoveryNode> nodes = IntStream.range(0, between(1, 10)).mapToObj(n -> newNode("test_" + n)).collect(Collectors.toSet());
ClusterState state = ClusterState.builder(ClusterName.DEFAULT).nodes(discoveryNodesBuilder(nodes, true)).metadata(metadata).build();
Set<DiscoveryNode> relevantNodes = service.relevantNodes(state);
assertThat(relevantNodes, equalTo(nodes));
}
private DiscoveryNodes.Builder discoveryNodesBuilder(Set<DiscoveryNode> nodes, boolean master) {
DiscoveryNodes.Builder nodesBuilder = DiscoveryNodes.builder();
final String localNodeId = nodes.isEmpty() ? null : randomFrom(nodes).getId();
nodesBuilder.localNodeId(localNodeId);
nodesBuilder.masterNodeId(master ? localNodeId : null);
nodes.forEach(nodesBuilder::add);
addIrrelevantNodes(nodesBuilder);
return nodesBuilder;
}
/**
* Add irrelevant nodes. NodeStatsClient will validate that they are not asked for.
*/
private void addIrrelevantNodes(DiscoveryNodes.Builder nodesBuilder) {
Set<Set<String>> relevantRoleSets = autoscalingMetadata.policies()
.values()
.stream()
.map(AutoscalingPolicyMetadata::policy)
.map(AutoscalingPolicy::roles)
.collect(Collectors.toSet());
IntStream.range(0, 5).mapToObj(i -> newNode("irrelevant_" + i, randomIrrelevantRoles(relevantRoleSets))).forEach(nodesBuilder::add);
}
private Set<DiscoveryNodeRole> randomIrrelevantRoles(Set<Set<String>> relevantRoleSets) {
return randomValueOtherThanMany(relevantRoleSets::contains, AutoscalingTestCase::randomRoles).stream()
.map(DiscoveryNodeRole::getRoleFromRoleName)
.collect(Collectors.toSet());
}
public void assertMatchesResponse(Set<DiscoveryNode> nodes, NodesStatsResponse response, NodesInfoResponse infoResponse) {
nodes.forEach(n -> {
assertThat(
service.snapshot().get(n),
isPresentWith(
new AutoscalingNodeInfo(
response.getNodesMap().get(n.getId()).getOs().getMem().getAdjustedTotal().getBytes(),
Processors.of(infoResponse.getNodesMap().get(n.getId()).getInfo(OsInfo.class).getFractionalAllocatedProcessors())
)
)
);
});
}
private Thread startThread(Runnable runnable) {
Thread thread = new Thread(runnable);
thread.start();
return thread;
}
private static NodeStats statsForNode(DiscoveryNode node, long memory) {
OsStats osStats = new OsStats(
randomNonNegativeLong(),
new OsStats.Cpu(randomShort(), null, randomInt()),
new OsStats.Mem(memory, randomLongBetween(0, memory), randomLongBetween(0, memory)),
new OsStats.Swap(randomNonNegativeLong(), randomNonNegativeLong()),
null
);
return new NodeStats(
node,
randomNonNegativeLong(),
null,
osStats,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
);
}
private static org.elasticsearch.action.admin.cluster.node.info.NodeInfo infoForNode(DiscoveryNode node, int processors) {
OsInfo osInfo = new OsInfo(randomLong(), processors, Processors.of((double) processors), null, null, null, null);
return new org.elasticsearch.action.admin.cluster.node.info.NodeInfo(
Build.current().version(),
new CompatibilityVersions(TransportVersion.current(), Map.of()),
IndexVersion.current(),
Map.of(),
Build.current(),
node,
null,
osInfo,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
);
}
private
|
AutoscalingNodesInfoServiceTests
|
java
|
spring-projects__spring-boot
|
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/graphql/transports/rsocket/RSocketGraphQlClientExample.java
|
{
"start": 912,
"end": 1471
}
|
class ____ {
private final RSocketGraphQlClient graphQlClient;
public RSocketGraphQlClientExample(RSocketGraphQlClient.Builder<?> builder) {
this.graphQlClient = builder.tcp("example.spring.io", 8181).route("graphql").build();
}
// end::builder[]
public void rsocketOverTcp() {
// tag::request[]
Mono<Book> book = this.graphQlClient.document("{ bookById(id: \"book-1\"){ id name pageCount author } }")
.retrieve("bookById")
.toEntity(Book.class);
// end::request[]
book.block(Duration.ofSeconds(5));
}
static
|
RSocketGraphQlClientExample
|
java
|
spring-projects__spring-boot
|
module/spring-boot-jackson/src/test/java/org/springframework/boot/jackson/autoconfigure/jsontest/app/ExampleJacksonComponent.java
|
{
"start": 1815,
"end": 2310
}
|
class ____ extends ObjectValueDeserializer<ExampleCustomObject> {
@Override
protected ExampleCustomObject deserializeObject(JsonParser jsonParser, DeserializationContext context,
JsonNode tree) {
String value = nullSafeValue(tree.get("value"), String.class);
Date date = nullSafeValue(tree.get("date"), Long.class, Date::new);
UUID uuid = nullSafeValue(tree.get("uuid"), String.class, UUID::fromString);
return new ExampleCustomObject(value, date, uuid);
}
}
}
|
Deserializer
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableReplayEagerTruncateTest.java
|
{
"start": 1853,
"end": 25738
}
|
class ____ extends RxJavaTest {
@Test
public void bufferedReplay() {
PublishProcessor<Integer> source = PublishProcessor.create();
ConnectableFlowable<Integer> cf = source.replay(3, true);
cf.connect();
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
cf.subscribe(subscriber1);
source.onNext(1);
source.onNext(2);
source.onNext(3);
inOrder.verify(subscriber1, times(1)).onNext(1);
inOrder.verify(subscriber1, times(1)).onNext(2);
inOrder.verify(subscriber1, times(1)).onNext(3);
source.onNext(4);
source.onComplete();
inOrder.verify(subscriber1, times(1)).onNext(4);
inOrder.verify(subscriber1, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onError(any(Throwable.class));
}
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
cf.subscribe(subscriber1);
inOrder.verify(subscriber1, times(1)).onNext(2);
inOrder.verify(subscriber1, times(1)).onNext(3);
inOrder.verify(subscriber1, times(1)).onNext(4);
inOrder.verify(subscriber1, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onError(any(Throwable.class));
}
}
@Test
public void bufferedWindowReplay() {
PublishProcessor<Integer> source = PublishProcessor.create();
TestScheduler scheduler = new TestScheduler();
ConnectableFlowable<Integer> cf = source.replay(3, 100, TimeUnit.MILLISECONDS, scheduler, true);
cf.connect();
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
cf.subscribe(subscriber1);
source.onNext(1);
scheduler.advanceTimeBy(10, TimeUnit.MILLISECONDS);
source.onNext(2);
scheduler.advanceTimeBy(10, TimeUnit.MILLISECONDS);
source.onNext(3);
scheduler.advanceTimeBy(10, TimeUnit.MILLISECONDS);
inOrder.verify(subscriber1, times(1)).onNext(1);
inOrder.verify(subscriber1, times(1)).onNext(2);
inOrder.verify(subscriber1, times(1)).onNext(3);
source.onNext(4);
source.onNext(5);
scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS);
inOrder.verify(subscriber1, times(1)).onNext(4);
inOrder.verify(subscriber1, times(1)).onNext(5);
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onError(any(Throwable.class));
}
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
cf.subscribe(subscriber1);
inOrder.verify(subscriber1, times(1)).onNext(4);
inOrder.verify(subscriber1, times(1)).onNext(5);
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onError(any(Throwable.class));
}
}
@Test
public void windowedReplay() {
TestScheduler scheduler = new TestScheduler();
PublishProcessor<Integer> source = PublishProcessor.create();
ConnectableFlowable<Integer> cf = source.replay(100, TimeUnit.MILLISECONDS, scheduler, true);
cf.connect();
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
cf.subscribe(subscriber1);
source.onNext(1);
scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS);
source.onNext(2);
scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS);
source.onNext(3);
scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS);
source.onComplete();
scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS);
inOrder.verify(subscriber1, times(1)).onNext(1);
inOrder.verify(subscriber1, times(1)).onNext(2);
inOrder.verify(subscriber1, times(1)).onNext(3);
inOrder.verify(subscriber1, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onError(any(Throwable.class));
}
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
cf.subscribe(subscriber1);
inOrder.verify(subscriber1, never()).onNext(3);
inOrder.verify(subscriber1, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onError(any(Throwable.class));
}
}
@Test
public void replaySelector() {
final Function<Integer, Integer> dbl = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer t1) {
return t1 * 2;
}
};
Function<Flowable<Integer>, Flowable<Integer>> selector = new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> t1) {
return t1.map(dbl);
}
};
PublishProcessor<Integer> source = PublishProcessor.create();
Flowable<Integer> co = source.replay(selector);
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
co.subscribe(subscriber1);
source.onNext(1);
source.onNext(2);
source.onNext(3);
inOrder.verify(subscriber1, times(1)).onNext(2);
inOrder.verify(subscriber1, times(1)).onNext(4);
inOrder.verify(subscriber1, times(1)).onNext(6);
source.onNext(4);
source.onComplete();
inOrder.verify(subscriber1, times(1)).onNext(8);
inOrder.verify(subscriber1, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onError(any(Throwable.class));
}
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
co.subscribe(subscriber1);
inOrder.verify(subscriber1, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onError(any(Throwable.class));
}
}
@Test
public void bufferedReplaySelector() {
final Function<Integer, Integer> dbl = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer t1) {
return t1 * 2;
}
};
Function<Flowable<Integer>, Flowable<Integer>> selector = new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> t1) {
return t1.map(dbl);
}
};
PublishProcessor<Integer> source = PublishProcessor.create();
Flowable<Integer> co = source.replay(selector, 3, true);
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
co.subscribe(subscriber1);
source.onNext(1);
source.onNext(2);
source.onNext(3);
inOrder.verify(subscriber1, times(1)).onNext(2);
inOrder.verify(subscriber1, times(1)).onNext(4);
inOrder.verify(subscriber1, times(1)).onNext(6);
source.onNext(4);
source.onComplete();
inOrder.verify(subscriber1, times(1)).onNext(8);
inOrder.verify(subscriber1, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onError(any(Throwable.class));
}
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
co.subscribe(subscriber1);
inOrder.verify(subscriber1, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onError(any(Throwable.class));
}
}
@Test
public void windowedReplaySelector() {
final Function<Integer, Integer> dbl = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer t1) {
return t1 * 2;
}
};
Function<Flowable<Integer>, Flowable<Integer>> selector = new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> t1) {
return t1.map(dbl);
}
};
TestScheduler scheduler = new TestScheduler();
PublishProcessor<Integer> source = PublishProcessor.create();
Flowable<Integer> co = source.replay(selector, 100, TimeUnit.MILLISECONDS, scheduler, true);
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
co.subscribe(subscriber1);
source.onNext(1);
scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS);
source.onNext(2);
scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS);
source.onNext(3);
scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS);
source.onComplete();
scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS);
inOrder.verify(subscriber1, times(1)).onNext(2);
inOrder.verify(subscriber1, times(1)).onNext(4);
inOrder.verify(subscriber1, times(1)).onNext(6);
inOrder.verify(subscriber1, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onError(any(Throwable.class));
}
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
co.subscribe(subscriber1);
inOrder.verify(subscriber1, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onError(any(Throwable.class));
}
}
@Test
public void bufferedReplayError() {
PublishProcessor<Integer> source = PublishProcessor.create();
ConnectableFlowable<Integer> cf = source.replay(3, true);
cf.connect();
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
cf.subscribe(subscriber1);
source.onNext(1);
source.onNext(2);
source.onNext(3);
inOrder.verify(subscriber1, times(1)).onNext(1);
inOrder.verify(subscriber1, times(1)).onNext(2);
inOrder.verify(subscriber1, times(1)).onNext(3);
source.onNext(4);
source.onError(new RuntimeException("Forced failure"));
inOrder.verify(subscriber1, times(1)).onNext(4);
inOrder.verify(subscriber1, times(1)).onError(any(RuntimeException.class));
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onComplete();
}
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
cf.subscribe(subscriber1);
inOrder.verify(subscriber1, times(1)).onNext(2);
inOrder.verify(subscriber1, times(1)).onNext(3);
inOrder.verify(subscriber1, times(1)).onNext(4);
inOrder.verify(subscriber1, times(1)).onError(any(RuntimeException.class));
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onComplete();
}
}
@Test
public void windowedReplayError() {
TestScheduler scheduler = new TestScheduler();
PublishProcessor<Integer> source = PublishProcessor.create();
ConnectableFlowable<Integer> cf = source.replay(100, TimeUnit.MILLISECONDS, scheduler, true);
cf.connect();
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
cf.subscribe(subscriber1);
source.onNext(1);
scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS);
source.onNext(2);
scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS);
source.onNext(3);
scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS);
source.onError(new RuntimeException("Forced failure"));
scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS);
inOrder.verify(subscriber1, times(1)).onNext(1);
inOrder.verify(subscriber1, times(1)).onNext(2);
inOrder.verify(subscriber1, times(1)).onNext(3);
inOrder.verify(subscriber1, times(1)).onError(any(RuntimeException.class));
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onComplete();
}
{
Subscriber<Object> subscriber1 = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber1);
cf.subscribe(subscriber1);
inOrder.verify(subscriber1, never()).onNext(3);
inOrder.verify(subscriber1, times(1)).onError(any(RuntimeException.class));
inOrder.verifyNoMoreInteractions();
verify(subscriber1, never()).onComplete();
}
}
@Test
public void synchronousDisconnect() {
final AtomicInteger effectCounter = new AtomicInteger();
Flowable<Integer> source = Flowable.just(1, 2, 3, 4)
.doOnNext(new Consumer<Integer>() {
@Override
public void accept(Integer v) {
effectCounter.incrementAndGet();
System.out.println("Sideeffect #" + v);
}
});
Flowable<Integer> result = source.replay(
new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> f) {
return f.take(2);
}
});
for (int i = 1; i < 3; i++) {
effectCounter.set(0);
System.out.printf("- %d -%n", i);
result.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer t1) {
System.out.println(t1);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable t1) {
t1.printStackTrace();
}
},
new Action() {
@Override
public void run() {
System.out.println("Done");
}
});
assertEquals(2, effectCounter.get());
}
}
/*
* test the basic expectation of OperatorMulticast via replay
*/
@SuppressWarnings("unchecked")
@Test
public void issue2191_UnsubscribeSource() throws Throwable {
// setup mocks
Consumer<Integer> sourceNext = mock(Consumer.class);
Action sourceCompleted = mock(Action.class);
Action sourceUnsubscribed = mock(Action.class);
Subscriber<Integer> spiedSubscriberBeforeConnect = TestHelper.mockSubscriber();
Subscriber<Integer> spiedSubscriberAfterConnect = TestHelper.mockSubscriber();
// Flowable under test
Flowable<Integer> source = Flowable.just(1, 2);
ConnectableFlowable<Integer> replay = source
.doOnNext(sourceNext)
.doOnCancel(sourceUnsubscribed)
.doOnComplete(sourceCompleted)
.replay();
replay.subscribe(spiedSubscriberBeforeConnect);
replay.subscribe(spiedSubscriberBeforeConnect);
replay.connect();
replay.subscribe(spiedSubscriberAfterConnect);
replay.subscribe(spiedSubscriberAfterConnect);
verify(spiedSubscriberBeforeConnect, times(2)).onSubscribe((Subscription)any());
verify(spiedSubscriberAfterConnect, times(2)).onSubscribe((Subscription)any());
// verify interactions
verify(sourceNext, times(1)).accept(1);
verify(sourceNext, times(1)).accept(2);
verify(sourceCompleted, times(1)).run();
verifyObserverMock(spiedSubscriberBeforeConnect, 2, 4);
verifyObserverMock(spiedSubscriberAfterConnect, 2, 4);
verify(sourceUnsubscribed, never()).run();
verifyNoMoreInteractions(sourceNext);
verifyNoMoreInteractions(sourceCompleted);
verifyNoMoreInteractions(sourceUnsubscribed);
verifyNoMoreInteractions(spiedSubscriberBeforeConnect);
verifyNoMoreInteractions(spiedSubscriberAfterConnect);
}
/**
* Specifically test interaction with a Scheduler with subscribeOn.
*
* @throws Throwable functional interfaces declare throws Exception
*/
@SuppressWarnings("unchecked")
@Test
public void issue2191_SchedulerUnsubscribe() throws Throwable {
// setup mocks
Consumer<Integer> sourceNext = mock(Consumer.class);
Action sourceCompleted = mock(Action.class);
Action sourceUnsubscribed = mock(Action.class);
final Scheduler mockScheduler = mock(Scheduler.class);
final Disposable mockSubscription = mock(Disposable.class);
Worker spiedWorker = workerSpy(mockSubscription);
Subscriber<Integer> mockObserverBeforeConnect = TestHelper.mockSubscriber();
Subscriber<Integer> mockObserverAfterConnect = TestHelper.mockSubscriber();
when(mockScheduler.createWorker()).thenReturn(spiedWorker);
// Flowable under test
ConnectableFlowable<Integer> replay = Flowable.just(1, 2, 3)
.doOnNext(sourceNext)
.doOnCancel(sourceUnsubscribed)
.doOnComplete(sourceCompleted)
.subscribeOn(mockScheduler).replay();
replay.subscribe(mockObserverBeforeConnect);
replay.subscribe(mockObserverBeforeConnect);
replay.connect();
replay.subscribe(mockObserverAfterConnect);
replay.subscribe(mockObserverAfterConnect);
verify(mockObserverBeforeConnect, times(2)).onSubscribe((Subscription)any());
verify(mockObserverAfterConnect, times(2)).onSubscribe((Subscription)any());
// verify interactions
verify(sourceNext, times(1)).accept(1);
verify(sourceNext, times(1)).accept(2);
verify(sourceNext, times(1)).accept(3);
verify(sourceCompleted, times(1)).run();
verify(mockScheduler, times(1)).createWorker();
verify(spiedWorker, times(1)).schedule((Runnable)notNull());
verifyObserverMock(mockObserverBeforeConnect, 2, 6);
verifyObserverMock(mockObserverAfterConnect, 2, 6);
// FIXME publish calls cancel too
verify(spiedWorker, times(1)).dispose();
verify(sourceUnsubscribed, never()).run();
verifyNoMoreInteractions(sourceNext);
verifyNoMoreInteractions(sourceCompleted);
verifyNoMoreInteractions(sourceUnsubscribed);
verifyNoMoreInteractions(spiedWorker);
verifyNoMoreInteractions(mockSubscription);
verifyNoMoreInteractions(mockScheduler);
verifyNoMoreInteractions(mockObserverBeforeConnect);
verifyNoMoreInteractions(mockObserverAfterConnect);
}
/**
* Specifically test interaction with a Scheduler with subscribeOn.
*
* @throws Throwable functional interfaces declare throws Exception
*/
@SuppressWarnings("unchecked")
@Test
public void issue2191_SchedulerUnsubscribeOnError() throws Throwable {
// setup mocks
Consumer<Integer> sourceNext = mock(Consumer.class);
Action sourceCompleted = mock(Action.class);
Consumer<Throwable> sourceError = mock(Consumer.class);
Action sourceUnsubscribed = mock(Action.class);
final Scheduler mockScheduler = mock(Scheduler.class);
final Disposable mockSubscription = mock(Disposable.class);
Worker spiedWorker = workerSpy(mockSubscription);
Subscriber<Integer> mockObserverBeforeConnect = TestHelper.mockSubscriber();
Subscriber<Integer> mockObserverAfterConnect = TestHelper.mockSubscriber();
when(mockScheduler.createWorker()).thenReturn(spiedWorker);
// Flowable under test
Function<Integer, Integer> mockFunc = mock(Function.class);
IllegalArgumentException illegalArgumentException = new IllegalArgumentException();
when(mockFunc.apply(1)).thenReturn(1);
when(mockFunc.apply(2)).thenThrow(illegalArgumentException);
ConnectableFlowable<Integer> replay = Flowable.just(1, 2, 3).map(mockFunc)
.doOnNext(sourceNext)
.doOnCancel(sourceUnsubscribed)
.doOnComplete(sourceCompleted)
.doOnError(sourceError)
.subscribeOn(mockScheduler).replay();
replay.subscribe(mockObserverBeforeConnect);
replay.subscribe(mockObserverBeforeConnect);
replay.connect();
replay.subscribe(mockObserverAfterConnect);
replay.subscribe(mockObserverAfterConnect);
verify(mockObserverBeforeConnect, times(2)).onSubscribe((Subscription)any());
verify(mockObserverAfterConnect, times(2)).onSubscribe((Subscription)any());
// verify interactions
verify(mockScheduler, times(1)).createWorker();
verify(spiedWorker, times(1)).schedule((Runnable)notNull());
verify(sourceNext, times(1)).accept(1);
verify(sourceError, times(1)).accept(illegalArgumentException);
verifyObserver(mockObserverBeforeConnect, 2, 2, illegalArgumentException);
verifyObserver(mockObserverAfterConnect, 2, 2, illegalArgumentException);
// FIXME publish also calls cancel
verify(spiedWorker, times(1)).dispose();
verify(sourceUnsubscribed, never()).run();
verifyNoMoreInteractions(sourceNext);
verifyNoMoreInteractions(sourceCompleted);
verifyNoMoreInteractions(sourceError);
verifyNoMoreInteractions(sourceUnsubscribed);
verifyNoMoreInteractions(spiedWorker);
verifyNoMoreInteractions(mockSubscription);
verifyNoMoreInteractions(mockScheduler);
verifyNoMoreInteractions(mockObserverBeforeConnect);
verifyNoMoreInteractions(mockObserverAfterConnect);
}
private static void verifyObserverMock(Subscriber<Integer> mock, int numSubscriptions, int numItemsExpected) {
verify(mock, times(numItemsExpected)).onNext((Integer) notNull());
verify(mock, times(numSubscriptions)).onComplete();
verifyNoMoreInteractions(mock);
}
private static void verifyObserver(Subscriber<Integer> mock, int numSubscriptions, int numItemsExpected, Throwable error) {
verify(mock, times(numItemsExpected)).onNext((Integer) notNull());
verify(mock, times(numSubscriptions)).onError(error);
verifyNoMoreInteractions(mock);
}
public static Worker workerSpy(final Disposable mockDisposable) {
return spy(new InprocessWorker(mockDisposable));
}
private static
|
FlowableReplayEagerTruncateTest
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableScalarXMapTest.java
|
{
"start": 1754,
"end": 2111
}
|
class ____ implements ObservableSource<Integer>, Supplier<Integer> {
@Override
public void subscribe(Observer<? super Integer> observer) {
EmptyDisposable.complete(observer);
}
@Override
public Integer get() throws Exception {
return null;
}
}
static final
|
EmptyCallablePublisher
|
java
|
apache__maven
|
api/maven-api-core/src/main/java/org/apache/maven/api/VersionRange.java
|
{
"start": 2178,
"end": 2419
}
|
interface ____ {
/**
* The bounding version.
*/
Version getVersion();
/**
* Returns {@code true} if version is included of the range.
*/
boolean isInclusive();
}
}
|
Boundary
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/DistinctVarargsCheckerTest.java
|
{
"start": 1691,
"end": 2794
}
|
class ____ {
void testFunction() {
ListenableFuture firstFuture = null, secondFuture = null;
// BUG: Diagnostic contains: DistinctVarargsChecker
Futures.whenAllSucceed(firstFuture, firstFuture);
// BUG: Diagnostic contains: DistinctVarargsChecker
Futures.whenAllSucceed(firstFuture, firstFuture, secondFuture);
// BUG: Diagnostic contains: DistinctVarargsChecker
Futures.whenAllComplete(firstFuture, firstFuture);
// BUG: Diagnostic contains: DistinctVarargsChecker
Futures.whenAllComplete(firstFuture, firstFuture, secondFuture);
}
}
""")
.doTest();
}
@Test
public void distinctVarargsCheckerdifferentVariableInFuturesVaragsMethods_shouldNotFlag() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
public
|
Test
|
java
|
reactor__reactor-core
|
reactor-core/src/main/java/reactor/core/publisher/ContextPropagation.java
|
{
"start": 13653,
"end": 15980
}
|
class ____<T> extends AbstractQueue<T> {
static final String NOT_SUPPORTED_MESSAGE = "ContextQueue wrapper is intended " +
"for use with instances returned by Queues class. Iterator based " +
"methods are usually unsupported.";
final Queue<Envelope<T>> envelopeQueue;
boolean cleanOnNull;
boolean hasPrevious = false;
@Nullable Thread lastReader;
ContextSnapshot.@Nullable Scope scope;
@SuppressWarnings({"unchecked", "rawtypes"})
ContextQueue(Queue<?> queue) {
this.envelopeQueue = (Queue) queue;
}
@Override
public int size() {
return envelopeQueue.size();
}
@Override
public boolean offer(T o) {
ContextSnapshot contextSnapshot = captureThreadLocals();
return envelopeQueue.offer(new Envelope<>(o, contextSnapshot));
}
@Override
public @Nullable T poll() {
Envelope<T> envelope = envelopeQueue.poll();
if (envelope == null) {
if (cleanOnNull && scope != null) {
// clear thread-locals if they were just restored
scope.close();
}
cleanOnNull = true;
lastReader = Thread.currentThread();
hasPrevious = false;
return null;
}
restoreTheContext(envelope);
hasPrevious = true;
return envelope.body;
}
private void restoreTheContext(Envelope<T> envelope) {
ContextSnapshot contextSnapshot = envelope.contextSnapshot;
// tries to read existing Thread for existing ThreadLocals
ContextSnapshot currentContextSnapshot = captureThreadLocals();
if (!contextSnapshot.equals(currentContextSnapshot)) {
if (!hasPrevious || !Thread.currentThread().equals(this.lastReader)) {
// means context was restored form the envelope,
// thus it has to be cleared
cleanOnNull = true;
lastReader = Thread.currentThread();
}
scope = contextSnapshot.setThreadLocals();
}
else if (!hasPrevious || !Thread.currentThread().equals(this.lastReader)) {
// means same context was already available, no need to clean anything
cleanOnNull = false;
lastReader = Thread.currentThread();
}
}
@Override
public @Nullable T peek() {
Envelope<T> envelope = envelopeQueue.peek();
return envelope == null ? null : envelope.body;
}
@Override
public Iterator<T> iterator() {
throw new UnsupportedOperationException(NOT_SUPPORTED_MESSAGE);
}
}
static
|
ContextQueue
|
java
|
spring-projects__spring-security
|
core/src/test/java/org/springframework/security/core/annotation/UniqueSecurityAnnotationScannerTests.java
|
{
"start": 16935,
"end": 17067
}
|
interface ____ {
@PreAuthorize("four")
String method();
}
@PreAuthorize("five")
private static
|
AlsoAnnotationOnInterfaceMethod
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorTests.java
|
{
"start": 1225,
"end": 5810
}
|
class ____ {
private final Context context = mock(Context.class);
private final StaticMessageSource messageSource = new StaticMessageSource();
private final MessageSourceMessageInterpolator interpolator = new MessageSourceMessageInterpolator(
this.messageSource, new IdentityMessageInterpolator());
@Test
void interpolateShouldReplaceParameters() {
this.messageSource.addMessage("foo", Locale.getDefault(), "fooValue");
this.messageSource.addMessage("bar", Locale.getDefault(), "");
assertThat(this.interpolator.interpolate("{foo}{bar}", this.context)).isEqualTo("fooValue");
}
@Test
void interpolateWhenParametersAreUnknownShouldLeaveThemUnchanged() {
this.messageSource.addMessage("top", Locale.getDefault(), "{child}+{child}");
assertThat(this.interpolator.interpolate("{foo}{top}{bar}", this.context))
.isEqualTo("{foo}{child}+{child}{bar}");
}
@Test
void interpolateWhenParametersAreUnknownUsingCodeAsDefaultShouldLeaveThemUnchanged() {
this.messageSource.setUseCodeAsDefaultMessage(true);
this.messageSource.addMessage("top", Locale.getDefault(), "{child}+{child}");
assertThat(this.interpolator.interpolate("{foo}{top}{bar}", this.context))
.isEqualTo("{foo}{child}+{child}{bar}");
}
@Test
void interpolateShouldReplaceParameterThatReferencesAMessageThatMatchesItsCode() {
this.messageSource.addMessage("foo", Locale.getDefault(), "foo");
assertThat(this.interpolator.interpolate("{foo}", this.context)).isEqualTo("foo");
}
@Test
void interpolateUsingCodeAsDefaultShouldReplaceParameterThatReferencesAMessageThatMatchesItsCode() {
this.messageSource.setUseCodeAsDefaultMessage(true);
this.messageSource.addMessage("foo", Locale.getDefault(), "foo");
assertThat(this.interpolator.interpolate("{foo}", this.context)).isEqualTo("foo");
}
@Test
void interpolateWhenParametersAreNestedShouldFullyReplaceAllParameters() {
this.messageSource.addMessage("top", Locale.getDefault(), "{child}+{child}");
this.messageSource.addMessage("child", Locale.getDefault(), "{{differentiator}.grandchild}");
this.messageSource.addMessage("differentiator", Locale.getDefault(), "first");
this.messageSource.addMessage("first.grandchild", Locale.getDefault(), "actualValue");
assertThat(this.interpolator.interpolate("{top}", this.context)).isEqualTo("actualValue+actualValue");
}
@Test
void interpolateWhenParameterBracesAreUnbalancedShouldLeaveThemUnchanged() {
this.messageSource.addMessage("top", Locale.getDefault(), "topValue");
assertThat(this.interpolator.interpolate("\\{top}", this.context)).isEqualTo("\\{top}");
assertThat(this.interpolator.interpolate("{top\\}", this.context)).isEqualTo("{top\\}");
assertThat(this.interpolator.interpolate("{{top}", this.context)).isEqualTo("{{top}");
assertThat(this.interpolator.interpolate("{top}}", this.context)).isEqualTo("topValue}");
}
@Test
void interpolateWhenBracesAreEscapedShouldIgnore() {
this.messageSource.addMessage("foo", Locale.getDefault(), "fooValue");
this.messageSource.addMessage("bar", Locale.getDefault(), "\\{foo}");
this.messageSource.addMessage("bazz\\}", Locale.getDefault(), "bazzValue");
assertThat(this.interpolator.interpolate("{foo}", this.context)).isEqualTo("fooValue");
assertThat(this.interpolator.interpolate("{foo}\\a", this.context)).isEqualTo("fooValue\\a");
assertThat(this.interpolator.interpolate("\\\\{foo}", this.context)).isEqualTo("\\\\fooValue");
assertThat(this.interpolator.interpolate("\\\\\\{foo}", this.context)).isEqualTo("\\\\\\{foo}");
assertThat(this.interpolator.interpolate("\\{foo}", this.context)).isEqualTo("\\{foo}");
assertThat(this.interpolator.interpolate("{foo\\}", this.context)).isEqualTo("{foo\\}");
assertThat(this.interpolator.interpolate("\\{foo\\}", this.context)).isEqualTo("\\{foo\\}");
assertThat(this.interpolator.interpolate("{foo}\\", this.context)).isEqualTo("fooValue\\");
assertThat(this.interpolator.interpolate("{bar}", this.context)).isEqualTo("\\{foo}");
assertThat(this.interpolator.interpolate("{bazz\\}}", this.context)).isEqualTo("bazzValue");
}
@Test
void interpolateWhenParametersContainACycleShouldThrow() {
this.messageSource.addMessage("a", Locale.getDefault(), "{b}");
this.messageSource.addMessage("b", Locale.getDefault(), "{c}");
this.messageSource.addMessage("c", Locale.getDefault(), "{a}");
assertThatIllegalArgumentException().isThrownBy(() -> this.interpolator.interpolate("{a}", this.context))
.withMessage("Circular reference '{a -> b -> c -> a}'");
}
private static final
|
MessageSourceMessageInterpolatorTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/type/OracleNamedEnumTest.java
|
{
"start": 1905,
"end": 2002
}
|
enum ____ not exported");
}
if (!namedOrdinalEnumFound) {
fail("named ordinal
|
type
|
java
|
netty__netty
|
testsuite-native-image/src/main/java/io/netty/testsuite/svm/HttpNativeClient.java
|
{
"start": 925,
"end": 1622
}
|
class ____ {
private final int port;
private final EventLoopGroup group;
private final Class<? extends Channel> channelType;
public HttpNativeClient(int port, EventLoopGroup group, Class<? extends Channel> channelType) {
this.port = port;
this.group = group;
this.channelType = channelType;
}
public Channel initClient() throws InterruptedException {
Channel clientChannel = new Bootstrap()
.group(group)
.channel(channelType)
.handler(new HttpClientCodec())
.connect("localhost", port)
.sync().channel();
return clientChannel;
}
}
|
HttpNativeClient
|
java
|
apache__camel
|
core/camel-management/src/main/java/org/apache/camel/management/mbean/ManagedRouteController.java
|
{
"start": 1217,
"end": 2334
}
|
class ____ extends ManagedService implements ManagedRouteControllerMBean {
private final RouteController controller;
public ManagedRouteController(CamelContext context, RouteController controller) {
super(context, controller);
this.controller = controller;
}
public RouteController getRouteController() {
return controller;
}
@Override
public boolean isStartingRoutes() {
return controller.isStartingRoutes();
}
@Override
public boolean isHasUnhealthyRoutes() {
return controller.hasUnhealthyRoutes();
}
@Override
public Collection<String> getControlledRoutes() {
if (controller != null) {
return controller.getControlledRoutes().stream()
.map(Route::getId)
.toList();
}
return Collections.emptyList();
}
@Override
public String getRouteStartupLoggingLevel() {
if (controller != null) {
return controller.getLoggingLevel().name();
} else {
return null;
}
}
}
|
ManagedRouteController
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/engine/creation/internal/SessionCreationOptions.java
|
{
"start": 714,
"end": 1522
}
|
interface ____ {
boolean shouldAutoJoinTransactions();
FlushMode getInitialSessionFlushMode();
boolean isSubselectFetchEnabled();
int getDefaultBatchFetchSize();
boolean shouldAutoClose();
boolean shouldAutoClear();
Connection getConnection();
Interceptor getInterceptor();
StatementInspector getStatementInspector();
PhysicalConnectionHandlingMode getPhysicalConnectionHandlingMode();
Object getTenantIdentifierValue();
boolean isReadOnly();
CacheMode getInitialCacheMode();
boolean isIdentifierRollbackEnabled();
TimeZone getJdbcTimeZone();
/**
* @return the full list of SessionEventListener if this was customized,
* or null if this Session is being created with the default list.
*/
List<SessionEventListener> getCustomSessionEventListeners();
}
|
SessionCreationOptions
|
java
|
apache__flink
|
flink-formats/flink-compress/src/main/java/org/apache/flink/formats/compress/writers/NoCompressionBulkWriter.java
|
{
"start": 1430,
"end": 2121
}
|
class ____<T> implements BulkWriter<T> {
private final Extractor<T> extractor;
private final FSDataOutputStream outputStream;
public NoCompressionBulkWriter(FSDataOutputStream outputStream, Extractor<T> extractor) {
this.outputStream = checkNotNull(outputStream);
this.extractor = checkNotNull(extractor);
}
@Override
public void addElement(T element) throws IOException {
outputStream.write(extractor.extract(element));
}
@Override
public void flush() throws IOException {
outputStream.flush();
}
@Override
public void finish() throws IOException {
outputStream.sync();
}
}
|
NoCompressionBulkWriter
|
java
|
spring-projects__spring-framework
|
integration-tests/src/test/java/org/springframework/cache/annotation/EnableCachingIntegrationTests.java
|
{
"start": 1627,
"end": 3009
}
|
class ____ {
@Test
void repositoryIsClassBasedCacheProxy() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(Config.class, ProxyTargetClassCachingConfig.class);
ctx.refresh();
assertCacheProxying(ctx);
assertThat(AopUtils.isCglibProxy(ctx.getBean(FooRepository.class))).isTrue();
}
@Test
void repositoryUsesAspectJAdviceMode() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(Config.class, AspectJCacheConfig.class);
// this test is a bit fragile, but gets the job done, proving that an
// attempt was made to look up the AJ aspect. It's due to classpath issues
// in integration-tests that it's not found.
assertThatException().isThrownBy(ctx::refresh)
.withMessageContaining("AspectJCachingConfiguration");
}
private void assertCacheProxying(AnnotationConfigApplicationContext ctx) {
FooRepository repo = ctx.getBean(FooRepository.class);
assertThat(isCacheProxy(repo)).isTrue();
}
private boolean isCacheProxy(FooRepository repo) {
if (AopUtils.isAopProxy(repo)) {
for (Advisor advisor : ((Advised)repo).getAdvisors()) {
if (advisor instanceof BeanFactoryCacheOperationSourceAdvisor) {
return true;
}
}
}
return false;
}
@Configuration
@EnableCaching(proxyTargetClass=true)
static
|
EnableCachingIntegrationTests
|
java
|
spring-projects__spring-boot
|
build-plugin/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java
|
{
"start": 1409,
"end": 3213
}
|
class ____ {
@SuppressWarnings("NullAway.Init")
GradleBuild gradleBuild;
@TestTemplate
void noBootWarTaskWithoutWarPluginApplied() {
assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootWar").getOutput())
.contains("bootWar exists = false");
}
@TestTemplate
void applyingWarPluginCreatesBootWarTask() {
assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootWar", "-PapplyWarPlugin").getOutput())
.contains("bootWar exists = true");
}
@TestTemplate
void assembleRunsBootWarAndWar() {
BuildResult result = this.gradleBuild.build("assemble");
BuildTask bootWar = result.task(":bootWar");
assertThat(bootWar).isNotNull();
assertThat(bootWar.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
BuildTask war = result.task(":war");
assertThat(war).isNotNull();
assertThat(war.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
File buildLibs = new File(this.gradleBuild.getProjectDir(), "build/libs");
List<File> expected = new ArrayList<>();
expected.add(new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".war"));
expected.add(new File(buildLibs, this.gradleBuild.getProjectDir().getName() + "-plain.war"));
if (this.gradleBuild.gradleVersionIsAtLeast("9.0-milestone-2")) {
expected.add(new File(buildLibs, this.gradleBuild.getProjectDir().getName() + "-plain.jar"));
}
assertThat(buildLibs.listFiles()).containsExactlyInAnyOrderElementsOf(expected);
}
@TestTemplate
void errorMessageIsHelpfulWhenMainClassCannotBeResolved() {
BuildResult result = this.gradleBuild.buildAndFail("build", "-PapplyWarPlugin");
BuildTask task = result.task(":bootWar");
assertThat(task).isNotNull();
assertThat(task.getOutcome()).isEqualTo(TaskOutcome.FAILED);
assertThat(result.getOutput()).contains("Main
|
WarPluginActionIntegrationTests
|
java
|
apache__kafka
|
streams/src/main/java/org/apache/kafka/streams/TopologyDescription.java
|
{
"start": 6329,
"end": 6834
}
|
class ____ get the topic name
*/
@SuppressWarnings("unused")
TopicNameExtractor<?, ?> topicNameExtractor();
}
/**
* All sub-topologies of the represented topology.
* @return set of all sub-topologies
*/
@SuppressWarnings("unused")
Set<Subtopology> subtopologies();
/**
* All global stores of the represented topology.
* @return set of all global stores
*/
@SuppressWarnings("unused")
Set<GlobalStore> globalStores();
}
|
used
|
java
|
google__auto
|
common/src/main/java/com/google/auto/common/SimpleTypeAnnotationValue.java
|
{
"start": 1142,
"end": 2356
}
|
class ____ implements AnnotationValue {
private final TypeMirror value;
private SimpleTypeAnnotationValue(TypeMirror value) {
checkArgument(
value.getKind().isPrimitive()
|| value.getKind().equals(DECLARED)
|| value.getKind().equals(ARRAY),
"value must be a primitive, array, or declared type, but was %s (%s)",
value.getKind(),
value);
if (value.getKind().equals(DECLARED)) {
checkArgument(
MoreTypes.asDeclared(value).getTypeArguments().isEmpty(),
"value must not be a parameterized type: %s",
value);
}
this.value = value;
}
/**
* An object representing an annotation value instance.
*
* @param value a primitive, array, or non-parameterized declared type
*/
public static AnnotationValue of(TypeMirror value) {
return new SimpleTypeAnnotationValue(value);
}
@Override
public TypeMirror getValue() {
return value;
}
@Override
public String toString() {
return value + ".class";
}
@Override
public <R, P> R accept(AnnotationValueVisitor<R, P> visitor, P parameter) {
return visitor.visitType(getValue(), parameter);
}
}
|
SimpleTypeAnnotationValue
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/error/future/ShouldNotBeDone.java
|
{
"start": 809,
"end": 1187
}
|
class ____ extends BasicErrorMessageFactory {
private static final String SHOULD_NOT_BE_DONE = "%nExpecting%n <%s>%nnot to be done.%n" + Warning.WARNING;
public static ErrorMessageFactory shouldNotBeDone(Future<?> actual) {
return new ShouldNotBeDone(actual);
}
private ShouldNotBeDone(Future<?> actual) {
super(SHOULD_NOT_BE_DONE, actual);
}
}
|
ShouldNotBeDone
|
java
|
spring-projects__spring-boot
|
module/spring-boot-sql/src/main/java/org/springframework/boot/sql/init/dependency/AbstractBeansOfTypeDatabaseInitializerDetector.java
|
{
"start": 1019,
"end": 1613
}
|
class ____ implements DatabaseInitializerDetector {
@Override
public Set<String> detect(ConfigurableListableBeanFactory beanFactory) {
try {
Set<Class<?>> types = getDatabaseInitializerBeanTypes();
return new BeansOfTypeDetector(types).detect(beanFactory);
}
catch (Throwable ex) {
return Collections.emptySet();
}
}
/**
* Returns the bean types that should be detected as being database initializers.
* @return the database initializer bean types
*/
protected abstract Set<Class<?>> getDatabaseInitializerBeanTypes();
}
|
AbstractBeansOfTypeDatabaseInitializerDetector
|
java
|
google__truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
{
"start": 3355,
"end": 3625
}
|
class ____, but that is
* generally not recommended.)
*
* <p>Instances of this are typically used via {@link IterableSubject#comparingElementsUsing},
* {@link MapSubject#comparingValuesUsing}, or {@link MultimapSubject#comparingValuesUsing}.
*/
public abstract
|
yourself
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/FailedCheckpointStatsTest.java
|
{
"start": 1156,
"end": 4757
}
|
class ____ {
/**
* Tests that the end to end duration of a failed checkpoint is the duration until the failure.
*/
@Test
void testEndToEndDuration() {
long duration = 123912931293L;
long triggerTimestamp = 10123;
long failureTimestamp = triggerTimestamp + duration;
Map<JobVertexID, TaskStateStats> taskStats = new HashMap<>();
JobVertexID jobVertexId = new JobVertexID();
taskStats.put(jobVertexId, new TaskStateStats(jobVertexId, 1));
FailedCheckpointStats failed =
new FailedCheckpointStats(
0,
triggerTimestamp,
CheckpointProperties.forCheckpoint(
CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION),
1,
taskStats,
0,
0,
0,
0,
0,
false,
failureTimestamp,
null,
null);
assertThat(failed.getEndToEndDuration()).isEqualTo(duration);
}
@Test
void testIsJavaSerializable() throws Exception {
long duration = 123912931293L;
long triggerTimestamp = 10123;
long failureTimestamp = triggerTimestamp + duration;
Map<JobVertexID, TaskStateStats> taskStats = new HashMap<>();
JobVertexID jobVertexId = new JobVertexID();
taskStats.put(jobVertexId, new TaskStateStats(jobVertexId, 1));
FailedCheckpointStats failed =
new FailedCheckpointStats(
123123123L,
triggerTimestamp,
CheckpointProperties.forCheckpoint(
CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION),
1337,
taskStats,
3,
190890123,
190890123,
4242,
4444,
true,
failureTimestamp,
null,
new NotSerializableException("message"));
FailedCheckpointStats copy = CommonTestUtils.createCopySerializable(failed);
assertThat(copy.getCheckpointId()).isEqualTo(failed.getCheckpointId());
assertThat(copy.getTriggerTimestamp()).isEqualTo(failed.getTriggerTimestamp());
assertThat(copy.getProperties()).isEqualTo(failed.getProperties());
assertThat(copy.getNumberOfSubtasks()).isEqualTo(failed.getNumberOfSubtasks());
assertThat(copy.getNumberOfAcknowledgedSubtasks())
.isEqualTo(failed.getNumberOfAcknowledgedSubtasks());
assertThat(copy.getEndToEndDuration()).isEqualTo(failed.getEndToEndDuration());
assertThat(copy.getStateSize()).isEqualTo(failed.getStateSize());
assertThat(copy.getProcessedData()).isEqualTo(failed.getProcessedData());
assertThat(copy.getPersistedData()).isEqualTo(failed.getPersistedData());
assertThat(copy.isUnalignedCheckpoint()).isEqualTo(failed.isUnalignedCheckpoint());
assertThat(copy.getLatestAcknowledgedSubtaskStats())
.isEqualTo(failed.getLatestAcknowledgedSubtaskStats());
assertThat(copy.getStatus()).isEqualTo(failed.getStatus());
assertThat(copy.getFailureMessage()).isEqualTo(failed.getFailureMessage());
}
}
|
FailedCheckpointStatsTest
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/core/GenericTypeResolverTests.java
|
{
"start": 13763,
"end": 13842
}
|
class ____ extends SpecializedBiGenericClass<E> {}
static
|
TypeFixedBiGenericClass
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/deps/lucene/VectorHighlighterTests.java
|
{
"start": 1688,
"end": 8302
}
|
class ____ extends ESTestCase {
public void testVectorHighlighter() throws Exception {
Directory dir = new ByteBuffersDirectory();
IndexWriter indexWriter = new IndexWriter(dir, new IndexWriterConfig(Lucene.STANDARD_ANALYZER));
Document document = new Document();
document.add(new TextField("_id", "1", Field.Store.YES));
FieldType vectorsType = new FieldType(TextField.TYPE_STORED);
vectorsType.setStoreTermVectors(true);
vectorsType.setStoreTermVectorPositions(true);
vectorsType.setStoreTermVectorOffsets(true);
document.add(new Field("content", "the big bad dog", vectorsType));
indexWriter.addDocument(document);
IndexReader reader = DirectoryReader.open(indexWriter);
IndexSearcher searcher = newSearcher(reader);
TopDocs topDocs = searcher.search(new TermQuery(new Term("_id", "1")), 1);
assertThat(topDocs.totalHits.value(), equalTo(1L));
FastVectorHighlighter highlighter = new FastVectorHighlighter();
String fragment = highlighter.getBestFragment(
highlighter.getFieldQuery(new TermQuery(new Term("content", "bad"))),
searcher.getIndexReader(),
topDocs.scoreDocs[0].doc,
"content",
30
);
assertThat(fragment, notNullValue());
assertThat(fragment, equalTo("the big <b>bad</b> dog"));
IOUtils.close(reader, indexWriter, dir);
}
public void testVectorHighlighterPrefixQuery() throws Exception {
Directory dir = new ByteBuffersDirectory();
IndexWriter indexWriter = new IndexWriter(dir, new IndexWriterConfig(Lucene.STANDARD_ANALYZER));
Document document = new Document();
document.add(new TextField("_id", "1", Field.Store.YES));
FieldType vectorsType = new FieldType(TextField.TYPE_STORED);
vectorsType.setStoreTermVectors(true);
vectorsType.setStoreTermVectorPositions(true);
vectorsType.setStoreTermVectorOffsets(true);
document.add(new Field("content", "the big bad dog", vectorsType));
indexWriter.addDocument(document);
IndexReader indexReader = DirectoryReader.open(indexWriter);
IndexSearcher searcher = newSearcher(indexReader);
IndexReader reader = searcher.getIndexReader();
TopDocs topDocs = searcher.search(new TermQuery(new Term("_id", "1")), 1);
assertThat(topDocs.totalHits.value(), equalTo(1L));
FastVectorHighlighter highlighter = new FastVectorHighlighter();
PrefixQuery prefixQuery = new PrefixQuery(new Term("content", "ba"));
assertThat(
prefixQuery.getRewriteMethod().getClass().getName(),
equalTo(PrefixQuery.CONSTANT_SCORE_BLENDED_REWRITE.getClass().getName())
);
String fragment = highlighter.getBestFragment(
highlighter.getFieldQuery(prefixQuery),
reader,
topDocs.scoreDocs[0].doc,
"content",
30
);
assertThat(fragment, nullValue());
prefixQuery = new PrefixQuery(new Term("content", "ba"), MultiTermQuery.SCORING_BOOLEAN_REWRITE);
Query rewriteQuery = prefixQuery.rewrite(searcher);
fragment = highlighter.getBestFragment(highlighter.getFieldQuery(rewriteQuery), reader, topDocs.scoreDocs[0].doc, "content", 30);
assertThat(fragment, notNullValue());
// now check with the custom field query
prefixQuery = new PrefixQuery(new Term("content", "ba"));
assertThat(
prefixQuery.getRewriteMethod().getClass().getName(),
equalTo(PrefixQuery.CONSTANT_SCORE_BLENDED_REWRITE.getClass().getName())
);
fragment = highlighter.getBestFragment(
new CustomFieldQuery(prefixQuery, reader, highlighter),
reader,
topDocs.scoreDocs[0].doc,
"content",
30
);
assertThat(fragment, notNullValue());
IOUtils.close(indexReader, indexWriter, dir);
}
public void testVectorHighlighterNoStore() throws Exception {
Directory dir = new ByteBuffersDirectory();
IndexWriter indexWriter = new IndexWriter(dir, new IndexWriterConfig(Lucene.STANDARD_ANALYZER));
Document document = new Document();
document.add(new TextField("_id", "1", Field.Store.YES));
FieldType vectorsType = new FieldType(TextField.TYPE_NOT_STORED);
vectorsType.setStoreTermVectors(true);
vectorsType.setStoreTermVectorPositions(true);
vectorsType.setStoreTermVectorOffsets(true);
document.add(new Field("content", "the big bad dog", vectorsType));
indexWriter.addDocument(document);
IndexReader reader = DirectoryReader.open(indexWriter);
IndexSearcher searcher = newSearcher(reader);
TopDocs topDocs = searcher.search(new TermQuery(new Term("_id", "1")), 1);
assertThat(topDocs.totalHits.value(), equalTo(1L));
FastVectorHighlighter highlighter = new FastVectorHighlighter();
String fragment = highlighter.getBestFragment(
highlighter.getFieldQuery(new TermQuery(new Term("content", "bad"))),
searcher.getIndexReader(),
topDocs.scoreDocs[0].doc,
"content",
30
);
assertThat(fragment, nullValue());
IOUtils.close(reader, indexWriter, dir);
}
public void testVectorHighlighterNoTermVector() throws Exception {
Directory dir = new ByteBuffersDirectory();
IndexWriter indexWriter = new IndexWriter(dir, new IndexWriterConfig(Lucene.STANDARD_ANALYZER));
Document document = new Document();
document.add(new TextField("_id", "1", Field.Store.YES));
document.add(new TextField("content", "the big bad dog", Field.Store.YES));
indexWriter.addDocument(document);
IndexReader reader = DirectoryReader.open(indexWriter);
IndexSearcher searcher = newSearcher(reader);
TopDocs topDocs = searcher.search(new TermQuery(new Term("_id", "1")), 1);
assertThat(topDocs.totalHits.value(), equalTo(1L));
FastVectorHighlighter highlighter = new FastVectorHighlighter();
String fragment = highlighter.getBestFragment(
highlighter.getFieldQuery(new TermQuery(new Term("content", "bad"))),
searcher.getIndexReader(),
topDocs.scoreDocs[0].doc,
"content",
30
);
assertThat(fragment, nullValue());
IOUtils.close(reader, indexWriter, dir);
}
}
|
VectorHighlighterTests
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/processor/RouteWithConstantFieldFromExchangeFailTest.java
|
{
"start": 1138,
"end": 2039
}
|
class ____ extends ContextTestSupport {
private Exception exception;
@Test
public void testFail() {
assertNotNull(exception, "Should have thrown an exception");
IllegalArgumentException iae = assertIsInstanceOf(IllegalArgumentException.class, exception.getCause());
assertEquals("Constant field with name: XXX not found on Exchange.class", iae.getMessage());
}
@Override
@BeforeEach
public void setUp() {
try {
super.setUp();
} catch (Exception e) {
exception = e;
}
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:bar").setHeader("Exchange.XXX", constant("bar")).to("mock:bar");
}
};
}
}
|
RouteWithConstantFieldFromExchangeFailTest
|
java
|
google__auto
|
value/src/main/java/com/google/auto/value/processor/TypeEncoder.java
|
{
"start": 8963,
"end": 9386
}
|
class ____ appropriately. The text is scanned for tokens
* like {@code `java.util.Locale`} or {@code `«java.util.Locale`} to determine which classes are
* referenced. An appropriate set of imports is computed based on the set of those types. If the
* special token {@code `import`} appears in {@code text} then it will be replaced by this set of
* import statements. Then all of the tokens are replaced by the
|
names
|
java
|
apache__camel
|
core/camel-core-xml/src/main/java/org/apache/camel/core/xml/util/jsse/AbstractTrustManagersParametersFactoryBean.java
|
{
"start": 1293,
"end": 4103
}
|
class ____ extends AbstractJsseUtilFactoryBean<TrustManagersParameters> {
@XmlAttribute
@Metadata(label = "advanced", description = "The provider identifier for the TrustManagerFactory used to create"
+ " TrustManagers represented by this object's configuration.")
protected String provider;
@XmlAttribute
@Metadata(label = "advanced", description = "The optional algorithm name for the TrustManagerFactory used to"
+ " create the TrustManagers represented by this objects configuration."
+ " See https://docs.oracle.com/en/java/javase/17/docs/specs/security/standard-names.html")
protected String algorithm;
@XmlAttribute
@Metadata(label = "advanced",
description = "To use a existing configured trust manager instead of using TrustManagerFactory to get the TrustManager.")
protected String trustManager;
@XmlTransient
private TrustManagersParameters instance;
public String getProvider() {
return provider;
}
public void setProvider(String value) {
this.provider = value;
}
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String value) {
this.algorithm = value;
}
public String getTrustManager() {
return trustManager;
}
public void setTrustManager(String trustManager) {
this.trustManager = trustManager;
}
@Override
public TrustManagersParameters getObject() throws Exception {
if (isSingleton()) {
if (instance == null) {
instance = createInstance();
}
return instance;
} else {
return createInstance();
}
}
@Override
public Class<TrustManagersParameters> getObjectType() {
return TrustManagersParameters.class;
}
protected TrustManagersParameters createInstance() throws Exception {
TrustManagersParameters newInstance = new TrustManagersParameters();
newInstance.setAlgorithm(algorithm);
if (getKeyStore() != null) {
getKeyStore().setCamelContext(getCamelContext());
newInstance.setKeyStore(getKeyStore().getObject());
}
newInstance.setProvider(provider);
newInstance.setCamelContext(getCamelContext());
if (trustManager != null) {
TrustManager tm = CamelContextHelper.mandatoryLookup(getCamelContext(), trustManager, TrustManager.class);
newInstance.setTrustManager(tm);
}
return newInstance;
}
protected abstract AbstractKeyStoreParametersFactoryBean getKeyStore();
}
|
AbstractTrustManagersParametersFactoryBean
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/exceptionhistory/TestingAccessExecution.java
|
{
"start": 1603,
"end": 4206
}
|
class ____ implements AccessExecution {
private final ExecutionAttemptID executionAttemptID;
private final ExecutionState state;
@Nullable private final ErrorInfo failureInfo;
@Nullable private final TaskManagerLocation taskManagerLocation;
private TestingAccessExecution(
ExecutionAttemptID executionAttemptID,
ExecutionState state,
@Nullable ErrorInfo failureInfo,
@Nullable TaskManagerLocation taskManagerLocation) {
this.executionAttemptID = executionAttemptID;
this.state = state;
this.failureInfo = failureInfo;
this.taskManagerLocation = taskManagerLocation;
}
@Override
public ExecutionAttemptID getAttemptId() {
return executionAttemptID;
}
@Override
public TaskManagerLocation getAssignedResourceLocation() {
return taskManagerLocation;
}
@Override
public Optional<ErrorInfo> getFailureInfo() {
return Optional.ofNullable(failureInfo);
}
@Override
public int getAttemptNumber() {
throw new UnsupportedOperationException("getAttemptNumber should not be called.");
}
@Override
public long[] getStateTimestamps() {
throw new UnsupportedOperationException("getStateTimestamps should not be called.");
}
@Override
public long[] getStateEndTimestamps() {
throw new UnsupportedOperationException("getStateTimestamps should not be called.");
}
@Override
public ExecutionState getState() {
return state;
}
@Override
public long getStateTimestamp(ExecutionState state) {
throw new UnsupportedOperationException("getStateTimestamp should not be called.");
}
@Override
public long getStateEndTimestamp(ExecutionState state) {
throw new UnsupportedOperationException("getStateTimestamp should not be called.");
}
@Override
public StringifiedAccumulatorResult[] getUserAccumulatorsStringified() {
throw new UnsupportedOperationException(
"getUserAccumulatorsStringified should not be called.");
}
@Override
public int getParallelSubtaskIndex() {
throw new UnsupportedOperationException("getParallelSubtaskIndex should not be called.");
}
@Override
public IOMetrics getIOMetrics() {
throw new UnsupportedOperationException("getIOMetrics should not be called.");
}
public static Builder newBuilder() {
return new Builder();
}
/** Builder for {@link TestingAccessExecution}. */
public static
|
TestingAccessExecution
|
java
|
google__dagger
|
hilt-compiler/main/java/dagger/hilt/processor/internal/aggregateddeps/PkgPrivateModuleGenerator.java
|
{
"start": 2100,
"end": 3183
}
|
class ____ {}
void generate() throws IOException {
TypeSpec.Builder builder =
TypeSpec.classBuilder(metadata.generatedClassName().simpleName())
.addAnnotation(Processors.getOriginatingElementAnnotation(metadata.getTypeElement()))
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
// generated @InstallIn is exactly the same as the module being processed
.addAnnotation(
XAnnotations.getAnnotationSpec(metadata.getOptionalInstallInAnnotation().get()))
.addAnnotation(
AnnotationSpec.builder(metadata.getAnnotation())
.addMember("includes", "$T.class", metadata.getTypeElement().getClassName())
.build());
JavaPoetExtKt.addOriginatingElement(builder, metadata.getTypeElement());
Processors.addGeneratedAnnotation(builder, env, getClass());
env.getFiler()
.write(
JavaFile.builder(metadata.generatedClassName().packageName(), builder.build()).build(),
Mode.Isolating);
}
}
|
HiltModuleWrapper_MyModule
|
java
|
alibaba__nacos
|
plugin/config/src/test/java/com/alibaba/nacos/plugin/config/ConfigChangePluginManagerTests.java
|
{
"start": 1486,
"end": 8753
}
|
class ____ {
@Test
void testInstance() {
ConfigChangePluginManager instance = ConfigChangePluginManager.getInstance();
assertNotNull(instance);
}
@BeforeEach
void initPluginServices() {
ConfigChangePluginManager.join(new ConfigChangePluginService() {
@Override
public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) {
// ignore
}
@Override
public ConfigChangeExecuteTypes executeType() {
return ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE;
}
@Override
public String getServiceType() {
return "test1";
}
@Override
public int getOrder() {
return 0;
}
@Override
public ConfigChangePointCutTypes[] pointcutMethodNames() {
return new ConfigChangePointCutTypes[] {ConfigChangePointCutTypes.PUBLISH_BY_HTTP,
ConfigChangePointCutTypes.PUBLISH_BY_RPC};
}
});
ConfigChangePluginManager.join(new ConfigChangePluginService() {
@Override
public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) {
// ignore
}
@Override
public ConfigChangeExecuteTypes executeType() {
return ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE;
}
@Override
public String getServiceType() {
return "test2";
}
@Override
public int getOrder() {
return 200;
}
@Override
public ConfigChangePointCutTypes[] pointcutMethodNames() {
return new ConfigChangePointCutTypes[] {ConfigChangePointCutTypes.IMPORT_BY_HTTP, ConfigChangePointCutTypes.PUBLISH_BY_RPC};
}
});
ConfigChangePluginManager.join(new ConfigChangePluginService() {
@Override
public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) {
// ignore
}
@Override
public ConfigChangeExecuteTypes executeType() {
return ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE;
}
@Override
public String getServiceType() {
return "test3";
}
@Override
public int getOrder() {
return 400;
}
@Override
public ConfigChangePointCutTypes[] pointcutMethodNames() {
return new ConfigChangePointCutTypes[] {ConfigChangePointCutTypes.IMPORT_BY_HTTP, ConfigChangePointCutTypes.PUBLISH_BY_RPC,
ConfigChangePointCutTypes.REMOVE_BATCH_HTTP, ConfigChangePointCutTypes.REMOVE_BY_RPC,
ConfigChangePointCutTypes.REMOVE_BY_HTTP};
}
});
ConfigChangePluginManager.join(new ConfigChangePluginService() {
@Override
public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) {
// ignore
}
@Override
public ConfigChangeExecuteTypes executeType() {
return ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE;
}
@Override
public String getServiceType() {
return "test4";
}
@Override
public int getOrder() {
return 600;
}
@Override
public ConfigChangePointCutTypes[] pointcutMethodNames() {
return new ConfigChangePointCutTypes[] {ConfigChangePointCutTypes.PUBLISH_BY_HTTP,
ConfigChangePointCutTypes.REMOVE_BATCH_HTTP, ConfigChangePointCutTypes.REMOVE_BY_RPC,
ConfigChangePointCutTypes.REMOVE_BY_HTTP};
}
});
}
@Test
void testFindPluginServiceQueueByPointcut() {
List<ConfigChangePluginService> configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(
ConfigChangePointCutTypes.PUBLISH_BY_HTTP);
assertEquals(2, configChangePluginServices.size());
assertTrue(isSorted(configChangePluginServices));
configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.PUBLISH_BY_RPC);
assertEquals(3, configChangePluginServices.size());
assertTrue(isSorted(configChangePluginServices));
configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.IMPORT_BY_HTTP);
assertEquals(2, configChangePluginServices.size());
assertTrue(isSorted(configChangePluginServices));
configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BATCH_HTTP);
assertEquals(2, configChangePluginServices.size());
assertTrue(isSorted(configChangePluginServices));
configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BY_RPC);
assertEquals(2, configChangePluginServices.size());
assertTrue(isSorted(configChangePluginServices));
configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BY_HTTP);
assertEquals(2, configChangePluginServices.size());
assertTrue(isSorted(configChangePluginServices));
}
@Test
void testFindPluginServiceByServiceType() {
Optional<ConfigChangePluginService> configChangePluginServiceOptional = ConfigChangePluginManager.getInstance()
.findPluginServiceImpl("test1");
assertTrue(configChangePluginServiceOptional.isPresent());
configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test2");
assertTrue(configChangePluginServiceOptional.isPresent());
configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test3");
assertTrue(configChangePluginServiceOptional.isPresent());
configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test4");
assertTrue(configChangePluginServiceOptional.isPresent());
configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test5");
assertFalse(configChangePluginServiceOptional.isPresent());
}
private boolean isSorted(List<ConfigChangePluginService> list) {
return IntStream.range(0, list.size() - 1).allMatch(i -> list.get(i).getOrder() <= list.get(i + 1).getOrder());
}
}
|
ConfigChangePluginManagerTests
|
java
|
google__auto
|
value/src/main/java/com/google/auto/value/processor/AutoOneOfTemplateVars.java
|
{
"start": 1380,
"end": 1578
}
|
enum ____. */
String kindType;
/** The name of the method that gets the kind of the current {@code @AutoOneOf} instance. */
String kindGetter;
/** Maps property names like {@code dog} to
|
class
|
java
|
quarkusio__quarkus
|
extensions/agroal/spi/src/main/java/io/quarkus/agroal/spi/JdbcDataSourceBuildItem.java
|
{
"start": 353,
"end": 1361
}
|
class ____ extends MultiBuildItem {
private final String name;
private final String dbKind;
private final Optional<String> dbVersion;
private final boolean transactionIntegrationEnabled;
private final boolean isDefault;
public JdbcDataSourceBuildItem(String name, String kind, Optional<String> dbVersion,
boolean transactionIntegrationEnabled, boolean isDefault) {
this.name = name;
this.dbKind = kind;
this.dbVersion = dbVersion;
this.transactionIntegrationEnabled = transactionIntegrationEnabled;
this.isDefault = isDefault;
}
public String getName() {
return name;
}
public String getDbKind() {
return dbKind;
}
public Optional<String> getDbVersion() {
return dbVersion;
}
public boolean isTransactionIntegrationEnabled() {
return transactionIntegrationEnabled;
}
public boolean isDefault() {
return isDefault;
}
}
|
JdbcDataSourceBuildItem
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/issue_1300/Issue1370.java
|
{
"start": 1421,
"end": 1473
}
|
class ____ {
public Timestamp val;
}
}
|
Model
|
java
|
elastic__elasticsearch
|
qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/IndexingIT.java
|
{
"start": 1646,
"end": 28165
}
|
class ____ extends ESRestTestCase {
private static final String BWC_NODES_VERSION = System.getProperty("tests.bwc_nodes_version");
private int indexDocs(String index, final int idStart, final int numDocs) throws IOException {
for (int i = 0; i < numDocs; i++) {
final int id = idStart + i;
Request request = new Request("PUT", index + "/_doc/" + id);
request.setJsonEntity("{\"test\": \"test_" + randomAlphaOfLength(2) + "\"}");
assertOK(client().performRequest(request));
}
return numDocs;
}
/**
* Indexes a document in <code>index</code> with <code>docId</code> then concurrently updates the same document
* <code>nUpdates</code> times
*
* @return the document version after updates
*/
private int indexDocWithConcurrentUpdates(String index, final int docId, int nUpdates) throws IOException, InterruptedException {
indexDocs(index, docId, 1);
runInParallel(nUpdates, i -> {
try {
indexDocs(index, docId, 1);
} catch (IOException e) {
throw new AssertionError("failed while indexing [" + e.getMessage() + "]");
}
});
return nUpdates + 1;
}
public void testIndexVersionPropagation() throws Exception {
MixedClusterTestNodes nodes = buildNodeAndVersions();
assumeFalse("new nodes is empty", nodes.getNewNodes().isEmpty());
logger.info("cluster discovered: {}", nodes.toString());
final List<String> bwcNamesList = nodes.getBWCNodes().stream().map(MixedClusterTestNode::nodeName).collect(Collectors.toList());
final String bwcNames = bwcNamesList.stream().collect(Collectors.joining(","));
Settings.Builder settings = indexSettings(1, 2).put("index.routing.allocation.include._name", bwcNames);
final String index = "indexversionprop";
final int minUpdates = 5;
final int maxUpdates = 10;
createIndex(index, settings.build());
try (
RestClient newNodeClient = buildClient(
restClientSettings(),
nodes.getNewNodes().stream().map(MixedClusterTestNode::publishAddress).toArray(HttpHost[]::new)
)
) {
int nUpdates = randomIntBetween(minUpdates, maxUpdates);
logger.info("indexing docs with [{}] concurrent updates initially", nUpdates);
final int finalVersionForDoc1 = indexDocWithConcurrentUpdates(index, 1, nUpdates);
logger.info("allowing shards on all nodes");
updateIndexSettings(index, Settings.builder().putNull("index.routing.allocation.include._name"));
ensureGreen(index);
assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
List<Shard> shards = buildShards(index, nodes, newNodeClient);
Shard primary = buildShards(index, nodes, newNodeClient).stream().filter(Shard::primary).findFirst().get();
logger.info("primary resolved to: " + primary.node().nodeName());
for (Shard shard : shards) {
assertVersion(index, 1, "_only_nodes:" + shard.node().nodeName(), finalVersionForDoc1);
assertCount(index, "_only_nodes:" + shard.node().nodeName(), 1);
}
nUpdates = randomIntBetween(minUpdates, maxUpdates);
logger.info("indexing docs with [{}] concurrent updates after allowing shards on all nodes", nUpdates);
final int finalVersionForDoc2 = indexDocWithConcurrentUpdates(index, 2, nUpdates);
assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
shards = buildShards(index, nodes, newNodeClient);
primary = shards.stream().filter(Shard::primary).findFirst().get();
logger.info("primary resolved to: " + primary.node().nodeName());
for (Shard shard : shards) {
assertVersion(index, 2, "_only_nodes:" + shard.node().nodeName(), finalVersionForDoc2);
assertCount(index, "_only_nodes:" + shard.node().nodeName(), 2);
}
primary = shards.stream().filter(Shard::primary).findFirst().get();
logger.info("moving primary to new node by excluding {}", primary.node().nodeName());
updateIndexSettings(index, Settings.builder().put("index.routing.allocation.exclude._name", primary.node().nodeName()));
ensureGreen(index);
nUpdates = randomIntBetween(minUpdates, maxUpdates);
logger.info("indexing docs with [{}] concurrent updates after moving primary", nUpdates);
final int finalVersionForDoc3 = indexDocWithConcurrentUpdates(index, 3, nUpdates);
assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
shards = buildShards(index, nodes, newNodeClient);
for (Shard shard : shards) {
assertVersion(index, 3, "_only_nodes:" + shard.node().nodeName(), finalVersionForDoc3);
assertCount(index, "_only_nodes:" + shard.node().nodeName(), 3);
}
logger.info("setting number of replicas to 0");
updateIndexSettings(index, Settings.builder().put("index.number_of_replicas", 0));
ensureGreen(index);
nUpdates = randomIntBetween(minUpdates, maxUpdates);
logger.info("indexing doc with [{}] concurrent updates after setting number of replicas to 0", nUpdates);
final int finalVersionForDoc4 = indexDocWithConcurrentUpdates(index, 4, nUpdates);
assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
shards = buildShards(index, nodes, newNodeClient);
for (Shard shard : shards) {
assertVersion(index, 4, "_only_nodes:" + shard.node().nodeName(), finalVersionForDoc4);
assertCount(index, "_only_nodes:" + shard.node().nodeName(), 4);
}
logger.info("setting number of replicas to 1");
updateIndexSettings(index, Settings.builder().put("index.number_of_replicas", 1));
ensureGreen(index);
nUpdates = randomIntBetween(minUpdates, maxUpdates);
logger.info("indexing doc with [{}] concurrent updates after setting number of replicas to 1", nUpdates);
final int finalVersionForDoc5 = indexDocWithConcurrentUpdates(index, 5, nUpdates);
assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
shards = buildShards(index, nodes, newNodeClient);
for (Shard shard : shards) {
assertVersion(index, 5, "_only_nodes:" + shard.node().nodeName(), finalVersionForDoc5);
assertCount(index, "_only_nodes:" + shard.node().nodeName(), 5);
}
}
}
public void testSeqNoCheckpoints() throws Exception {
MixedClusterTestNodes nodes = buildNodeAndVersions();
assumeFalse("new nodes is empty", nodes.getNewNodes().isEmpty());
logger.info("cluster discovered: {}", nodes.toString());
final List<String> bwcNamesList = nodes.getBWCNodes().stream().map(MixedClusterTestNode::nodeName).collect(Collectors.toList());
final String bwcNames = bwcNamesList.stream().collect(Collectors.joining(","));
Settings.Builder settings = indexSettings(1, 2).put("index.routing.allocation.include._name", bwcNames);
final String index = "test";
createIndex(index, settings.build());
try (
RestClient newNodeClient = buildClient(
restClientSettings(),
nodes.getNewNodes().stream().map(MixedClusterTestNode::publishAddress).toArray(HttpHost[]::new)
)
) {
int numDocs = 0;
final int numberOfInitialDocs = 1 + randomInt(5);
logger.info("indexing [{}] docs initially", numberOfInitialDocs);
numDocs += indexDocs(index, 0, numberOfInitialDocs);
assertSeqNoOnShards(index, nodes, numDocs, newNodeClient);
logger.info("allowing shards on all nodes");
updateIndexSettings(index, Settings.builder().putNull("index.routing.allocation.include._name"));
ensureGreen(index);
assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
for (final String bwcName : bwcNamesList) {
assertCount(index, "_only_nodes:" + bwcName, numDocs);
}
final int numberOfDocsAfterAllowingShardsOnAllNodes = 1 + randomInt(5);
logger.info("indexing [{}] docs after allowing shards on all nodes", numberOfDocsAfterAllowingShardsOnAllNodes);
numDocs += indexDocs(index, numDocs, numberOfDocsAfterAllowingShardsOnAllNodes);
assertSeqNoOnShards(index, nodes, numDocs, newNodeClient);
Shard primary = buildShards(index, nodes, newNodeClient).stream().filter(Shard::primary).findFirst().get();
logger.info("moving primary to new node by excluding {}", primary.node().nodeName());
updateIndexSettings(index, Settings.builder().put("index.routing.allocation.exclude._name", primary.node().nodeName()));
ensureGreen(index);
int numDocsOnNewPrimary = 0;
final int numberOfDocsAfterMovingPrimary = 1 + randomInt(5);
logger.info("indexing [{}] docs after moving primary", numberOfDocsAfterMovingPrimary);
numDocsOnNewPrimary += indexDocs(index, numDocs, numberOfDocsAfterMovingPrimary);
numDocs += numberOfDocsAfterMovingPrimary;
assertSeqNoOnShards(index, nodes, numDocs, newNodeClient);
/*
* Dropping the number of replicas to zero, and then increasing it to one triggers a recovery thus exercising any BWC-logic in
* the recovery code.
*/
logger.info("setting number of replicas to 0");
updateIndexSettings(index, Settings.builder().put("index.number_of_replicas", 0));
final int numberOfDocsAfterDroppingReplicas = 1 + randomInt(5);
logger.info("indexing [{}] docs after setting number of replicas to 0", numberOfDocsAfterDroppingReplicas);
numDocsOnNewPrimary += indexDocs(index, numDocs, numberOfDocsAfterDroppingReplicas);
numDocs += numberOfDocsAfterDroppingReplicas;
logger.info("setting number of replicas to 1");
updateIndexSettings(index, Settings.builder().put("index.number_of_replicas", 1));
ensureGreen(index);
assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
for (Shard shard : buildShards(index, nodes, newNodeClient)) {
assertCount(index, "_only_nodes:" + shard.node.nodeName(), numDocs);
}
assertSeqNoOnShards(index, nodes, numDocs, newNodeClient);
}
}
public void testUpdateSnapshotStatus() throws Exception {
MixedClusterTestNodes nodes = buildNodeAndVersions();
assumeFalse("new nodes is empty", nodes.getNewNodes().isEmpty());
logger.info("cluster discovered: {}", nodes.toString());
// Create the repository before taking the snapshot.
Request request = new Request("PUT", "/_snapshot/repo");
request.setJsonEntity(
Strings.toString(
JsonXContent.contentBuilder()
.startObject()
.field("type", "fs")
.startObject("settings")
.field("compress", randomBoolean())
.field("location", System.getProperty("tests.path.repo"))
.endObject()
.endObject()
)
);
assertOK(client().performRequest(request));
String bwcNames = nodes.getBWCNodes().stream().map(MixedClusterTestNode::nodeName).collect(Collectors.joining(","));
// Allocating shards on the BWC nodes to makes sure that taking snapshot happens on those nodes.
Settings.Builder settings = indexSettings(between(5, 10), 1).put("index.routing.allocation.include._name", bwcNames);
final String index = "test-snapshot-index";
createIndex(index, settings.build());
indexDocs(index, 0, between(50, 100));
ensureGreen(index);
assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
request = new Request("PUT", "/_snapshot/repo/bwc-snapshot");
request.addParameter("wait_for_completion", "true");
request.setJsonEntity("{\"indices\": \"" + index + "\"}");
assertOK(client().performRequest(request));
// Allocating shards on all nodes, taking snapshots should happen on all nodes.
updateIndexSettings(index, Settings.builder().putNull("index.routing.allocation.include._name"));
ensureGreen(index);
assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
request = new Request("PUT", "/_snapshot/repo/mixed-snapshot");
request.addParameter("wait_for_completion", "true");
request.setJsonEntity("{\"indices\": \"" + index + "\"}");
}
/**
* Tries to extract a major version from a version string, if this is in the major.minor.revision format
* @param version a string representing a version. Can be opaque or semantic
* @return Optional.empty() if the format is not recognized, or an Optional containing the major Integer otherwise
*/
private static Optional<Integer> extractLegacyMajorVersion(String version) {
var semanticVersionMatcher = Pattern.compile("^(\\d+)\\.\\d+\\.\\d+\\D?.*").matcher(version);
if (semanticVersionMatcher.matches() == false) {
return Optional.empty();
}
var major = Integer.parseInt(semanticVersionMatcher.group(1));
return Optional.of(major);
}
private static boolean syncedFlushDeprecated() {
// Only versions past 8.10 can be non-semantic, so we can safely assume that non-semantic versions have this "feature"
return extractLegacyMajorVersion(BWC_NODES_VERSION).map(m -> m >= 7).orElse(true);
}
private static boolean syncedFlushRemoved() {
// Only versions past 8.10 can be non-semantic, so we can safely assume that non-semantic versions have this "feature"
return extractLegacyMajorVersion(BWC_NODES_VERSION).map(m -> m >= 8).orElse(true);
}
public void testSyncedFlushTransition() throws Exception {
MixedClusterTestNodes nodes = buildNodeAndVersions();
assumeTrue(
"bwc version is on 7.x (synced flush deprecated but not removed yet)",
syncedFlushDeprecated() && syncedFlushRemoved() == false
);
assumeFalse("no new node found", nodes.getNewNodes().isEmpty());
assumeFalse("no bwc node found", nodes.getBWCNodes().isEmpty());
// Allocate shards to new nodes then verify synced flush requests processed by old nodes/new nodes
String newNodes = nodes.getNewNodes().stream().map(MixedClusterTestNode::nodeName).collect(Collectors.joining(","));
int numShards = randomIntBetween(1, 10);
int numOfReplicas = randomIntBetween(0, nodes.getNewNodes().size() - 1);
int totalShards = numShards * (numOfReplicas + 1);
final String index = "test_synced_flush";
createIndex(index, indexSettings(numShards, numOfReplicas).put("index.routing.allocation.include._name", newNodes).build());
ensureGreen(index);
indexDocs(index, randomIntBetween(0, 100), between(1, 100));
try (
RestClient oldNodeClient = buildClient(
restClientSettings(),
nodes.getBWCNodes().stream().map(MixedClusterTestNode::publishAddress).toArray(HttpHost[]::new)
)
) {
Request request = new Request("POST", index + "/_flush/synced");
assertBusy(() -> {
ResponseException responseException = expectThrows(ResponseException.class, () -> oldNodeClient.performRequest(request));
assertThat(responseException.getResponse().getStatusLine().getStatusCode(), equalTo(RestStatus.CONFLICT.getStatus()));
assertThat(
responseException.getResponse().getWarnings(),
contains(
oneOf(
"Synced flush is deprecated and will be removed in 8.0. Use flush at _/flush or /{index}/_flush instead.",
"Synced flush is deprecated and will be removed in 8.0. Use flush at /_flush or /{index}/_flush instead."
)
)
);
Map<String, Object> result = ObjectPath.createFromResponse(responseException.getResponse()).evaluate("_shards");
assertThat(result.get("total"), equalTo(totalShards));
assertThat(result.get("successful"), equalTo(0));
assertThat(result.get("failed"), equalTo(totalShards));
});
Map<String, Object> stats = entityAsMap(client().performRequest(new Request("GET", index + "/_stats?level=shards")));
assertThat(XContentMapValues.extractValue("indices." + index + ".total.translog.uncommitted_operations", stats), equalTo(0));
}
indexDocs(index, randomIntBetween(0, 100), between(1, 100));
try (
RestClient newNodeClient = buildClient(
restClientSettings(),
nodes.getNewNodes().stream().map(MixedClusterTestNode::publishAddress).toArray(HttpHost[]::new)
)
) {
Request request = new Request("POST", index + "/_flush/synced");
final String v7MediaType = XContentType.VND_JSON.toParsedMediaType()
.responseContentTypeHeader(
Map.of(MediaType.COMPATIBLE_WITH_PARAMETER_NAME, String.valueOf(RestApiVersion.minimumSupported().major))
);
List<String> warningMsg = List.of(
"Synced flush is deprecated and will be removed in 8.0." + " Use flush at /_flush or /{index}/_flush instead."
);
request.setOptions(
RequestOptions.DEFAULT.toBuilder()
.setWarningsHandler(warnings -> warnings.equals(warningMsg) == false)
.addHeader("Accept", v7MediaType)
);
assertBusy(() -> {
Map<String, Object> result = ObjectPath.createFromResponse(newNodeClient.performRequest(request)).evaluate("_shards");
assertThat(result.get("total"), equalTo(totalShards));
assertThat(result.get("successful"), equalTo(totalShards));
assertThat(result.get("failed"), equalTo(0));
});
Map<String, Object> stats = entityAsMap(client().performRequest(new Request("GET", index + "/_stats?level=shards")));
assertThat(XContentMapValues.extractValue("indices." + index + ".total.translog.uncommitted_operations", stats), equalTo(0));
}
}
public void testFlushTransition() throws Exception {
MixedClusterTestNodes nodes = buildNodeAndVersions();
assumeFalse("no new node found", nodes.getNewNodes().isEmpty());
assumeFalse("no bwc node found", nodes.getBWCNodes().isEmpty());
// Allocate shards to new nodes then verify flush requests processed by old nodes/new nodes
String newNodes = nodes.getNewNodes().stream().map(MixedClusterTestNode::nodeName).collect(Collectors.joining(","));
int numShards = randomIntBetween(1, 10);
int numOfReplicas = randomIntBetween(0, nodes.getNewNodes().size() - 1);
int totalShards = numShards * (numOfReplicas + 1);
final String index = "test_flush";
createIndex(index, indexSettings(numShards, numOfReplicas).put("index.routing.allocation.include._name", newNodes).build());
ensureGreen(index);
indexDocs(index, randomIntBetween(0, 100), between(1, 100));
try (
RestClient oldNodeClient = buildClient(
restClientSettings(),
nodes.getBWCNodes().stream().map(MixedClusterTestNode::publishAddress).toArray(HttpHost[]::new)
)
) {
Request request = new Request("POST", index + "/_flush");
assertBusy(() -> {
Map<String, Object> result = ObjectPath.createFromResponse(oldNodeClient.performRequest(request)).evaluate("_shards");
assertThat(result.get("total"), equalTo(totalShards));
assertThat(result.get("successful"), equalTo(totalShards));
assertThat(result.get("failed"), equalTo(0));
});
Map<String, Object> stats = entityAsMap(client().performRequest(new Request("GET", index + "/_stats?level=shards")));
assertThat(XContentMapValues.extractValue("indices." + index + ".total.translog.uncommitted_operations", stats), equalTo(0));
}
indexDocs(index, randomIntBetween(0, 100), between(1, 100));
try (
RestClient newNodeClient = buildClient(
restClientSettings(),
nodes.getNewNodes().stream().map(MixedClusterTestNode::publishAddress).toArray(HttpHost[]::new)
)
) {
Request request = new Request("POST", index + "/_flush");
assertBusy(() -> {
Map<String, Object> result = ObjectPath.createFromResponse(newNodeClient.performRequest(request)).evaluate("_shards");
assertThat(result.get("total"), equalTo(totalShards));
assertThat(result.get("successful"), equalTo(totalShards));
assertThat(result.get("failed"), equalTo(0));
});
Map<String, Object> stats = entityAsMap(client().performRequest(new Request("GET", index + "/_stats?level=shards")));
assertThat(XContentMapValues.extractValue("indices." + index + ".total.translog.uncommitted_operations", stats), equalTo(0));
}
}
private void assertCount(final String index, final String preference, final int expectedCount) throws IOException {
Request request = new Request("GET", index + "/_count");
request.addParameter("preference", preference);
final Response response = client().performRequest(request);
assertOK(response);
final int actualCount = Integer.parseInt(ObjectPath.createFromResponse(response).evaluate("count").toString());
assertThat(actualCount, equalTo(expectedCount));
}
private void assertVersion(final String index, final int docId, final String preference, final int expectedVersion) throws IOException {
Request request = new Request("GET", index + "/_doc/" + docId);
request.addParameter("preference", preference);
final Response response = client().performRequest(request);
assertOK(response);
final int actualVersion = Integer.parseInt(ObjectPath.createFromResponse(response).evaluate("_version").toString());
assertThat("version mismatch for doc [" + docId + "] preference [" + preference + "]", actualVersion, equalTo(expectedVersion));
}
private void assertSeqNoOnShards(String index, MixedClusterTestNodes nodes, int numDocs, RestClient client) throws Exception {
assertBusy(() -> {
try {
List<Shard> shards = buildShards(index, nodes, client);
Shard primaryShard = shards.stream().filter(Shard::primary).findFirst().get();
assertNotNull("failed to find primary shard", primaryShard);
final long expectedGlobalCkp = numDocs - 1;
final long expectMaxSeqNo = numDocs - 1;
logger.info("primary resolved to node {}", primaryShard.node());
for (Shard shard : shards) {
final SeqNoStats seqNoStats = shard.seqNoStats();
logger.info("stats for {}, primary [{}]: [{}]", shard.node(), shard.primary(), seqNoStats);
assertThat("max_seq no on " + shard.node() + " is wrong", seqNoStats.getMaxSeqNo(), equalTo(expectMaxSeqNo));
assertThat(
"localCheckpoint no on " + shard.node() + " is wrong",
seqNoStats.getLocalCheckpoint(),
equalTo(expectMaxSeqNo)
);
assertThat(
"globalCheckpoint no on " + shard.node() + " is wrong",
seqNoStats.getGlobalCheckpoint(),
equalTo(expectedGlobalCkp)
);
}
} catch (IOException e) {
throw new AssertionError("unexpected io exception", e);
}
});
}
private List<Shard> buildShards(String index, MixedClusterTestNodes nodes, RestClient client) throws IOException {
Request request = new Request("GET", index + "/_stats");
request.addParameter("level", "shards");
Response response = client.performRequest(request);
List<Object> shardStats = ObjectPath.createFromResponse(response).evaluate("indices." + index + ".shards.0");
ArrayList<Shard> shards = new ArrayList<>();
for (Object shard : shardStats) {
final String nodeId = ObjectPath.evaluate(shard, "routing.node");
final Boolean primary = ObjectPath.evaluate(shard, "routing.primary");
final MixedClusterTestNode node = nodes.getSafe(nodeId);
final SeqNoStats seqNoStats;
Integer maxSeqNo = ObjectPath.evaluate(shard, "seq_no.max_seq_no");
Integer localCheckpoint = ObjectPath.evaluate(shard, "seq_no.local_checkpoint");
Integer globalCheckpoint = ObjectPath.evaluate(shard, "seq_no.global_checkpoint");
seqNoStats = new SeqNoStats(maxSeqNo, localCheckpoint, globalCheckpoint);
shards.add(new Shard(node, primary, seqNoStats));
}
logger.info("shards {}", shards);
return shards;
}
private MixedClusterTestNodes buildNodeAndVersions() throws IOException {
return MixedClusterTestNodes.buildNodes(client(), BWC_NODES_VERSION);
}
private record Shard(MixedClusterTestNode node, boolean primary, SeqNoStats seqNoStats) {}
}
|
IndexingIT
|
java
|
google__auto
|
value/src/main/java/com/google/auto/value/processor/SimpleServiceLoader.java
|
{
"start": 1760,
"end": 5013
}
|
class ____ {
private SimpleServiceLoader() {}
public static <T> ImmutableList<T> load(Class<? extends T> service, ClassLoader loader) {
return load(service, loader, Optional.empty());
}
public static <T> ImmutableList<T> load(
Class<? extends T> service, ClassLoader loader, Optional<Pattern> allowedMissingClasses) {
String resourceName = "META-INF/services/" + service.getName();
List<URL> resourceUrls;
try {
resourceUrls = Collections.list(loader.getResources(resourceName));
} catch (IOException e) {
throw new ServiceConfigurationError("Could not look up " + resourceName, e);
}
ImmutableSet.Builder<Class<? extends T>> providerClasses = ImmutableSet.builder();
for (URL resourceUrl : resourceUrls) {
try {
providerClasses.addAll(
providerClassesFromUrl(resourceUrl, service, loader, allowedMissingClasses));
} catch (IOException e) {
throw new ServiceConfigurationError("Could not read " + resourceUrl, e);
}
}
ImmutableList.Builder<T> providers = ImmutableList.builder();
for (Class<? extends T> providerClass : providerClasses.build()) {
try {
T provider = providerClass.getConstructor().newInstance();
providers.add(provider);
} catch (ReflectiveOperationException e) {
throw new ServiceConfigurationError("Could not construct " + providerClass.getName(), e);
}
}
return providers.build();
}
private static <T> ImmutableSet<Class<? extends T>> providerClassesFromUrl(
URL resourceUrl,
Class<? extends T> service,
ClassLoader loader,
Optional<Pattern> allowedMissingClasses)
throws IOException {
ImmutableSet.Builder<Class<? extends T>> providerClasses = ImmutableSet.builder();
URLConnection urlConnection = resourceUrl.openConnection();
urlConnection.setUseCaches(false);
List<String> lines;
try (InputStream in = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, UTF_8))) {
lines = reader.lines().collect(toList());
}
List<String> classNames =
lines.stream()
.map(SimpleServiceLoader::parseClassName)
.flatMap(Streams::stream)
.collect(toList());
for (String className : classNames) {
Class<?> c;
try {
c = Class.forName(className, false, loader);
} catch (ClassNotFoundException e) {
if (allowedMissingClasses.isPresent()
&& allowedMissingClasses.get().matcher(className).matches()) {
continue;
}
throw new ServiceConfigurationError("Could not load " + className, e);
}
if (!service.isAssignableFrom(c)) {
throw new ServiceConfigurationError(
"Class " + className + " is not assignable to " + service.getName());
}
providerClasses.add(c.asSubclass(service));
}
return providerClasses.build();
}
private static Optional<String> parseClassName(String line) {
int hash = line.indexOf('#');
if (hash >= 0) {
line = line.substring(0, hash);
}
line = line.trim();
return line.isEmpty() ? Optional.empty() : Optional.of(line);
}
}
|
SimpleServiceLoader
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/ResourceManagerConstants.java
|
{
"start": 859,
"end": 1153
}
|
interface ____ {
/**
* This states the invalid identifier of Resource Manager. This is used as a
* default value for initializing RM identifier. Currently, RM is using time
* stamp as RM identifier.
*/
public static final long RM_INVALID_IDENTIFIER = -1;
}
|
ResourceManagerConstants
|
java
|
quarkusio__quarkus
|
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/security/HttpUpgradeSelectAuthMechWithAnnotationTest.java
|
{
"start": 3116,
"end": 15061
}
|
class ____ extends SecurityTestBase {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addAsResource(new StringAsset("""
quarkus.tls.key-store.p12.path=keystore.p12
quarkus.tls.key-store.p12.password=secret
quarkus.tls.trust-store.p12.path=server-truststore.p12
quarkus.tls.trust-store.p12.password=secret
quarkus.tls.ws-client.trust-store.p12.path=client-truststore.p12
quarkus.tls.ws-client.trust-store.p12.password=secret
quarkus.tls.ws-client.key-store.p12.path=client-keystore.p12
quarkus.tls.ws-client.key-store.p12.password=secret
quarkus.websockets-next.client.tls-configuration-name=ws-client
quarkus.http.auth.proactive=false
quarkus.http.ssl.client-auth=request
quarkus.http.insecure-requests=enabled
quarkus.http.auth.basic=true
"""), "application.properties")
.addAsResource(new File("target/certs/mtls-test-client-keystore.p12"), "client-keystore.p12")
.addAsResource(new File("target/certs/mtls-test-keystore.p12"), "keystore.p12")
.addAsResource(new File("target/certs/mtls-test-server-truststore.p12"), "server-truststore.p12")
.addAsResource(new File("target/certs/mtls-test-client-truststore.p12"), "client-truststore.p12")
.addClasses(Endpoint.class, WSClient.class, TestIdentityProvider.class, TestIdentityController.class,
PublicEndpoint.class, PublicEndpoint.SubEndpoint.class, CustomAuthEndpoint.class,
CustomAuthenticationRequest.class, CustomAuthMechanism.class, CustomIdentityProvider.class,
RolesAndCustomAuthEndpoint.class, UnknownAuthEndpoint.class));
@Inject
WebSocketConnector<TlsClientEndpoint> connector;
@TestHTTPResource(value = "/", tls = true)
URI tlsEndpointUri;
@TestHTTPResource(value = "/")
URI tlsEndpointUnsecuredUri;
@TestHTTPResource("unknown-auth-endpoint")
URI unknownAuthEndpointUri;
@TestHTTPResource("public-end")
URI publicEndUri;
@TestHTTPResource("public-end/sub")
URI subEndUri;
@TestHTTPResource("custom-auth-endpoint")
URI customAuthEndointUri;
@TestHTTPResource("roles-and-custom-auth-endpoint")
URI rolesAndCustomAuthEndpointUri;
@Test
public void testBasicAuthSubEndpoint() {
// no authentication required - public endpoint
try (WSClient client = new WSClient(vertx)) {
client.connect(publicEndUri);
client.waitForMessages(1);
assertEquals("ready", client.getMessages().get(0).toString());
client.sendAndAwait("hello");
client.waitForMessages(2);
assertEquals("hello", client.getMessages().get(1).toString());
}
// authentication failure as no basic auth is required and no credentials were provided
try (WSClient client = new WSClient(vertx)) {
CompletionException ce = assertThrows(CompletionException.class, () -> client.connect(subEndUri));
Throwable root = ExceptionUtil.getRootCause(ce);
assertInstanceOf(UpgradeRejectedException.class, root);
assertTrue(root.getMessage().contains("401"), root.getMessage());
}
// basic authentication - succeed as admin has required permissions
try (WSClient client = new WSClient(vertx)) {
client.connect(basicAuth("admin", "admin"), subEndUri);
client.waitForMessages(1);
assertEquals("ready", client.getMessages().get(0).toString());
client.sendAndAwait("hello");
client.waitForMessages(2);
assertEquals("sub-endpoint", client.getMessages().get(1).toString());
}
// basic authentication - fail as user doesn't have 'admin' role
try (WSClient client = new WSClient(vertx)) {
client.connect(basicAuth("user", "user"), subEndUri);
client.waitForMessages(1);
assertEquals("ready", client.getMessages().get(0).toString());
client.sendAndAwait("hello");
client.waitForMessages(2);
assertEquals("sub-endpoint:forbidden:user", client.getMessages().get(1).toString());
}
// custom authentication - correct credentials - fails as wrong authentication mechanism
try (WSClient client = new WSClient(vertx)) {
CompletionException ce = assertThrows(CompletionException.class,
() -> client.connect(customAuth("admin"), subEndUri));
Throwable root = ExceptionUtil.getRootCause(ce);
assertInstanceOf(UpgradeRejectedException.class, root);
assertTrue(root.getMessage().contains("401"), root.getMessage());
}
}
@Test
public void testCustomAuthenticationEndpoint() {
// no credentials - deny access
try (WSClient client = new WSClient(vertx)) {
CompletionException ce = assertThrows(CompletionException.class, () -> client.connect(customAuthEndointUri));
Throwable root = ExceptionUtil.getRootCause(ce);
assertInstanceOf(UpgradeRejectedException.class, root);
assertTrue(root.getMessage().contains("401"));
}
// custom auth - correct credentials - pass as has admin role
try (WSClient client = new WSClient(vertx)) {
client.connect(customAuth("admin"), customAuthEndointUri);
client.waitForMessages(1);
assertEquals("ready", client.getMessages().get(0).toString());
client.sendAndAwait("hello");
client.waitForMessages(2);
assertEquals("hello who", client.getMessages().get(1).toString());
}
// basic auth - correct credentials - fail as wrong mechanism
try (WSClient client = new WSClient(vertx)) {
CompletionException ce = assertThrows(CompletionException.class, () -> client
.connect(basicAuth("admin", "admin"), customAuthEndointUri));
Throwable root = ExceptionUtil.getRootCause(ce);
assertInstanceOf(UpgradeRejectedException.class, root);
assertTrue(root.getMessage().contains("401"), root.getMessage());
}
}
@Test
public void testUnknownAuthenticationEndpoint() {
// there is no such authentication mechanism, therefore all requests must be denied
// we can't validate it during the build-time as credentials transport is resolved based on the RoutingContext
// no credentials - deny access
try (WSClient client = new WSClient(vertx)) {
CompletionException ce = assertThrows(CompletionException.class, () -> client.connect(unknownAuthEndpointUri));
Throwable root = ExceptionUtil.getRootCause(ce);
assertInstanceOf(UpgradeRejectedException.class, root);
assertTrue(root.getMessage().contains("401"));
}
// basic auth - correct credentials - fail as wrong mechanism
try (WSClient client = new WSClient(vertx)) {
CompletionException ce = assertThrows(CompletionException.class, () -> client
.connect(basicAuth("admin", "admin"), unknownAuthEndpointUri));
Throwable root = ExceptionUtil.getRootCause(ce);
assertInstanceOf(UpgradeRejectedException.class, root);
assertTrue(root.getMessage().contains("401"), root.getMessage());
}
}
@Test
public void testHttpUpgradeRolesAllowedAndCustomAuth() {
// custom auth - correct credentials - pass as has admin role
try (WSClient client = new WSClient(vertx)) {
client.connect(customAuth("admin"), rolesAndCustomAuthEndpointUri);
client.waitForMessages(1);
assertEquals("ready", client.getMessages().get(0).toString());
client.sendAndAwait("hello");
client.waitForMessages(2);
assertEquals("hello who", client.getMessages().get(1).toString());
}
// custom auth - correct credentials - fails as no admin role
try (WSClient client = new WSClient(vertx)) {
CompletionException ce = assertThrows(CompletionException.class, () -> client
.connect(customAuth("user"), rolesAndCustomAuthEndpointUri));
Throwable root = ExceptionUtil.getRootCause(ce);
assertInstanceOf(UpgradeRejectedException.class, root);
assertTrue(root.getMessage().contains("403"), root.getMessage());
}
// basic auth - correct credentials - fails as wrong authentication mechanism
try (WSClient client = new WSClient(vertx)) {
CompletionException ce = assertThrows(CompletionException.class, () -> client
.connect(basicAuth("admin", "admin"), rolesAndCustomAuthEndpointUri));
Throwable root = ExceptionUtil.getRootCause(ce);
assertInstanceOf(UpgradeRejectedException.class, root);
assertTrue(root.getMessage().contains("401"), root.getMessage());
}
}
@Test
public void testMutualTlsEndpoint() throws InterruptedException, URISyntaxException {
// no TLS, no credentials
Assertions.assertThrows(UpgradeRejectedException.class, () -> assertTlsClient(tlsEndpointUnsecuredUri, null));
// no TLS, admin basic auth credentials
Assertions.assertThrows(UpgradeRejectedException.class, () -> assertTlsClient(tlsEndpointUnsecuredUri, "admin"));
// authenticated as communication is opening WebSockets handshake request
assertTlsClient(tlsEndpointUri, null);
// authenticated using mTLS with explicit 'wss'
URI wssUri = new URI("wss", tlsEndpointUri.getUserInfo(), tlsEndpointUri.getHost(),
tlsEndpointUri.getPort(), tlsEndpointUri.getPath(), tlsEndpointUri.getQuery(), tlsEndpointUri.getFragment());
assertTlsClient(wssUri, null);
}
private void assertTlsClient(URI uri, String basicAuthCred) throws InterruptedException {
TlsServerEndpoint.reset();
TlsClientEndpoint.reset();
var connectorBuilder = connector
.baseUri(uri)
// The value will be encoded automatically
.pathParam("name", "Lu=");
if (basicAuthCred != null) {
connectorBuilder = connectorBuilder.addHeader(HttpHeaders.AUTHORIZATION.toString(),
new UsernamePasswordCredentials(basicAuthCred, basicAuthCred).applyHttpChallenge(null)
.toHttpAuthorization());
}
WebSocketClientConnection connection = connectorBuilder.connectAndAwait();
assertTrue(connection.isSecure());
assertEquals("Lu=", connection.pathParam("name"));
connection.sendTextAndAwait("Hi!");
assertTrue(TlsClientEndpoint.messageLatch.await(5, TimeUnit.SECONDS));
assertEquals("Lu=:Hello Lu=!", TlsClientEndpoint.MESSAGES.get(0));
assertEquals("Lu=:Hi!", TlsClientEndpoint.MESSAGES.get(1));
connection.closeAndAwait();
assertTrue(TlsClientEndpoint.closedLatch.await(5, TimeUnit.SECONDS));
assertTrue(TlsServerEndpoint.closedLatch.await(5, TimeUnit.SECONDS));
}
private static WebSocketConnectOptions customAuth(String role) {
return new WebSocketConnectOptions().addHeader("CustomAuthorization", role);
}
@WebSocket(path = "/public-end")
public static
|
HttpUpgradeSelectAuthMechWithAnnotationTest
|
java
|
google__gson
|
gson/src/test/java/com/google/gson/common/TestTypes.java
|
{
"start": 9966,
"end": 10355
}
|
class ____ {
public ClassOverridingEquals ref;
public String getExpectedJson() {
if (ref == null) {
return "{}";
}
return "{\"ref\":" + ref.getExpectedJson() + "}";
}
@Override
public boolean equals(Object obj) {
return true;
}
@Override
public int hashCode() {
return 1;
}
}
public static
|
ClassOverridingEquals
|
java
|
apache__camel
|
test-infra/camel-test-infra-qdrant/src/main/java/org/apache/camel/test/infra/qdrant/common/QdrantProperties.java
|
{
"start": 862,
"end": 1398
}
|
class ____ {
public static final String INFRA_TYPE = "qdrant";
public static final String QDRANT_HTTP_HOST = "qdrant.http.host";
public static final String QDRANT_HTTP_PORT = "qdrant.http.port";
public static final String QDRANT_GRPC_HOST = "qdrant.grpc.host";
public static final String QDRANT_GRPC_PORT = "qdrant.grpc.port";
public static final String QDRANT_API_KEY = "qdrant.apiKey";
public static final String QDRANT_CONTAINER = "qdrant.container";
private QdrantProperties() {
}
}
|
QdrantProperties
|
java
|
spring-projects__spring-boot
|
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/testing/testcontainers/springbeans/MyIntegrationTests.java
|
{
"start": 1019,
"end": 1162
}
|
class ____ {
@Autowired
private MongoDBContainer mongo;
@Test
void myTest() {
/**/ System.out.println(this.mongo);
}
}
|
MyIntegrationTests
|
java
|
google__guice
|
core/test/com/google/inject/ScopesTest.java
|
{
"start": 7243,
"end": 7297
}
|
class ____ implements A {}
@Retention(RUNTIME)
@
|
AImpl
|
java
|
grpc__grpc-java
|
xds/src/main/java/io/grpc/xds/client/EnvoyProtoData.java
|
{
"start": 4969,
"end": 11252
}
|
class ____ {
private String id = "";
private String cluster = "";
@Nullable
private Map<String, ?> metadata;
@Nullable
private Locality locality;
// TODO(sanjaypujare): eliminate usage of listening_addresses field.
private final List<Address> listeningAddresses = new ArrayList<>();
private String buildVersion = "";
private String userAgentName = "";
@Nullable
private String userAgentVersion;
private final List<String> clientFeatures = new ArrayList<>();
private Builder() {
}
@VisibleForTesting
public Builder setId(String id) {
this.id = checkNotNull(id, "id");
return this;
}
@CanIgnoreReturnValue
public Builder setCluster(String cluster) {
this.cluster = checkNotNull(cluster, "cluster");
return this;
}
@CanIgnoreReturnValue
public Builder setMetadata(Map<String, ?> metadata) {
this.metadata = checkNotNull(metadata, "metadata");
return this;
}
@CanIgnoreReturnValue
public Builder setLocality(Locality locality) {
this.locality = checkNotNull(locality, "locality");
return this;
}
@CanIgnoreReturnValue
Builder addListeningAddresses(Address address) {
listeningAddresses.add(checkNotNull(address, "address"));
return this;
}
@CanIgnoreReturnValue
public Builder setBuildVersion(String buildVersion) {
this.buildVersion = checkNotNull(buildVersion, "buildVersion");
return this;
}
@CanIgnoreReturnValue
public Builder setUserAgentName(String userAgentName) {
this.userAgentName = checkNotNull(userAgentName, "userAgentName");
return this;
}
@CanIgnoreReturnValue
public Builder setUserAgentVersion(String userAgentVersion) {
this.userAgentVersion = checkNotNull(userAgentVersion, "userAgentVersion");
return this;
}
@CanIgnoreReturnValue
public Builder addClientFeatures(String clientFeature) {
this.clientFeatures.add(checkNotNull(clientFeature, "clientFeature"));
return this;
}
public Node build() {
return new Node(
id, cluster, metadata, locality, listeningAddresses, buildVersion, userAgentName,
userAgentVersion, clientFeatures);
}
}
public static Builder newBuilder() {
return new Builder();
}
public Builder toBuilder() {
Builder builder = new Builder();
builder.id = id;
builder.cluster = cluster;
builder.metadata = metadata;
builder.locality = locality;
builder.buildVersion = buildVersion;
builder.listeningAddresses.addAll(listeningAddresses);
builder.userAgentName = userAgentName;
builder.userAgentVersion = userAgentVersion;
builder.clientFeatures.addAll(clientFeatures);
return builder;
}
public String getId() {
return id;
}
String getCluster() {
return cluster;
}
@Nullable
Map<String, ?> getMetadata() {
return metadata;
}
@Nullable
Locality getLocality() {
return locality;
}
List<Address> getListeningAddresses() {
return listeningAddresses;
}
@SuppressWarnings("deprecation")
@VisibleForTesting
public io.envoyproxy.envoy.config.core.v3.Node toEnvoyProtoNode() {
io.envoyproxy.envoy.config.core.v3.Node.Builder builder =
io.envoyproxy.envoy.config.core.v3.Node.newBuilder();
builder.setId(id);
builder.setCluster(cluster);
if (metadata != null) {
Struct.Builder structBuilder = Struct.newBuilder();
for (Map.Entry<String, ?> entry : metadata.entrySet()) {
structBuilder.putFields(entry.getKey(), convertToValue(entry.getValue()));
}
builder.setMetadata(structBuilder);
}
if (locality != null) {
builder.setLocality(
io.envoyproxy.envoy.config.core.v3.Locality.newBuilder()
.setRegion(locality.region())
.setZone(locality.zone())
.setSubZone(locality.subZone()));
}
for (Address address : listeningAddresses) {
builder.addListeningAddresses(address.toEnvoyProtoAddress());
}
builder.setUserAgentName(userAgentName);
if (userAgentVersion != null) {
builder.setUserAgentVersion(userAgentVersion);
}
builder.addAllClientFeatures(clientFeatures);
return builder.build();
}
}
/**
* Converts Java representation of the given JSON value to protobuf's {@link
* com.google.protobuf.Value} representation.
*
* <p>The given {@code rawObject} must be a valid JSON value in Java representation, which is
* either a {@code Map<String, ?>}, {@code List<?>}, {@code String}, {@code Double}, {@code
* Boolean}, or {@code null}.
*/
private static Value convertToValue(Object rawObject) {
Value.Builder valueBuilder = Value.newBuilder();
if (rawObject == null) {
valueBuilder.setNullValue(NullValue.NULL_VALUE);
} else if (rawObject instanceof Double) {
valueBuilder.setNumberValue((Double) rawObject);
} else if (rawObject instanceof String) {
valueBuilder.setStringValue((String) rawObject);
} else if (rawObject instanceof Boolean) {
valueBuilder.setBoolValue((Boolean) rawObject);
} else if (rawObject instanceof Map) {
Struct.Builder structBuilder = Struct.newBuilder();
@SuppressWarnings("unchecked")
Map<String, ?> map = (Map<String, ?>) rawObject;
for (Map.Entry<String, ?> entry : map.entrySet()) {
structBuilder.putFields(entry.getKey(), convertToValue(entry.getValue()));
}
valueBuilder.setStructValue(structBuilder);
} else if (rawObject instanceof List) {
ListValue.Builder listBuilder = ListValue.newBuilder();
List<?> list = (List<?>) rawObject;
for (Object obj : list) {
listBuilder.addValues(convertToValue(obj));
}
valueBuilder.setListValue(listBuilder);
}
return valueBuilder.build();
}
/**
* See corresponding Envoy proto message {@link io.envoyproxy.envoy.config.core.v3.Address}.
*/
static final
|
Builder
|
java
|
apache__flink
|
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/util/collections/binary/BytesHashMap.java
|
{
"start": 1437,
"end": 1946
}
|
class ____ extends AbstractBytesHashMap<BinaryRowData> {
public BytesHashMap(
final Object owner,
MemoryManager memoryManager,
long memorySize,
LogicalType[] keyTypes,
LogicalType[] valueTypes) {
super(
owner,
memoryManager,
memorySize,
new BinaryRowDataSerializer(keyTypes.length),
valueTypes);
checkArgument(keyTypes.length > 0);
}
}
|
BytesHashMap
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java
|
{
"start": 97990,
"end": 99202
}
|
class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((requests) -> requests
.anyRequest().authenticated())
.oauth2ResourceServer((server) -> server
.jwt(Customizer.withDefaults()));
return http.build();
// @formatter:on
}
@Bean
AuthenticationConverter authenticationConverterOne() {
DefaultBearerTokenResolver resolver = new DefaultBearerTokenResolver();
resolver.setAllowUriQueryParameter(true);
BearerTokenAuthenticationConverter authenticationConverter = new BearerTokenAuthenticationConverter();
authenticationConverter.setBearerTokenResolver(resolver);
return authenticationConverter;
}
@Bean
AuthenticationConverter authenticationConverterTwo() {
DefaultBearerTokenResolver resolver = new DefaultBearerTokenResolver();
resolver.setAllowUriQueryParameter(true);
BearerTokenAuthenticationConverter authenticationConverter = new BearerTokenAuthenticationConverter();
authenticationConverter.setBearerTokenResolver(resolver);
return authenticationConverter;
}
}
@Configuration
@EnableWebSecurity
static
|
MultipleAuthenticationConverterBeansConfig
|
java
|
quarkusio__quarkus
|
extensions/scheduler/common/src/main/java/io/quarkus/scheduler/common/runtime/AbstractJobDefinition.java
|
{
"start": 509,
"end": 5103
}
|
class ____<THIS extends JobDefinition<THIS>> implements JobDefinition<THIS> {
protected final String identity;
protected String cron = "";
protected String every = "";
protected String delayed = "";
protected String overdueGracePeriod = "";
protected ConcurrentExecution concurrentExecution = ConcurrentExecution.PROCEED;
protected SkipPredicate skipPredicate = null;
protected Class<? extends SkipPredicate> skipPredicateClass;
protected Consumer<ScheduledExecution> task;
protected Class<? extends Consumer<ScheduledExecution>> taskClass;
protected Function<ScheduledExecution, Uni<Void>> asyncTask;
protected Class<? extends Function<ScheduledExecution, Uni<Void>>> asyncTaskClass;
protected boolean scheduled = false;
protected String timeZone = Scheduled.DEFAULT_TIMEZONE;
protected boolean runOnVirtualThread;
protected String implementation = Scheduled.AUTO;
protected String executionMaxDelay = "";
public AbstractJobDefinition(String identity) {
this.identity = identity;
}
@Override
public THIS setCron(String cron) {
checkScheduled();
this.cron = Objects.requireNonNull(cron);
return self();
}
@Override
public THIS setInterval(String every) {
checkScheduled();
this.every = Objects.requireNonNull(every);
return self();
}
@Override
public THIS setDelayed(String period) {
checkScheduled();
this.delayed = Objects.requireNonNull(period);
return self();
}
@Override
public THIS setConcurrentExecution(ConcurrentExecution concurrentExecution) {
checkScheduled();
this.concurrentExecution = Objects.requireNonNull(concurrentExecution);
return self();
}
@Override
public THIS setSkipPredicate(SkipPredicate skipPredicate) {
checkScheduled();
this.skipPredicate = Objects.requireNonNull(skipPredicate);
return self();
}
@Override
public THIS setSkipPredicate(Class<? extends SkipPredicate> skipPredicateClass) {
checkScheduled();
this.skipPredicateClass = Objects.requireNonNull(skipPredicateClass);
return setSkipPredicate(SchedulerUtils.instantiateBeanOrClass(skipPredicateClass));
}
@Override
public THIS setOverdueGracePeriod(String period) {
checkScheduled();
this.overdueGracePeriod = Objects.requireNonNull(period);
return self();
}
@Override
public THIS setTimeZone(String timeZone) {
checkScheduled();
this.timeZone = Objects.requireNonNull(timeZone);
return self();
}
@Override
public THIS setExecuteWith(String implementation) {
checkScheduled();
this.implementation = Objects.requireNonNull(implementation);
return self();
}
@Override
public THIS setExecutionMaxDelay(String maxDelay) {
checkScheduled();
this.executionMaxDelay = maxDelay;
return self();
}
@Override
public THIS setTask(Consumer<ScheduledExecution> task, boolean runOnVirtualThread) {
checkScheduled();
if (asyncTask != null) {
throw new IllegalStateException("Async task was already set");
}
this.task = Objects.requireNonNull(task);
this.runOnVirtualThread = runOnVirtualThread;
return self();
}
@Override
public THIS setTask(Class<? extends Consumer<ScheduledExecution>> taskClass, boolean runOnVirtualThread) {
this.taskClass = Objects.requireNonNull(taskClass);
return setTask(SchedulerUtils.instantiateBeanOrClass(taskClass), runOnVirtualThread);
}
@Override
public THIS setAsyncTask(Function<ScheduledExecution, Uni<Void>> asyncTask) {
checkScheduled();
if (task != null) {
throw new IllegalStateException("Sync task was already set");
}
this.asyncTask = Objects.requireNonNull(asyncTask);
return self();
}
@Override
public THIS setAsyncTask(Class<? extends Function<ScheduledExecution, Uni<Void>>> asyncTaskClass) {
this.asyncTaskClass = Objects.requireNonNull(asyncTaskClass);
return setAsyncTask(SchedulerUtils.instantiateBeanOrClass(asyncTaskClass));
}
protected void checkScheduled() {
if (scheduled) {
throw new IllegalStateException("Cannot modify a job that was already scheduled");
}
}
@SuppressWarnings("unchecked")
protected THIS self() {
return (THIS) this;
}
}
|
AbstractJobDefinition
|
java
|
jhy__jsoup
|
src/test/java/org/jsoup/integration/ProxyTest.java
|
{
"start": 1026,
"end": 7876
}
|
class ____ {
private static String echoUrl;
private static TestServer.ProxySettings proxy;
@BeforeAll
public static void setUp() {
echoUrl = EchoServlet.Url;
proxy = ProxyServlet.ProxySettings;
}
@ParameterizedTest @MethodSource("helloUrls")
void fetchViaProxy(String url) throws IOException {
Connection con = Jsoup.connect(url)
.proxy(proxy.hostname, proxy.port);
Connection.Response res = con.execute();
if (url.startsWith("http:/")) assertVia(res); // HTTPS CONNECT won't have Via
Document doc = res.parse();
Element p = doc.expectFirst("p");
assertEquals("Hello, World!", p.text());
}
private static Stream<String> helloUrls() {
return Stream.of(HelloServlet.Url, HelloServlet.TlsUrl);
}
private static Stream<String> echoUrls() {
return Stream.of(EchoServlet.Url, EchoServlet.TlsUrl);
}
private static void assertVia(Connection.Response res) {
assertEquals(res.header("Via"), ProxyServlet.Via);
}
@Test void redirectViaProxy() throws IOException {
Connection.Response res = Jsoup
.connect(RedirectServlet.Url)
.data(RedirectServlet.LocationParam, echoUrl)
.header("Random-Header-name", "hello")
.proxy(proxy.hostname, proxy.port)
.execute();
assertVia(res);
Document doc = res.parse();
assertEquals(echoUrl, doc.location());
assertEquals("hello", ihVal("Random-Header-name", doc));
assertVia(res);
}
@Test void proxyForSession() throws IOException {
Connection session = Jsoup.newSession().proxy(proxy.hostname, proxy.port);
Connection.Response medRes = session.newRequest(FileServlet.urlTo("/htmltests/medium.html")).execute();
Connection.Response largeRes = session.newRequest(FileServlet.urlTo("/htmltests/large.html")).execute();
assertVia(medRes);
assertVia(largeRes);
assertEquals("Medium HTML", medRes.parse().title());
assertEquals("Large HTML", largeRes.parse().title());
Connection.Response smedRes = session.newRequest(FileServlet.tlsUrlTo("/htmltests/medium.html")).execute();
Connection.Response slargeRes = session.newRequest(FileServlet.tlsUrlTo("/htmltests/large.html")).execute();
assertEquals("Medium HTML", smedRes.parse().title());
assertEquals("Large HTML", slargeRes.parse().title());
}
@ParameterizedTest @MethodSource("echoUrls")
void canAuthenticateToProxy(String url) throws IOException {
int closed = TestServer.closeAuthedProxyConnections(); // reset any existing authed connections from previous tests, so we can test the auth flow
// the proxy wants auth, but not the server. HTTP and HTTPS, so tests direct proxy and CONNECT
Connection session = Jsoup.newSession()
.proxy(proxy.hostname, proxy.authedPort)
.ignoreHttpErrors(true)
.ignoreContentType(true); // ignore content type, as error served may not have a content type
String password = AuthFilter.newProxyPassword();
// fail first
try {
Connection.Response execute = session.newRequest(url)
.execute();
int code = execute.statusCode(); // no auth sent
assertEquals(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED, code);
} catch (IOException e) {
assertAuthRequiredException(e);
}
try {
AtomicInteger count = new AtomicInteger(0);
Connection.Response res = session.newRequest(url)
.auth(ctx -> {
count.incrementAndGet();
return ctx.credentials(AuthFilter.ProxyUser, password + "wrong"); // incorrect
})
.execute();
assertEquals(MaxAttempts, count.get());
assertEquals(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED, res.statusCode());
} catch (IOException e) {
assertAuthRequiredException(e);
}
AtomicInteger successCount = new AtomicInteger(0);
Connection.Response successRes = session.newRequest(url)
.auth(ctx -> {
successCount.incrementAndGet();
return ctx.credentials(AuthFilter.ProxyUser, password); // correct
})
.execute();
assertEquals(1, successCount.get());
assertEquals(HttpServletResponse.SC_OK, successRes.statusCode());
}
static void assertAuthRequiredException(IOException e) {
// in CONNECT (for the HTTPS url), URLConnection will throw the proxy connect as a Stringly typed IO exception - "Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 Proxy Authentication Required"". (Not a response code)
// Alternatively, some platforms (?) will report: "No credentials provided"
String err = e.getMessage();
if (!(err.contains("407") || err.contains("No credentials provided") || err.contains("exch.exchImpl"))) {
// https://github.com/jhy/jsoup/pull/2403 - Ubuntu Azul 25 throws `Cannot invoke "jdk.internal.net.http.ExchangeImpl.cancel(java.io.IOException)" because "exch.exchImpl" is null` here but is just from cancelling the 407 req
System.err.println("Not a 407 exception? " + e.getClass());
e.printStackTrace(System.err);
fail("Expected 407 Proxy Authentication Required, got: " + err);
}
}
@ParameterizedTest @MethodSource("echoUrls")
void canAuthToProxyAndServer(String url) throws IOException {
String serverPassword = AuthFilter.newServerPassword();
String proxyPassword = AuthFilter.newProxyPassword();
AtomicInteger count = new AtomicInteger(0);
Connection session = Jsoup.newSession() // both proxy and server will want auth
.proxy(proxy.hostname, proxy.authedPort)
.header(AuthFilter.WantsServerAuthentication, "1")
.auth(auth -> {
count.incrementAndGet();
if (auth.isServer()) {
assertEquals(url, auth.url().toString());
assertEquals(AuthFilter.ServerRealm, auth.realm());
return auth.credentials(AuthFilter.ServerUser, serverPassword);
} else {
assertTrue(auth.isProxy());
return auth.credentials(AuthFilter.ProxyUser, proxyPassword);
}
});
Connection.Response res = session.newRequest(url).execute();
assertEquals(200, res.statusCode());
assertEquals(2, count.get()); // hit server and proxy auth stages
assertEquals("Webserver Environment Variables", res.parse().title());
}
}
|
ProxyTest
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/InputSelectable.java
|
{
"start": 2076,
"end": 2335
}
|
interface ____ {
/**
* Returns the next {@link InputSelection} that wants to get the record. This method is
* guaranteed to not be called concurrently with other methods of the operator.
*/
InputSelection nextSelection();
}
|
InputSelectable
|
java
|
grpc__grpc-java
|
alts/src/main/java/io/grpc/alts/internal/AltsProtocolNegotiator.java
|
{
"start": 4093,
"end": 5824
}
|
class ____ implements ProtocolNegotiator {
private final TsiHandshakerFactory handshakerFactory;
private final LazyChannel lazyHandshakerChannel;
ClientAltsProtocolNegotiator(
ImmutableList<String> targetServiceAccounts, ObjectPool<Channel> handshakerChannelPool) {
this.lazyHandshakerChannel = new LazyChannel(handshakerChannelPool);
this.handshakerFactory =
new ClientTsiHandshakerFactory(targetServiceAccounts, lazyHandshakerChannel);
}
@Override
public AsciiString scheme() {
return SCHEME;
}
@Override
public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHandler) {
ChannelLogger negotiationLogger = grpcHandler.getNegotiationLogger();
TsiHandshaker handshaker =
handshakerFactory.newHandshaker(grpcHandler.getAuthority(), negotiationLogger);
NettyTsiHandshaker nettyHandshaker = new NettyTsiHandshaker(handshaker);
ChannelHandler gnh = InternalProtocolNegotiators.grpcNegotiationHandler(grpcHandler);
ChannelHandler thh = new TsiHandshakeHandler(
gnh, nettyHandshaker, new AltsHandshakeValidator(), handshakeSemaphore,
negotiationLogger);
ChannelHandler wuah = InternalProtocolNegotiators.waitUntilActiveHandler(thh,
negotiationLogger);
return wuah;
}
@Override
public void close() {
lazyHandshakerChannel.close();
}
}
/**
* Creates a protocol negotiator for ALTS on the server side.
*/
public static ProtocolNegotiator serverAltsProtocolNegotiator(
ObjectPool<Channel> handshakerChannelPool) {
final LazyChannel lazyHandshakerChannel = new LazyChannel(handshakerChannelPool);
final
|
ClientAltsProtocolNegotiator
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/data/sort/LongFloatBucketedSort.java
|
{
"start": 1211,
"end": 15647
}
|
class ____ implements Releasable {
private final BigArrays bigArrays;
private final SortOrder order;
private final int bucketSize;
/**
* {@code true} if the bucket is in heap mode, {@code false} if
* it is still gathering.
*/
private final BitArray heapMode;
/**
* An array containing all the values on all buckets. The structure is as follows:
* <p>
* For each bucket, there are bucketSize elements, based on the bucket id (0, 1, 2...).
* Then, for each bucket, it can be in 2 states:
* </p>
* <ul>
* <li>
* Gather mode: All buckets start in gather mode, and remain here while they have less than bucketSize elements.
* In gather mode, the elements are stored in the array from the highest index to the lowest index.
* The lowest index contains the offset to the next slot to be filled.
* <p>
* This allows us to insert elements in O(1) time.
* </p>
* <p>
* When the bucketSize-th element is collected, the bucket transitions to heap mode, by heapifying its contents.
* </p>
* </li>
* <li>
* Heap mode: The bucket slots are organized as a min heap structure.
* <p>
* The root of the heap is the minimum value in the bucket,
* which allows us to quickly discard new values that are not in the top N.
* </p>
* </li>
* </ul>
*/
private LongArray values;
private FloatArray extraValues;
public LongFloatBucketedSort(BigArrays bigArrays, SortOrder order, int bucketSize) {
this.bigArrays = bigArrays;
this.order = order;
this.bucketSize = bucketSize;
heapMode = new BitArray(0, bigArrays);
boolean success = false;
try {
values = bigArrays.newLongArray(0, false);
extraValues = bigArrays.newFloatArray(0, false);
success = true;
} finally {
if (success == false) {
close();
}
}
}
/**
* Collects a {@code value} into a {@code bucket}.
* <p>
* It may or may not be inserted in the heap, depending on if it is better than the current root.
* </p>
*/
public void collect(long value, float extraValue, int bucket) {
long rootIndex = (long) bucket * bucketSize;
if (inHeapMode(bucket)) {
if (betterThan(value, values.get(rootIndex), extraValue, extraValues.get(rootIndex))) {
values.set(rootIndex, value);
extraValues.set(rootIndex, extraValue);
downHeap(rootIndex, 0, bucketSize);
}
return;
}
// Gathering mode
long requiredSize = rootIndex + bucketSize;
if (values.size() < requiredSize) {
grow(bucket);
}
int next = getNextGatherOffset(rootIndex);
assert 0 <= next && next < bucketSize
: "Expected next to be in the range of valid buckets [0 <= " + next + " < " + bucketSize + "]";
long index = next + rootIndex;
values.set(index, value);
extraValues.set(index, extraValue);
if (next == 0) {
heapMode.set(bucket);
heapify(rootIndex, bucketSize);
} else {
setNextGatherOffset(rootIndex, next - 1);
}
}
/**
* The order of the sort.
*/
public SortOrder getOrder() {
return order;
}
/**
* The number of values to store per bucket.
*/
public int getBucketSize() {
return bucketSize;
}
/**
* Get the first and last indexes (inclusive, exclusive) of the values for a bucket.
* Returns [0, 0] if the bucket has never been collected.
*/
private Tuple<Long, Long> getBucketValuesIndexes(int bucket) {
long rootIndex = (long) bucket * bucketSize;
if (rootIndex >= values.size()) {
// We've never seen this bucket.
return Tuple.tuple(0L, 0L);
}
long start = inHeapMode(bucket) ? rootIndex : (rootIndex + getNextGatherOffset(rootIndex) + 1);
long end = rootIndex + bucketSize;
return Tuple.tuple(start, end);
}
/**
* Merge the values from {@code other}'s {@code otherGroupId} into {@code groupId}.
*/
public void merge(int groupId, LongFloatBucketedSort other, int otherGroupId) {
var otherBounds = other.getBucketValuesIndexes(otherGroupId);
// TODO: This can be improved for heapified buckets by making use of the heap structures
for (long i = otherBounds.v1(); i < otherBounds.v2(); i++) {
collect(other.values.get(i), other.extraValues.get(i), groupId);
}
}
/**
* Creates a block with the values from the {@code selected} groups.
*/
public void toBlocks(BlockFactory blockFactory, Block[] blocks, int offset, IntVector selected) {
// Check if the selected groups are all empty, to avoid allocating extra memory
if (allSelectedGroupsAreEmpty(selected)) {
Block constantNullBlock = blockFactory.newConstantNullBlock(selected.getPositionCount());
constantNullBlock.incRef();
blocks[offset] = constantNullBlock;
blocks[offset + 1] = constantNullBlock;
return;
}
try (
var builder = blockFactory.newLongBlockBuilder(selected.getPositionCount());
var extraBuilder = blockFactory.newFloatBlockBuilder(selected.getPositionCount())
) {
for (int s = 0; s < selected.getPositionCount(); s++) {
int bucket = selected.getInt(s);
var bounds = getBucketValuesIndexes(bucket);
var rootIndex = bounds.v1();
var size = bounds.v2() - bounds.v1();
if (size == 0) {
builder.appendNull();
extraBuilder.appendNull();
continue;
}
if (size == 1) {
builder.appendLong(values.get(rootIndex));
extraBuilder.appendFloat(extraValues.get(rootIndex));
continue;
}
// If we are in the gathering mode, we need to heapify before sorting.
if (inHeapMode(bucket) == false) {
heapify(rootIndex, (int) size);
}
heapSort(rootIndex, (int) size);
builder.beginPositionEntry();
extraBuilder.beginPositionEntry();
for (int i = 0; i < size; i++) {
builder.appendLong(values.get(rootIndex + i));
extraBuilder.appendFloat(extraValues.get(rootIndex + i));
}
builder.endPositionEntry();
extraBuilder.endPositionEntry();
}
blocks[offset] = builder.build();
blocks[offset + 1] = extraBuilder.build();
}
}
/**
* Checks if the selected groups are all empty.
*/
private boolean allSelectedGroupsAreEmpty(IntVector selected) {
return IntStream.range(0, selected.getPositionCount()).map(selected::getInt).noneMatch(bucket -> {
var bounds = this.getBucketValuesIndexes(bucket);
var size = bounds.v2() - bounds.v1();
return size > 0;
});
}
/**
* Is this bucket a min heap {@code true} or in gathering mode {@code false}?
*/
private boolean inHeapMode(int bucket) {
return heapMode.get(bucket);
}
/**
* Get the next index that should be "gathered" for a bucket rooted
* at {@code rootIndex}.
*/
private int getNextGatherOffset(long rootIndex) {
return (int) values.get(rootIndex);
}
/**
* Set the next index that should be "gathered" for a bucket rooted
* at {@code rootIndex}.
*/
private void setNextGatherOffset(long rootIndex, int offset) {
values.set(rootIndex, offset);
}
/**
* {@code true} if the entry at index {@code lhs} is "better" than
* the entry at {@code rhs}. "Better" in this means "lower" for
* {@link SortOrder#ASC} and "higher" for {@link SortOrder#DESC}.
*/
private boolean betterThan(long lhs, long rhs, float lhsExtra, float rhsExtra) {
int res = Long.compare(lhs, rhs);
if (res != 0) {
return getOrder().reverseMul() * res < 0;
}
res = Float.compare(lhsExtra, rhsExtra);
return getOrder().reverseMul() * res < 0;
}
/**
* Swap the data at two indices.
*/
private void swap(long lhs, long rhs) {
var tmp = values.get(lhs);
values.set(lhs, values.get(rhs));
values.set(rhs, tmp);
var tmpExtra = extraValues.get(lhs);
extraValues.set(lhs, extraValues.get(rhs));
extraValues.set(rhs, tmpExtra);
}
/**
* Allocate storage for more buckets and store the "next gather offset"
* for those new buckets. We always grow the storage by whole bucket's
* worth of slots at a time. We never allocate space for partial buckets.
*/
private void grow(int bucket) {
long oldMax = values.size();
assert oldMax % bucketSize == 0;
long newSize = BigArrays.overSize(((long) bucket + 1) * bucketSize, PageCacheRecycler.LONG_PAGE_SIZE, Long.BYTES);
// Round up to the next full bucket.
newSize = (newSize + bucketSize - 1) / bucketSize;
values = bigArrays.resize(values, newSize * bucketSize);
// Round up to the next full bucket.
extraValues = bigArrays.resize(extraValues, newSize * bucketSize);
// Set the next gather offsets for all newly allocated buckets.
fillGatherOffsets(oldMax);
}
/**
* Maintain the "next gather offsets" for newly allocated buckets.
*/
private void fillGatherOffsets(long startingAt) {
int nextOffset = getBucketSize() - 1;
for (long bucketRoot = startingAt; bucketRoot < values.size(); bucketRoot += getBucketSize()) {
setNextGatherOffset(bucketRoot, nextOffset);
}
}
/**
* Heapify a bucket whose entries are in random order.
* <p>
* This works by validating the heap property on each node, iterating
* "upwards", pushing any out of order parents "down". Check out the
* <a href="https://en.wikipedia.org/w/index.php?title=Binary_heap&oldid=940542991#Building_a_heap">wikipedia</a>
* entry on binary heaps for more about this.
* </p>
* <p>
* While this *looks* like it could easily be {@code O(n * log n)}, it is
* a fairly well studied algorithm attributed to Floyd. There's
* been a bunch of work that puts this at {@code O(n)}, close to 1.88n worst
* case.
* </p>
* <ul>
* <li>Hayward, Ryan; McDiarmid, Colin (1991).
* <a href="https://web.archive.org/web/20160205023201/http://www.stats.ox.ac.uk/__data/assets/pdf_file/0015/4173/heapbuildjalg.pdf">
* Average Case Analysis of Heap Building byRepeated Insertion</a> J. Algorithms.
* <li>D.E. Knuth, ”The Art of Computer Programming, Vol. 3, Sorting and Searching”</li>
* </ul>
* @param rootIndex the index the start of the bucket
*/
private void heapify(long rootIndex, int heapSize) {
int maxParent = heapSize / 2 - 1;
for (int parent = maxParent; parent >= 0; parent--) {
downHeap(rootIndex, parent, heapSize);
}
}
/**
* Sorts all the values in the heap using heap sort algorithm.
* This runs in {@code O(n log n)} time.
* @param rootIndex index of the start of the bucket
* @param heapSize Number of values that belong to the heap.
* Can be less than bucketSize.
* In such a case, the remaining values in range
* (rootIndex + heapSize, rootIndex + bucketSize)
* are *not* considered part of the heap.
*/
private void heapSort(long rootIndex, int heapSize) {
while (heapSize > 0) {
swap(rootIndex, rootIndex + heapSize - 1);
heapSize--;
downHeap(rootIndex, 0, heapSize);
}
}
/**
* Correct the heap invariant of a parent and its children. This
* runs in {@code O(log n)} time.
* @param rootIndex index of the start of the bucket
* @param parent Index within the bucket of the parent to check.
* For example, 0 is the "root".
* @param heapSize Number of values that belong to the heap.
* Can be less than bucketSize.
* In such a case, the remaining values in range
* (rootIndex + heapSize, rootIndex + bucketSize)
* are *not* considered part of the heap.
*/
private void downHeap(long rootIndex, int parent, int heapSize) {
while (true) {
long parentIndex = rootIndex + parent;
int worst = parent;
long worstIndex = parentIndex;
int leftChild = parent * 2 + 1;
long leftIndex = rootIndex + leftChild;
if (leftChild < heapSize) {
if (betterThan(values.get(worstIndex), values.get(leftIndex), extraValues.get(worstIndex), extraValues.get(leftIndex))) {
worst = leftChild;
worstIndex = leftIndex;
}
int rightChild = leftChild + 1;
long rightIndex = rootIndex + rightChild;
if (rightChild < heapSize
&& betterThan(
values.get(worstIndex),
values.get(rightIndex),
extraValues.get(worstIndex),
extraValues.get(rightIndex)
)) {
worst = rightChild;
worstIndex = rightIndex;
}
}
if (worst == parent) {
break;
}
swap(worstIndex, parentIndex);
parent = worst;
}
}
@Override
public final void close() {
Releasables.close(values, extraValues, heapMode);
}
}
|
LongFloatBucketedSort
|
java
|
apache__kafka
|
streams/src/test/java/org/apache/kafka/streams/state/internals/RocksDBTimeOrderedSessionSchemaWithoutIndexSegmentedBytesStoreTest.java
|
{
"start": 857,
"end": 1095
}
|
class ____ extends AbstractDualSchemaRocksDBSegmentedBytesStoreTest {
@Override
SchemaType schemaType() {
return SchemaType.SessionSchemaWithoutIndex;
}
}
|
RocksDBTimeOrderedSessionSchemaWithoutIndexSegmentedBytesStoreTest
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/ManagedRefEndpointTest.java
|
{
"start": 1465,
"end": 3533
}
|
class ____ extends SpringTestSupport {
@Override
protected boolean useJmx() {
return true;
}
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/spring/management/ManagedRefEndpointTest.xml");
}
protected MBeanServer getMBeanServer() {
return context.getManagementStrategy().getManagementAgent().getMBeanServer();
}
@Test
public void testRef() throws Exception {
// fire a message to get it running
getMockEndpoint("mock:result").expectedMessageCount(1);
getMockEndpoint("foo").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
MBeanServer mbeanServer = getMBeanServer();
Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=producers,*"), null);
assertEquals(2, set.size());
for (ObjectName on : set) {
boolean registered = mbeanServer.isRegistered(on);
assertEquals(true, registered, "Should be registered");
String uri = (String) mbeanServer.getAttribute(on, "EndpointUri");
assertTrue(uri.equals("mock://foo") || uri.equals("mock://result"), uri);
// should be started
String state = (String) mbeanServer.getAttribute(on, "State");
assertEquals(ServiceStatus.Started.name(), state, "Should be started");
}
set = mbeanServer.queryNames(new ObjectName("*:type=endpoints,*"), null);
assertEquals(4, set.size());
for (ObjectName on : set) {
boolean registered = mbeanServer.isRegistered(on);
assertTrue(registered, "Should be registered");
String uri = (String) mbeanServer.getAttribute(on, "EndpointUri");
assertTrue(uri.equals("direct://start") || uri.equals("mock://foo")
|| uri.equals("mock://result") || uri.equals("ref://foo"), uri);
}
}
}
|
ManagedRefEndpointTest
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest87.java
|
{
"start": 1005,
"end": 2954
}
|
class ____ extends MysqlTest {
public void test_one() throws Exception {
String sql = "CREATE TABLE `test_4` (\n" +
" `id` bigint(20) zerofill unsigNed NOT NULL AUTO_INCREMENT COMMENT 'id',\n" +
" `c_tinyint` tinyint(4) DEFAULT '1' COMMENT 'tinyint',\n" +
" PRIMARY KEY (`id`)\n" +
") ENGINE=InnoDB AUTO_INCREMENT=1769531 DEFAULT CHARSET=utf8mb4 COMMENT='10000000'";
MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.KeepComments);
SQLStatement stmt = parser.parseCreateTable();
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
//
// Column column = visitor.getColumn("tb_custom_vip_show_message", "custom_vip_show_message_seq");
// assertNotNull(column);
// assertEquals("INT", column.getDataType());
System.out.println(stmt);
{
String output = SQLUtils.toMySqlString(stmt);
assertEquals("CREATE TABLE `test_4` (\n" +
"\t`id` bigint(20) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT COMMENT 'id',\n" +
"\t`c_tinyint` tinyint(4) DEFAULT '1' COMMENT 'tinyint',\n" +
"\tPRIMARY KEY (`id`)\n" +
") ENGINE = InnoDB AUTO_INCREMENT = 1769531 CHARSET = utf8mb4 COMMENT '10000000'", output);
}
{
String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
assertEquals("create table `test_4` (\n" +
"\t`id` bigint(20) unsigned zerofill not null auto_increment comment 'id',\n" +
"\t`c_tinyint` tinyint(4) default '1' comment 'tinyint',\n" +
"\tprimary key (`id`)\n" +
") engine = InnoDB auto_increment = 1769531 charset = utf8mb4 comment '10000000'", output);
}
}
}
|
MySqlCreateTableTest87
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/EmbeddableAndMappedSuperClassWithGenericsTest.java
|
{
"start": 3852,
"end": 4114
}
|
class ____<T> {
private Edition edition;
@Column(name = "CODE_COLUMN")
private T code;
public Book() {
}
public Book(Edition edition, T code) {
this.edition = edition;
this.code = code;
}
}
@Entity(name = "PopularBook")
public static
|
Book
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Super.java
|
{
"start": 142,
"end": 290
}
|
class ____ {
protected String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
Super
|
java
|
apache__flink
|
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/utils/OperationExpressionsUtils.java
|
{
"start": 7073,
"end": 10376
}
|
class ____
extends ApiExpressionDefaultVisitor<Expression> {
private final Map<Expression, String> aggregates;
private final Map<Expression, String> properties;
private AggregationAndPropertiesReplacer(
Map<Expression, String> aggregates, Map<Expression, String> properties) {
this.aggregates = aggregates;
this.properties = properties;
}
@Override
public Expression visit(LookupCallExpression unresolvedCall) {
throw new IllegalStateException(
"All lookup calls should be resolved by now. Got: " + unresolvedCall);
}
@Override
public Expression visit(CallExpression call) {
throw new IllegalStateException("All calls should still be unresolved by now.");
}
@Override
public Expression visit(UnresolvedCallExpression unresolvedCall) {
if (aggregates.get(unresolvedCall) != null) {
return unresolvedRef(aggregates.get(unresolvedCall));
} else if (properties.get(unresolvedCall) != null) {
return unresolvedRef(properties.get(unresolvedCall));
}
final List<Expression> args =
unresolvedCall.getChildren().stream()
.map(c -> c.accept(this))
.collect(Collectors.toList());
return unresolvedCall.replaceArgs(args);
}
@Override
protected Expression defaultMethod(Expression expression) {
return expression;
}
}
// --------------------------------------------------------------------------------------------
// utils that can be used both before and after resolution
// --------------------------------------------------------------------------------------------
private static final ExtractNameVisitor extractNameVisitor = new ExtractNameVisitor();
/**
* Extracts names from given expressions if they have one. Expressions that have names are:
*
* <ul>
* <li>{@link FieldReferenceExpression}
* <li>{@link TableReferenceExpression}
* <li>{@link LocalReferenceExpression}
* <li>{@link BuiltInFunctionDefinitions#AS}
* </ul>
*
* @param expressions list of expressions to extract names from
* @return corresponding list of optional names
*/
public static List<Optional<String>> extractNames(List<ResolvedExpression> expressions) {
return expressions.stream()
.map(OperationExpressionsUtils::extractName)
.collect(Collectors.toList());
}
/**
* Extracts name from given expression if it has one. Expressions that have names are:
*
* <ul>
* <li>{@link FieldReferenceExpression}
* <li>{@link TableReferenceExpression}
* <li>{@link LocalReferenceExpression}
* <li>{@link BuiltInFunctionDefinitions#AS}
* </ul>
*
* @param expression expression to extract name from
* @return optional name of given expression
*/
public static Optional<String> extractName(Expression expression) {
return expression.accept(extractNameVisitor);
}
private static
|
AggregationAndPropertiesReplacer
|
java
|
netty__netty
|
testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketSslGreetingTest.java
|
{
"start": 2475,
"end": 7947
}
|
class ____ extends AbstractSocketTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocketSslGreetingTest.class);
private static final LogLevel LOG_LEVEL = LogLevel.TRACE;
private static final File CERT_FILE;
private static final File KEY_FILE;
static {
try {
X509Bundle cert = new CertificateBuilder()
.subject("cn=localhost")
.setIsCertificateAuthority(true)
.buildSelfSigned();
CERT_FILE = cert.toTempCertChainPem();
KEY_FILE = cert.toTempPrivateKeyPem();
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Collection<Object[]> data() throws Exception {
List<SslContext> serverContexts = new ArrayList<SslContext>();
serverContexts.add(SslContextBuilder.forServer(CERT_FILE, KEY_FILE).sslProvider(SslProvider.JDK).build());
List<SslContext> clientContexts = new ArrayList<SslContext>();
clientContexts.add(SslContextBuilder.forClient().sslProvider(SslProvider.JDK)
.endpointIdentificationAlgorithm(null).trustManager(CERT_FILE).build());
boolean hasOpenSsl = OpenSsl.isAvailable();
if (hasOpenSsl) {
serverContexts.add(SslContextBuilder.forServer(CERT_FILE, KEY_FILE)
.sslProvider(SslProvider.OPENSSL).build());
clientContexts.add(SslContextBuilder.forClient().sslProvider(SslProvider.OPENSSL)
.endpointIdentificationAlgorithm(null)
.trustManager(CERT_FILE).build());
} else {
logger.warn("OpenSSL is unavailable and thus will not be tested.", OpenSsl.unavailabilityCause());
}
List<Object[]> params = new ArrayList<Object[]>();
for (SslContext sc: serverContexts) {
for (SslContext cc: clientContexts) {
params.add(new Object[] { sc, cc, true });
params.add(new Object[] { sc, cc, false });
}
}
return params;
}
private static SslHandler newSslHandler(SslContext sslCtx, ByteBufAllocator allocator, Executor executor) {
if (executor == null) {
return sslCtx.newHandler(allocator);
} else {
return sslCtx.newHandler(allocator, executor);
}
}
// Test for https://github.com/netty/netty/pull/2437
@ParameterizedTest(name = "{index}: serverEngine = {0}, clientEngine = {1}, delegate = {2}")
@MethodSource("data")
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testSslGreeting(final SslContext serverCtx, final SslContext clientCtx, final boolean delegate,
TestInfo testInfo) throws Throwable {
run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
@Override
public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
testSslGreeting(sb, cb, serverCtx, clientCtx, delegate);
}
});
}
public void testSslGreeting(ServerBootstrap sb, Bootstrap cb, final SslContext serverCtx,
final SslContext clientCtx, boolean delegate) throws Throwable {
final ServerHandler sh = new ServerHandler();
final ClientHandler ch = new ClientHandler();
final ExecutorService executorService = delegate ? Executors.newCachedThreadPool() : null;
try {
sb.childHandler(new ChannelInitializer<Channel>() {
@Override
public void initChannel(Channel sch) throws Exception {
ChannelPipeline p = sch.pipeline();
p.addLast(newSslHandler(serverCtx, sch.alloc(), executorService));
p.addLast(new LoggingHandler(LOG_LEVEL));
p.addLast(sh);
}
});
cb.handler(new ChannelInitializer<Channel>() {
@Override
public void initChannel(Channel sch) throws Exception {
ChannelPipeline p = sch.pipeline();
p.addLast(newSslHandler(clientCtx, sch.alloc(), executorService));
p.addLast(new LoggingHandler(LOG_LEVEL));
p.addLast(ch);
}
});
Channel sc = sb.bind().sync().channel();
Channel cc = cb.connect(sc.localAddress()).sync().channel();
ch.latch.await();
sh.channel.close().awaitUninterruptibly();
cc.close().awaitUninterruptibly();
sc.close().awaitUninterruptibly();
if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
throw sh.exception.get();
}
if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
throw ch.exception.get();
}
if (sh.exception.get() != null) {
throw sh.exception.get();
}
if (ch.exception.get() != null) {
throw ch.exception.get();
}
} finally {
if (executorService != null) {
executorService.shutdown();
}
}
}
private static
|
SocketSslGreetingTest
|
java
|
dropwizard__dropwizard
|
dropwizard-migrations/src/main/java/io/dropwizard/migrations/AbstractLiquibaseCommand.java
|
{
"start": 1193,
"end": 5717
}
|
class ____<T extends Configuration> extends ConfiguredCommand<T> {
private final DatabaseConfiguration<T> strategy;
private final Class<T> configurationClass;
private final String migrationsFileName;
protected AbstractLiquibaseCommand(String name,
String description,
DatabaseConfiguration<T> strategy,
Class<T> configurationClass,
String migrationsFileName) {
super(name, description);
this.strategy = strategy;
this.configurationClass = configurationClass;
this.migrationsFileName = migrationsFileName;
}
@Override
protected Class<T> getConfigurationClass() {
return configurationClass;
}
@Override
public void configure(Subparser subparser) {
super.configure(subparser);
subparser.addArgument("--migrations")
.dest("migrations-file")
.help("the file containing the Liquibase migrations for the application");
subparser.addArgument("--catalog")
.dest("catalog")
.help("Specify the database catalog (use database default if omitted)");
subparser.addArgument("--schema")
.dest("schema")
.help("Specify the database schema (use database default if omitted)");
subparser.addArgument("--analytics-enabled")
.setDefault(false)
.dest("analytics-enabled")
.help("This turns on analytics gathering for that single occurrence of a command.");
}
@Override
@SuppressWarnings("UseOfSystemOutOrSystemErr")
protected void run(@Nullable Bootstrap<T> bootstrap, Namespace namespace, T configuration) throws Exception {
final PooledDataSourceFactory dbConfig = strategy.getDataSourceFactory(configuration);
dbConfig.asSingleConnectionPool();
try (final CloseableLiquibase liquibase = openLiquibase(dbConfig, namespace)) {
run(namespace, liquibase);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.err);
throw e;
}
}
CloseableLiquibase openLiquibase(final PooledDataSourceFactory dataSourceFactory, final Namespace namespace)
throws SQLException, LiquibaseException {
final CloseableLiquibase liquibase;
final ManagedDataSource dataSource = dataSourceFactory.build(new MetricRegistry(), "liquibase");
final Database database = createDatabase(dataSource, namespace);
final String migrationsFile = namespace.getString("migrations-file");
if (migrationsFile == null) {
liquibase = new CloseableLiquibaseWithClassPathMigrationsFile(dataSource, database, migrationsFileName);
} else {
liquibase = new CloseableLiquibaseWithFileSystemMigrationsFile(dataSource, database, migrationsFile);
}
final Boolean analyticsEnabled = namespace.getBoolean("analytics-enabled");
try {
Map<String, Object> values = Map.of(
"liquibase.analytics.enabled", analyticsEnabled != null && analyticsEnabled,
"liquibase.analytics.logLevel", Level.FINEST // OFF is mapped to SLF4J ERROR level...
);
Scope.enter(values);
} catch (Exception e) {
throw new LiquibaseException(e);
}
return liquibase;
}
private Database createDatabase(
ManagedDataSource dataSource,
Namespace namespace
) throws SQLException, LiquibaseException {
final DatabaseConnection conn = new JdbcConnection(dataSource.getConnection());
final Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(conn);
final String catalogName = namespace.getString("catalog");
final String schemaName = namespace.getString("schema");
if (database.supports(Catalog.class) && catalogName != null) {
database.setDefaultCatalogName(catalogName);
database.setOutputDefaultCatalog(true);
}
if (database.supports(Schema.class) && schemaName != null) {
database.setDefaultSchemaName(schemaName);
database.setOutputDefaultSchema(true);
}
return database;
}
protected abstract void run(Namespace namespace, Liquibase liquibase) throws Exception;
}
|
AbstractLiquibaseCommand
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/float2darray/Float2DArrayAssert_hasDimensions_Test.java
|
{
"start": 924,
"end": 1272
}
|
class ____ extends Float2DArrayAssertBaseTest {
@Override
protected Float2DArrayAssert invoke_api_method() {
return assertions.hasDimensions(1, 2);
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertHasDimensions(getInfo(assertions), getActual(assertions), 1, 2);
}
}
|
Float2DArrayAssert_hasDimensions_Test
|
java
|
quarkusio__quarkus
|
independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/ClientProxies.java
|
{
"start": 3175,
"end": 3505
}
|
class ____ {
public final Collection<Class<?>> clientClasses;
public final Map<Class<?>, String> failures;
public ClientData(Collection<Class<?>> clientClasses, Map<Class<?>, String> failures) {
this.clientClasses = clientClasses;
this.failures = failures;
}
}
}
|
ClientData
|
java
|
micronaut-projects__micronaut-core
|
http/src/main/java/io/micronaut/http/exceptions/ConnectionClosedException.java
|
{
"start": 780,
"end": 1170
}
|
class ____ extends HttpException {
/**
* @param message The message
*/
public ConnectionClosedException(String message) {
super(message);
}
/**
* @param message The message
* @param cause The throwable
*/
public ConnectionClosedException(String message, Throwable cause) {
super(message, cause);
}
}
|
ConnectionClosedException
|
java
|
elastic__elasticsearch
|
x-pack/plugin/sql/sql-action/src/main/java/org/elasticsearch/xpack/sql/action/SqlQueryRequestBuilder.java
|
{
"start": 885,
"end": 5517
}
|
class ____ extends ActionRequestBuilder<SqlQueryRequest, SqlQueryResponse> {
public SqlQueryRequestBuilder(ElasticsearchClient client) {
this(
client,
"",
emptyList(),
null,
emptyMap(),
Protocol.TIME_ZONE,
null,
Protocol.FETCH_SIZE,
Protocol.REQUEST_TIMEOUT,
Protocol.PAGE_TIMEOUT,
false,
"",
new RequestInfo(Mode.PLAIN),
Protocol.FIELD_MULTI_VALUE_LENIENCY,
Protocol.INDEX_INCLUDE_FROZEN,
Protocol.DEFAULT_WAIT_FOR_COMPLETION_TIMEOUT,
Protocol.DEFAULT_KEEP_ON_COMPLETION,
Protocol.DEFAULT_KEEP_ALIVE,
Protocol.ALLOW_PARTIAL_SEARCH_RESULTS
);
}
public SqlQueryRequestBuilder(
ElasticsearchClient client,
String query,
List<SqlTypedParamValue> params,
QueryBuilder filter,
Map<String, Object> runtimeMappings,
ZoneId zoneId,
String catalog,
int fetchSize,
TimeValue requestTimeout,
TimeValue pageTimeout,
boolean columnar,
String nextPageInfo,
RequestInfo requestInfo,
boolean multiValueFieldLeniency,
boolean indexIncludeFrozen,
TimeValue waitForCompletionTimeout,
boolean keepOnCompletion,
TimeValue keepAlive,
boolean allowPartialSearchResults
) {
super(
client,
SqlQueryAction.INSTANCE,
new SqlQueryRequest(
query,
params,
filter,
runtimeMappings,
zoneId,
catalog,
fetchSize,
requestTimeout,
pageTimeout,
columnar,
nextPageInfo,
requestInfo,
multiValueFieldLeniency,
indexIncludeFrozen,
waitForCompletionTimeout,
keepOnCompletion,
keepAlive,
allowPartialSearchResults
)
);
}
public SqlQueryRequestBuilder query(String query) {
request.query(query);
return this;
}
public SqlQueryRequestBuilder mode(String mode) {
request.mode(mode);
return this;
}
public SqlQueryRequestBuilder mode(Mode mode) {
request.mode(mode);
return this;
}
public SqlQueryRequestBuilder version(String version) {
request.version(version);
return this;
}
public SqlQueryRequestBuilder cursor(String cursor) {
request.cursor(cursor);
return this;
}
public SqlQueryRequestBuilder filter(QueryBuilder filter) {
request.filter(filter);
return this;
}
public SqlQueryRequestBuilder runtimeMappings(Map<String, Object> runtimeMappings) {
request.runtimeMappings(runtimeMappings);
return this;
}
public SqlQueryRequestBuilder zoneId(ZoneId zoneId) {
request.zoneId(zoneId);
return this;
}
public SqlQueryRequestBuilder catalog(String catalog) {
request.catalog(catalog);
return this;
}
public SqlQueryRequestBuilder requestTimeout(TimeValue timeout) {
request.requestTimeout(timeout);
return this;
}
public SqlQueryRequestBuilder pageTimeout(TimeValue timeout) {
request.pageTimeout(timeout);
return this;
}
public SqlQueryRequestBuilder columnar(boolean columnar) {
request.columnar(columnar);
return this;
}
public SqlQueryRequestBuilder fetchSize(int fetchSize) {
request.fetchSize(fetchSize);
return this;
}
public SqlQueryRequestBuilder multiValueFieldLeniency(boolean lenient) {
request.fieldMultiValueLeniency(lenient);
return this;
}
public SqlQueryRequestBuilder waitForCompletionTimeout(TimeValue waitForCompletionTimeout) {
request.waitForCompletionTimeout(waitForCompletionTimeout);
return this;
}
public SqlQueryRequestBuilder keepOnCompletion(boolean keepOnCompletion) {
request.keepOnCompletion(keepOnCompletion);
return this;
}
public SqlQueryRequestBuilder keepAlive(TimeValue keepAlive) {
request.keepAlive(keepAlive);
return this;
}
public SqlQueryRequestBuilder allowPartialSearchResults(boolean allowPartialSearchResults) {
request.allowPartialSearchResults(allowPartialSearchResults);
return this;
}
}
|
SqlQueryRequestBuilder
|
java
|
micronaut-projects__micronaut-core
|
test-suite/src/test/java/io/micronaut/docs/ioc/validation/custom/HolidayService.java
|
{
"start": 795,
"end": 1490
}
|
class ____ {
// tag::method[]
public String startHoliday(@NotBlank String person,
@DurationPattern String duration) {
final Duration d = Duration.parse(duration);
return "Person " + person + " is off on holiday for " + d.toMinutes() + " minutes";
}
// end::method[]
public String startHoliday(@DurationPattern String fromDuration, @DurationPattern String toDuration, @NotBlank String person
) {
final Duration d = Duration.parse(fromDuration);
final Duration e = Duration.parse(toDuration);
return "Person " + person + " is off on holiday from " + d + " to " + e;
}
}
// end::class[]
|
HolidayService
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/spi/DatabaseObjectDetails.java
|
{
"start": 486,
"end": 843
}
|
interface ____ extends Annotation {
/**
* The catalog in which the object exists
*/
String catalog();
/**
* Setter for {@linkplain #catalog()}
*/
void catalog(String catalog);
/**
* The schema in which the object exists
*/
String schema();
/**
* Setter for {@linkplain #schema()}
*/
void schema(String schema);
}
|
DatabaseObjectDetails
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/context/annotation/EnableLoadTimeWeavingTests.java
|
{
"start": 3123,
"end": 3383
}
|
class ____ implements LoadTimeWeavingConfigurer {
@Override
public LoadTimeWeaver getLoadTimeWeaver() {
return mock();
}
}
@Configuration
@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.ENABLED)
static
|
EnableLTWConfig_withAjWeavingAutodetect
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/logical/LogicalTypeVisitor.java
|
{
"start": 1331,
"end": 2735
}
|
interface ____<R> {
R visit(CharType charType);
R visit(VarCharType varCharType);
R visit(BooleanType booleanType);
R visit(BinaryType binaryType);
R visit(VarBinaryType varBinaryType);
R visit(DecimalType decimalType);
R visit(TinyIntType tinyIntType);
R visit(SmallIntType smallIntType);
R visit(IntType intType);
R visit(BigIntType bigIntType);
R visit(FloatType floatType);
R visit(DoubleType doubleType);
R visit(DateType dateType);
R visit(TimeType timeType);
R visit(TimestampType timestampType);
R visit(ZonedTimestampType zonedTimestampType);
R visit(LocalZonedTimestampType localZonedTimestampType);
R visit(YearMonthIntervalType yearMonthIntervalType);
R visit(DayTimeIntervalType dayTimeIntervalType);
R visit(ArrayType arrayType);
R visit(MultisetType multisetType);
R visit(MapType mapType);
R visit(RowType rowType);
R visit(DistinctType distinctType);
R visit(StructuredType structuredType);
R visit(NullType nullType);
R visit(RawType<?> rawType);
R visit(SymbolType<?> symbolType);
default R visit(DescriptorType descriptorType) {
return visit((LogicalType) descriptorType);
}
default R visit(VariantType variantType) {
return visit((LogicalType) variantType);
}
R visit(LogicalType other);
}
|
LogicalTypeVisitor
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementServerProperties.java
|
{
"start": 1411,
"end": 3437
}
|
class ____ {
/**
* Management endpoint HTTP port (uses the same port as the application by default).
* Configure a different port to use management-specific SSL.
*/
private @Nullable Integer port;
/**
* Network address to which the management endpoints should bind. Requires a custom
* management.server.port.
*/
private @Nullable InetAddress address;
/**
* Management endpoint base path (for instance, '/management'). Requires a custom
* management.server.port.
*/
private String basePath = "";
@NestedConfigurationProperty
private @Nullable Ssl ssl;
/**
* Returns the management port or {@code null} if the
* {@link ServerProperties#getPort() server port} should be used.
* @return the port
* @see #setPort(Integer)
*/
public @Nullable Integer getPort() {
return this.port;
}
/**
* Sets the port of the management server, use {@code null} if the
* {@link ServerProperties#getPort() server port} should be used. Set to 0 to use a
* random port or set to -1 to disable.
* @param port the port
*/
public void setPort(@Nullable Integer port) {
this.port = port;
}
public @Nullable InetAddress getAddress() {
return this.address;
}
public void setAddress(@Nullable InetAddress address) {
this.address = address;
}
public String getBasePath() {
return this.basePath;
}
public void setBasePath(String basePath) {
this.basePath = cleanBasePath(basePath);
}
public @Nullable Ssl getSsl() {
return this.ssl;
}
public void setSsl(@Nullable Ssl ssl) {
this.ssl = ssl;
}
@Contract("!null -> !null")
private @Nullable String cleanBasePath(@Nullable String basePath) {
String candidate = null;
if (StringUtils.hasLength(basePath)) {
candidate = basePath.strip();
}
if (StringUtils.hasText(candidate)) {
if (!candidate.startsWith("/")) {
candidate = "/" + candidate;
}
if (candidate.endsWith("/")) {
candidate = candidate.substring(0, candidate.length() - 1);
}
}
return candidate;
}
}
|
ManagementServerProperties
|
java
|
quarkusio__quarkus
|
extensions/smallrye-openapi/deployment/src/main/java/io/quarkus/smallrye/openapi/deployment/filter/DefaultInfoFilter.java
|
{
"start": 328,
"end": 1150
}
|
class ____ implements OASFilter {
final Config config;
public DefaultInfoFilter(Config config) {
this.config = config;
}
@Override
public void filterOpenAPI(OpenAPI openAPI) {
Info info = openAPI.getInfo();
if (info == null) {
info = OASFactory.createInfo();
openAPI.setInfo(info);
}
if (info.getTitle() == null) {
String title = config.getOptionalValue("quarkus.application.name", String.class).orElse("Generated");
info.setTitle(title + " API");
}
if (info.getVersion() == null) {
String version = config.getOptionalValue("quarkus.application.version", String.class).orElse("1.0");
info.setVersion((version == null ? "1.0" : version));
}
}
}
|
DefaultInfoFilter
|
java
|
spring-projects__spring-framework
|
spring-r2dbc/src/test/java/org/springframework/r2dbc/connection/R2dbcTransactionManagerTests.java
|
{
"start": 28416,
"end": 30101
}
|
class ____ implements TransactionSynchronization {
private final int status;
public boolean beforeCommitCalled;
public boolean beforeCompletionCalled;
public boolean afterCommitCalled;
public boolean afterCompletionCalled;
TestTransactionSynchronization(int status) {
this.status = status;
}
@Override
public Mono<Void> suspend() {
return Mono.empty();
}
@Override
public Mono<Void> resume() {
return Mono.empty();
}
@Override
public Mono<Void> beforeCommit(boolean readOnly) {
if (this.status != TransactionSynchronization.STATUS_COMMITTED) {
fail("Should never be called");
}
return Mono.fromRunnable(() -> {
assertThat(this.beforeCommitCalled).isFalse();
this.beforeCommitCalled = true;
});
}
@Override
public Mono<Void> beforeCompletion() {
return Mono.fromRunnable(() -> {
assertThat(this.beforeCompletionCalled).isFalse();
this.beforeCompletionCalled = true;
});
}
@Override
public Mono<Void> afterCommit() {
if (this.status != TransactionSynchronization.STATUS_COMMITTED) {
fail("Should never be called");
}
return Mono.fromRunnable(() -> {
assertThat(this.afterCommitCalled).isFalse();
this.afterCommitCalled = true;
});
}
@Override
public Mono<Void> afterCompletion(int status) {
try {
return Mono.fromRunnable(() -> doAfterCompletion(status));
}
catch (Throwable ignored) {
}
return Mono.empty();
}
protected void doAfterCompletion(int status) {
assertThat(this.afterCompletionCalled).isFalse();
this.afterCompletionCalled = true;
assertThat(status).isEqualTo(this.status);
}
}
}
|
TestTransactionSynchronization
|
java
|
apache__flink
|
flink-tests/src/test/java/org/apache/flink/test/streaming/runtime/RecordAttributesPropagationITCase.java
|
{
"start": 2622,
"end": 4101
}
|
class ____ {
@Test
void testRecordAttributesPropagation() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
final SourceWithBacklog source1 = new SourceWithBacklog();
final SourceWithBacklog source2 = new SourceWithBacklog();
env.fromSource(source1, WatermarkStrategy.noWatermarks(), "source1")
.returns(Long.class)
.transform("my_op1", Types.LONG, new OneInputOperator())
.connect(
env.fromSource(source2, WatermarkStrategy.noWatermarks(), "source2")
.returns(Long.class))
.transform("my_op2", Types.LONG, new TwoInputOperator())
.addSink(new DiscardingSink<>());
env.execute();
final RecordAttributes backlog =
new RecordAttributesBuilder(Collections.emptyList()).setBacklog(true).build();
final RecordAttributes nonBacklog =
new RecordAttributesBuilder(Collections.emptyList()).setBacklog(false).build();
assertThat(OneInputOperator.receivedRecordAttributes).containsExactly(backlog, nonBacklog);
assertThat(TwoInputOperator.receivedRecordAttributes1).containsExactly(backlog, nonBacklog);
assertThat(TwoInputOperator.receivedRecordAttributes2).containsExactly(backlog, nonBacklog);
}
static
|
RecordAttributesPropagationITCase
|
java
|
spring-projects__spring-framework
|
spring-orm/src/main/java/org/springframework/orm/jpa/support/SharedEntityManagerBean.java
|
{
"start": 2389,
"end": 2724
}
|
class ____ extends EntityManagerFactoryAccessor
implements FactoryBean<EntityManager>, InitializingBean {
private @Nullable Class<? extends EntityManager> entityManagerInterface;
private boolean synchronizedWithTransaction = true;
private @Nullable EntityManager shared;
/**
* Specify the EntityManager
|
SharedEntityManagerBean
|
java
|
apache__camel
|
components/camel-guava-eventbus/src/test/java/org/apache/camel/component/guava/eventbus/GuavaEventBusConsumingDeadEventsTest.java
|
{
"start": 1266,
"end": 2570
}
|
class ____ extends CamelTestSupport {
@BindToRegistry("eventBus")
EventBus eventBus = new EventBus();
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("guava-eventbus:eventBus?listenerInterface=org.apache.camel.component.guava.eventbus.CustomListener")
.to("mock:customListenerEvents");
from("guava-eventbus:eventBus?listenerInterface=org.apache.camel.component.guava.eventbus.DeadEventListener")
.to("mock:deadEvents");
}
};
}
@Test
public void shouldForwardMessageToCamel() throws InterruptedException {
// Given
Date message = new Date();
// When
eventBus.post(message);
// Then
getMockEndpoint("mock:customListenerEvents").setExpectedMessageCount(0);
MockEndpoint.assertIsSatisfied(context);
getMockEndpoint("mock:deadEvents").setExpectedMessageCount(1);
MockEndpoint.assertIsSatisfied(context);
assertEquals(message,
getMockEndpoint("mock:deadEvents").getExchanges().get(0).getIn().getBody(DeadEvent.class).getEvent());
}
}
|
GuavaEventBusConsumingDeadEventsTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/CompositeIdRepeatedQueryTest.java
|
{
"start": 1108,
"end": 2230
}
|
class ____ {
@BeforeAll
public void setup(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
Person person = new Person("1", "Andrew");
Corporation corporation = new Corporation("2", "ibm");
Document document = new Document(3,"registration", person, corporation);
entityManager.persist( person );
entityManager.persist( corporation );
entityManager.persist( document );
}
);
}
@Test
public void testRepeatedQuery(EntityManagerFactoryScope scope){
scope.inTransaction(
entityManager -> {
String query = "SELECT d FROM Document d";
List<Document> resultList = entityManager.createQuery( query, Document.class ).getResultList();
assertThat(resultList.size()).isEqualTo( 1 );
Document document = resultList.get( 0 );
resultList = entityManager.createQuery( query, Document.class ).getResultList();
assertThat(resultList.size()).isEqualTo( 1 );
assertThat( resultList.get( 0 ) ).isSameAs( document );
}
);
}
@Entity(name = "Document")
@Table(name = "documents")
public static
|
CompositeIdRepeatedQueryTest
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
|
{
"start": 103571,
"end": 104153
}
|
interface ____<@ImmutableTypeParameter T> {
T get();
}
void test(ImmutableProvider<?> f) {
// BUG: Diagnostic contains:
test(ArrayList::new);
}
}
""")
.doTest();
}
@Test
public void lambda_immutableTypeParam() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import com.google.errorprone.annotations.ImmutableTypeParameter;
import java.util.ArrayList;
abstract
|
ImmutableProvider
|
java
|
google__guava
|
android/guava-testlib/src/com/google/common/testing/AbstractPackageSanityTests.java
|
{
"start": 15204,
"end": 16834
}
|
class
____<String, Class<?>> classMap = Maps.newTreeMap();
for (Class<?> cls : classes) {
classMap.put(cls.getName(), cls);
}
// Foo.class -> [FooTest.class, FooTests.class, FooTestSuite.class, ...]
Multimap<Class<?>, Class<?>> testClasses = HashMultimap.create();
LinkedHashSet<Class<?>> candidateClasses = new LinkedHashSet<>();
for (Class<?> cls : classes) {
Optional<String> testedClassName = TEST_SUFFIX.chop(cls.getName());
if (testedClassName.isPresent()) {
Class<?> testedClass = classMap.get(testedClassName.get());
if (testedClass != null) {
testClasses.put(testedClass, cls);
}
} else {
candidateClasses.add(cls);
}
}
List<Class<?>> result = new ArrayList<>();
NEXT_CANDIDATE:
for (Class<?> candidate : Iterables.filter(candidateClasses, classFilter)) {
for (Class<?> testClass : testClasses.get(candidate)) {
if (hasTest(testClass, explicitTestNames)) {
// covered by explicit test
continue NEXT_CANDIDATE;
}
}
result.add(candidate);
}
return result;
}
private List<Class<?>> loadClassesInPackage() throws IOException {
List<Class<?>> classes = new ArrayList<>();
String packageName = getClass().getPackage().getName();
for (ClassPath.ClassInfo classInfo :
ClassPath.from(getClass().getClassLoader()).getTopLevelClasses(packageName)) {
Class<?> cls;
try {
cls = classInfo.load();
} catch (NoClassDefFoundError e) {
// In case there were linking problems, this is probably not a
|
TreeMap
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest98.java
|
{
"start": 804,
"end": 1134
}
|
class ____ extends TestCase {
public void test_false() throws Exception {
WallProvider provider = new MySqlWallProvider();
provider.getConfig().setCommentAllow(false);
String sql = "select * from t where id = ? or ascii(0x7F) = 127";
assertFalse(provider.checkValid(sql));
}
}
|
MySqlWallTest98
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-client/runtime/src/main/java/io/quarkus/rest/client/reactive/ClientRedirectHandler.java
|
{
"start": 1281,
"end": 1447
}
|
interface ____ {
/**
* The priority with which the redirect handler will be executed
*/
int priority() default Priorities.USER;
}
|
ClientRedirectHandler
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriTemplateServletAnnotationControllerHandlerMethodTests.java
|
{
"start": 21900,
"end": 22829
}
|
class ____ {
@RequestMapping(value = {"/{category}/page/{page}", "/*/{category}/page/{page}"})
void category(@PathVariable String category, @PathVariable int page, Writer writer) throws IOException {
writer.write("handle1-");
writer.write("category-" + category);
writer.write("page-" + page);
}
@RequestMapping(value = {"/{category}", "/*/{category}"})
void category(@PathVariable String category, Writer writer) throws IOException {
writer.write("handle2-");
writer.write("category-" + category);
}
@RequestMapping(value = {""})
void category(Writer writer) throws IOException {
writer.write("handle3");
}
@RequestMapping(value = {"/page/{page}"})
void category(@PathVariable int page, Writer writer) throws IOException {
writer.write("handle4-");
writer.write("page-" + page);
}
}
@Controller
@RequestMapping("/*/menu/") // was /*/menu/**
public static
|
MultiPathController
|
java
|
quarkusio__quarkus
|
independent-projects/tools/codestarts/src/main/java/io/quarkus/devtools/codestarts/CodestartCatalogLoader.java
|
{
"start": 6756,
"end": 7145
}
|
class ____ implements CodestartPathLoader {
private final Path dir;
public DirectoryCodestartPathLoader(Path dir) {
this.dir = dir;
}
@Override
public <T> T loadResourceAsPath(String name, PathConsumer<T> consumer) throws IOException {
return consumer.consume(dir.resolve(name));
}
}
}
|
DirectoryCodestartPathLoader
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.