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
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/error/ShouldBeLessOrEqual_create_Test.java
|
{
"start": 1107,
"end": 2383
}
|
class ____ {
@Test
void should_create_error_message() {
// GIVEN
ErrorMessageFactory factory = shouldBeLessOrEqual(8, 6);
// WHEN
String message = factory.create(new TextDescription("Test"), new StandardRepresentation());
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" 8%n" +
"to be less than or equal to:%n" +
" 6 "));
}
@Test
void should_create_error_message_with_custom_comparison_strategy() {
// GIVEN
ErrorMessageFactory factory = shouldBeLessOrEqual(8, 6,
new ComparatorBasedComparisonStrategy(new AbsValueComparator<Integer>()));
// WHEN
String message = factory.create(new TextDescription("Test"), new StandardRepresentation());
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" 8%n" +
"to be less than or equal to:%n" +
" 6 when comparing values using AbsValueComparator"));
}
}
|
ShouldBeLessOrEqual_create_Test
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/XjComponentBuilderFactory.java
|
{
"start": 10815,
"end": 12979
}
|
class ____
extends AbstractComponentBuilder<XJComponent>
implements XjComponentBuilder {
@Override
protected XJComponent buildConcreteComponent() {
return new XJComponent();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "allowTemplateFromHeader": ((XJComponent) component).setAllowTemplateFromHeader((boolean) value); return true;
case "contentCache": ((XJComponent) component).setContentCache((boolean) value); return true;
case "lazyStartProducer": ((XJComponent) component).setLazyStartProducer((boolean) value); return true;
case "autowiredEnabled": ((XJComponent) component).setAutowiredEnabled((boolean) value); return true;
case "saxonConfiguration": ((XJComponent) component).setSaxonConfiguration((net.sf.saxon.Configuration) value); return true;
case "saxonConfigurationProperties": ((XJComponent) component).setSaxonConfigurationProperties((java.util.Map) value); return true;
case "saxonExtensionFunctions": ((XJComponent) component).setSaxonExtensionFunctions((java.lang.String) value); return true;
case "secureProcessing": ((XJComponent) component).setSecureProcessing((boolean) value); return true;
case "transformerFactoryClass": ((XJComponent) component).setTransformerFactoryClass((java.lang.String) value); return true;
case "transformerFactoryConfigurationStrategy": ((XJComponent) component).setTransformerFactoryConfigurationStrategy((org.apache.camel.component.xslt.TransformerFactoryConfigurationStrategy) value); return true;
case "uriResolver": ((XJComponent) component).setUriResolver((javax.xml.transform.URIResolver) value); return true;
case "uriResolverFactory": ((XJComponent) component).setUriResolverFactory((org.apache.camel.component.xslt.XsltUriResolverFactory) value); return true;
default: return false;
}
}
}
}
|
XjComponentBuilderImpl
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/deser/filter/UnknownPropertyDeserTest.java
|
{
"start": 3436,
"end": 3574
}
|
class ____ {
@JsonIgnoreProperties("x")
public Map<String,Integer> values;
}
// [databind#987]
static
|
MapWithoutX
|
java
|
elastic__elasticsearch
|
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/execution/sequence/StageToKeys.java
|
{
"start": 744,
"end": 2633
}
|
class ____ implements Accountable {
private final List<Set<SequenceKey>> stageToKey;
@SuppressWarnings(value = { "unchecked", "rawtypes" })
StageToKeys(int stages) {
// use asList to create an immutable list already initialized to null
this.stageToKey = Arrays.asList(new Set[stages]);
}
void add(int stage, SequenceKey key) {
Set<SequenceKey> set = stageToKey.get(stage);
if (set == null) {
// TODO: could we use an allocation strategy?
set = new LinkedHashSet<>();
stageToKey.set(stage, set);
}
set.add(key);
}
void remove(int stage, SequenceKey key) {
Set<SequenceKey> set = stageToKey.get(stage);
if (set != null) {
set.remove(key);
}
}
boolean isEmpty(int stage) {
Set<SequenceKey> set = stageToKey.get(stage);
return set == null || set.isEmpty();
}
Set<SequenceKey> keys(int stage) {
Set<SequenceKey> set = stageToKey.get(stage);
return set == null ? emptySet() : set;
}
Set<SequenceKey> keys() {
Set<SequenceKey> keys = new LinkedHashSet<>();
for (Set<SequenceKey> sequenceKeys : stageToKey) {
if (CollectionUtils.isEmpty(sequenceKeys) == false) {
keys.addAll(sequenceKeys);
}
}
return keys;
}
void clear() {
for (Set<SequenceKey> set : stageToKey) {
if (set != null) {
set.clear();
}
}
}
@Override
public long ramBytesUsed() {
return RamUsageEstimator.sizeOfCollection(stageToKey);
}
@Override
public String toString() {
StringJoiner sj = new StringJoiner(",", "[", "]");
stageToKey.forEach(s -> sj.add(s != null ? "" + s.size() : "0"));
return sj.toString();
}
}
|
StageToKeys
|
java
|
netty__netty
|
transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueDatagramConnectNotExistsTest.java
|
{
"start": 870,
"end": 1129
}
|
class ____ extends DatagramConnectNotExistsTest {
@Override
protected List<TestsuitePermutation.BootstrapFactory<Bootstrap>> newFactories() {
return KQueueSocketTestPermutation.INSTANCE.datagramSocket();
}
}
|
KQueueDatagramConnectNotExistsTest
|
java
|
elastic__elasticsearch
|
modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/MaxMindSupportTests.java
|
{
"start": 18933,
"end": 22355
}
|
class ____ MaxMind does not expose through DatabaseReader: "
+ supportedMaxMindClassesThatDoNotExist,
supportedMaxMindClassesThatDoNotExist,
empty()
);
}
/*
* This tests that this test has a mapping in TYPE_TO_MAX_MIND_CLASS for all MaxMind classes exposed through GeoIpDatabase.
*/
public void testUsedMaxMindResponseClassesAreAccountedFor() {
Set<Class<? extends AbstractResponse>> usedMaxMindResponseClasses = getUsedMaxMindResponseClasses();
Set<Class<? extends AbstractResponse>> supportedMaxMindClasses = new HashSet<>(TYPE_TO_MAX_MIND_CLASS.values());
Set<Class<? extends AbstractResponse>> usedButNotSupportedMaxMindResponseClasses = Sets.difference(
usedMaxMindResponseClasses,
supportedMaxMindClasses
);
assertThat(
"MaxmindIpDataLookups exposes MaxMind response classes that this test does not know what to do with. Add mappings to "
+ "TYPE_TO_MAX_MIND_CLASS for the following: "
+ usedButNotSupportedMaxMindResponseClasses,
usedButNotSupportedMaxMindResponseClasses,
empty()
);
Set<Class<? extends AbstractResponse>> supportedButNotUsedMaxMindClasses = Sets.difference(
supportedMaxMindClasses,
usedMaxMindResponseClasses
);
assertThat(
"This test claims to support MaxMind response classes that are not exposed in GeoIpDatabase. Remove the following from "
+ "TYPE_TO_MAX_MIND_CLASS: "
+ supportedButNotUsedMaxMindClasses,
supportedButNotUsedMaxMindClasses,
empty()
);
}
/*
* This is the list of field types that causes us to stop recursing. That is, fields of these types are the lowest-level fields that
* we care about.
*/
private static final Set<Class<?>> TERMINAL_TYPES = Set.of(
boolean.class,
Boolean.class,
char.class,
Character.class,
Class.class,
ConnectionTypeResponse.ConnectionType.class,
double.class,
Double.class,
InetAddress.class,
int.class,
Integer.class,
long.class,
Long.class,
MaxMind.class,
Network.class,
Object.class,
String.class,
void.class,
Void.class
);
/*
* These are types that are containers for other types. We don't need to recurse into each method on these types. Instead, we need to
* look at their generic types.
*/
private static final Set<Class<?>> CONTAINER_TYPES = Set.of(Collection.class, List.class, Map.class, Optional.class);
/*
* These are methods we don't want to traverse into.
*/
private static final Set<Method> IGNORED_METHODS = Arrays.stream(Object.class.getMethods()).collect(Collectors.toUnmodifiableSet());
/**
* Returns the set of bean-property-like field names referenced from aClass, sorted alphabetically. This method calls itself
* recursively for all methods until it reaches one of the types in TERMINAL_TYPES. The name of the method returning one of those
* terminal types is converted to a bean-property-like name using the "beanify" method.
*
* @param context This is a String representing where in the list of methods we are
* @param aClass The
|
that
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/subselect/EmployeeGroupId.java
|
{
"start": 262,
"end": 926
}
|
class ____
implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "group_name")
private String groupName;
@Column(name = "dept_name")
private String departmentName;
@SuppressWarnings("unused")
private EmployeeGroupId() {
}
public EmployeeGroupId(String groupName, String departmentName) {
this.groupName = groupName;
this.departmentName = departmentName;
}
public String getDepartmentName() {
return departmentName;
}
public String getGroupName() {
return groupName;
}
@Override
public String toString() {
return "groupName: " + groupName + ", departmentName: " + departmentName;
}
}
|
EmployeeGroupId
|
java
|
FasterXML__jackson-core
|
src/test/java/tools/jackson/core/unittest/testutil/AsyncReaderWrapperForByteBuffer.java
|
{
"start": 351,
"end": 1989
}
|
class ____ extends AsyncReaderWrapper
{
private final byte[] _doc;
private final int _bytesPerFeed;
private final int _padding;
private int _offset;
private int _end;
public AsyncReaderWrapperForByteBuffer(JsonParser sr, int bytesPerCall,
byte[] doc, int padding)
{
super(sr);
_bytesPerFeed = bytesPerCall;
_doc = doc;
_offset = 0;
_end = doc.length;
_padding = padding;
}
@Override
public JsonToken nextToken() throws JacksonException
{
JsonToken token;
while ((token = _streamReader.nextToken()) == JsonToken.NOT_AVAILABLE) {
ByteBufferFeeder feeder = (ByteBufferFeeder) _streamReader.nonBlockingInputFeeder();
if (!feeder.needMoreInput()) {
throw new StreamReadException(null, "Got NOT_AVAILABLE, could not feed more input");
}
int amount = Math.min(_bytesPerFeed, _end - _offset);
if (amount < 1) { // end-of-input?
feeder.endOfInput();
} else {
// padding?
if (_padding == 0) {
feeder.feedInput(ByteBuffer.wrap(_doc, _offset, amount));
} else {
byte[] tmp = new byte[amount + _padding + _padding];
System.arraycopy(_doc, _offset, tmp, _padding, amount);
feeder.feedInput(ByteBuffer.wrap(tmp, _padding, amount));
}
_offset += amount;
}
}
return token;
}
}
|
AsyncReaderWrapperForByteBuffer
|
java
|
quarkusio__quarkus
|
extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/OidcRequestAndResponseFilterTest.java
|
{
"start": 31022,
"end": 31360
}
|
class ____ extends CallableFilterParent
implements OidcRequestFilter {
@Override
public void filter(OidcRequestContext requestContext) {
called();
}
}
@TenantFeature("response-my-bearer-tenant")
@ApplicationScoped
public static
|
TenantFeatureAuthorizationCodeFlowRequestFilter
|
java
|
resilience4j__resilience4j
|
resilience4j-hedge/src/main/java/io/github/resilience4j/hedge/event/HedgeOnPrimarySuccessEvent.java
|
{
"start": 701,
"end": 1140
}
|
class ____ extends AbstractHedgeEvent {
public HedgeOnPrimarySuccessEvent(String hedgeName, Duration duration) {
super(hedgeName, Type.PRIMARY_SUCCESS, duration);
}
@Override
public String toString() {
return String.format("%s: Hedge '%s' recorded a successful call in %dms",
getCreationTime(),
getHedgeName(),
getDuration().toMillis());
}
}
|
HedgeOnPrimarySuccessEvent
|
java
|
elastic__elasticsearch
|
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/transport/TransportVersionResourcesPlugin.java
|
{
"start": 1509,
"end": 7419
}
|
class ____ implements Plugin<Project> {
public static final String TRANSPORT_REFERENCES_TOPIC = "transportReferences";
@Override
public void apply(Project project) {
project.getPluginManager().apply(LifecycleBasePlugin.class);
project.getPluginManager().apply(VersionPropertiesPlugin.class);
project.getPluginManager().apply(PrecommitTaskPlugin.class);
var psService = project.getPlugins().apply(ProjectSubscribeServicePlugin.class).getService();
project.getRootProject().getPlugins().apply(GlobalBuildInfoPlugin.class);
Property<BuildParameterExtension> buildParams = loadBuildParams(project);
Properties versions = (Properties) project.getExtensions().getByName(VersionPropertiesPlugin.VERSIONS_EXT);
Version currentVersion = Version.fromString(versions.getProperty("elasticsearch"));
var resourceRoot = getResourceRoot(project);
String taskGroup = "Transport Versions";
project.getGradle()
.getSharedServices()
.registerIfAbsent("transportVersionResources", TransportVersionResourcesService.class, spec -> {
Directory transportResources = project.getLayout().getProjectDirectory().dir("src/main/resources/" + resourceRoot);
spec.getParameters().getTransportResourcesDirectory().set(transportResources);
spec.getParameters().getRootDirectory().set(project.getLayout().getSettingsDirectory().getAsFile());
Provider<String> upstreamRef = project.getProviders().gradleProperty("org.elasticsearch.transport.baseRef");
if (upstreamRef.isPresent()) {
spec.getParameters().getBaseRefOverride().set(upstreamRef.get());
}
});
var depsHandler = project.getDependencies();
var tvReferencesConfig = project.getConfigurations().create("globalTvReferences", c -> {
c.setCanBeConsumed(false);
c.setCanBeResolved(true);
c.attributes(TransportVersionReference::addArtifactAttribute);
c.getDependencies()
.addAllLater(
psService.flatMap(t -> t.getProjectsByTopic(TRANSPORT_REFERENCES_TOPIC))
.map(projectPaths -> projectPaths.stream().map(path -> depsHandler.project(Map.of("path", path))).toList())
);
});
var validateTask = project.getTasks()
.register("validateTransportVersionResources", ValidateTransportVersionResourcesTask.class, t -> {
t.setGroup(taskGroup);
t.setDescription("Validates that all transport version resources are internally consistent with each other");
t.getReferencesFiles().setFrom(tvReferencesConfig);
t.getShouldValidateDensity().convention(true);
t.getShouldValidatePrimaryIdNotPatch().convention(true);
t.getCurrentUpperBoundName().convention(currentVersion.getMajor() + "." + currentVersion.getMinor());
t.getCI().set(buildParams.get().getCi());
});
project.getTasks().named(PrecommitPlugin.PRECOMMIT_TASK_NAME).configure(t -> t.dependsOn(validateTask));
var generateManifestTask = project.getTasks()
.register("generateTransportVersionManifest", GenerateTransportVersionManifestTask.class, t -> {
t.setGroup(taskGroup);
t.setDescription("Generate a manifest resource for all transport version definitions");
t.getManifestFile().set(project.getLayout().getBuildDirectory().file("generated-resources/manifest.txt"));
});
project.getTasks().named(JavaPlugin.PROCESS_RESOURCES_TASK_NAME, Copy.class).configure(t -> {
t.into(resourceRoot + "/definitions", c -> c.from(generateManifestTask));
});
Action<GenerateTransportVersionDefinitionTask> generationConfiguration = t -> {
t.setGroup(taskGroup);
t.getReferencesFiles().setFrom(tvReferencesConfig);
t.getIncrement().convention(1000);
t.getCurrentUpperBoundName().convention(currentVersion.getMajor() + "." + currentVersion.getMinor());
};
var generateDefinitionsTask = project.getTasks()
.register("generateTransportVersion", GenerateTransportVersionDefinitionTask.class, t -> {
t.setDescription("(Re)generates a transport version definition file");
});
generateDefinitionsTask.configure(generationConfiguration);
validateTask.configure(t -> t.mustRunAfter(generateDefinitionsTask));
var resolveConflictTask = project.getTasks()
.register("resolveTransportVersionConflict", GenerateTransportVersionDefinitionTask.class, t -> {
t.setDescription("Resolve merge conflicts in transport version internal state files");
t.getResolveConflict().set(true);
});
resolveConflictTask.configure(generationConfiguration);
validateTask.configure(t -> t.mustRunAfter(resolveConflictTask));
var generateInitialTask = project.getTasks()
.register("generateInitialTransportVersion", GenerateInitialTransportVersionTask.class, t -> {
t.setGroup(taskGroup);
t.setDescription("(Re)generates an initial transport version for an Elasticsearch release version");
t.getCurrentVersion().set(currentVersion);
});
validateTask.configure(t -> t.mustRunAfter(generateInitialTask));
}
private static String getResourceRoot(Project project) {
Provider<String> resourceRootProperty = project.getProviders().gradleProperty("org.elasticsearch.transport.resourceRoot");
return resourceRootProperty.isPresent() ? resourceRootProperty.get() : "transport";
}
}
|
TransportVersionResourcesPlugin
|
java
|
quarkusio__quarkus
|
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/mapping/timezone/TimezoneDefaultStorageAutoTest.java
|
{
"start": 345,
"end": 1860
}
|
class ____ extends AbstractTimezoneDefaultStorageTest {
@RegisterExtension
static QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(EntityWithTimezones.class)
.addClasses(SchemaUtil.class, SmokeTestUtils.class))
.withConfigurationResource("application.properties")
.overrideConfigKey("quarkus.hibernate-orm.mapping.timezone.default-storage", "auto");
@Test
public void schema() throws Exception {
assertThat(SchemaUtil.getColumnNames(sessionFactory, EntityWithTimezones.class))
.doesNotContain("zonedDateTime_tz", "offsetDateTime_tz", "offsetTime_tz");
assertThat(SchemaUtil.getColumnTypeName(sessionFactory, EntityWithTimezones.class, "zonedDateTime"))
.isEqualTo("TIMESTAMP_WITH_TIMEZONE");
assertThat(SchemaUtil.getColumnTypeName(sessionFactory, EntityWithTimezones.class, "offsetDateTime"))
.isEqualTo("TIMESTAMP_WITH_TIMEZONE");
}
@Test
public void persistAndLoad() {
long id = persistWithValuesToTest();
assertLoadedValues(id,
// Native storage preserves the offset, but not the zone ID: https://hibernate.atlassian.net/browse/HHH-16289
PERSISTED_ZONED_DATE_TIME.withZoneSameInstant(PERSISTED_ZONED_DATE_TIME.getOffset()),
PERSISTED_OFFSET_DATE_TIME,
PERSISTED_OFFSET_TIME);
}
}
|
TimezoneDefaultStorageAutoTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/B.java
|
{
"start": 449,
"end": 808
}
|
class ____ implements Serializable {
private Integer id;
private A a;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "FK_FOR_B")
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
}
|
B
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/test/entity/Employee.java
|
{
"start": 99,
"end": 1531
}
|
class ____ {
private Long id;
private String number;
private String name;
private String description;
private Integer age;
private BigDecimal salary;
private Date birthdate;
private boolean badboy;
public Employee(){
}
public boolean isBadboy() {
return badboy;
}
public void setBadboy(boolean badboy) {
this.badboy = badboy;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
}
|
Employee
|
java
|
elastic__elasticsearch
|
x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/exporter/local/LocalExporter.java
|
{
"start": 36675,
"end": 38000
}
|
class ____<Response> extends ResponseActionListener<Response> {
private final List<Exception> errors;
ErrorCapturingResponseListener(
String type,
String name,
AtomicInteger countDown,
Consumer<ExporterResourceStatus> setupListener,
List<Exception> errors,
String configName
) {
super(type, name, countDown, () -> {
// Called on completion of all removal tasks
ExporterResourceStatus status = ExporterResourceStatus.determineReadiness(configName, TYPE, errors);
setupListener.accept(status);
});
this.errors = errors;
}
@Override
public void onResponse(Response response) {
if (response instanceof AcknowledgedResponse && ((AcknowledgedResponse) response).isAcknowledged() == false) {
errors.add(new ElasticsearchException("failed to set monitoring {} [{}]", type, name));
}
super.onResponse(response);
}
@Override
public void onFailure(Exception e) {
errors.add(new ElasticsearchException("failed to set monitoring {} [{}]", e, type, name));
super.onFailure(e);
}
}
private
|
ErrorCapturingResponseListener
|
java
|
spring-projects__spring-framework
|
framework-docs/src/main/java/org/springframework/docs/integration/jms/jmstxparticipation/JmsConfiguration.java
|
{
"start": 1059,
"end": 1588
}
|
class ____ {
// tag::snippet[]
@Bean
DefaultMessageListenerContainer jmsContainer(ConnectionFactory connectionFactory, Destination destination,
ExampleListener messageListener) {
DefaultMessageListenerContainer jmsContainer = new DefaultMessageListenerContainer();
jmsContainer.setConnectionFactory(connectionFactory);
jmsContainer.setDestination(destination);
jmsContainer.setMessageListener(messageListener);
jmsContainer.setSessionTransacted(true);
return jmsContainer;
}
// end::snippet[]
}
|
JmsConfiguration
|
java
|
quarkusio__quarkus
|
extensions/grpc/deployment/src/test/java/io/quarkus/grpc/lock/detection/BlockingClientCallOnEventLoopTest.java
|
{
"start": 606,
"end": 1563
}
|
class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.setFlatClassPath(true)
.withApplicationRoot((jar) -> jar
.addClasses(HelloService.class, CallBlockingService.class, CallBlocking.class)
.addPackage(GreeterGrpc.class.getPackage())
.addPackage(CallBlockingGrpc.class.getPackage()));
@GrpcClient
CallBlocking callBlocking;
@Test
void shouldThrowExceptionOnBlockingClientCall() {
Uni<CallHello.SuccessOrFailureDescription> result = callBlocking.doBlockingCall(CallHello.Empty.getDefaultInstance());
CallHello.SuccessOrFailureDescription response = result.await().atMost(Duration.ofSeconds(10));
assertThat(response.getSuccess()).isFalse();
assertThat(response.getErrorDescription()).contains(CallBlockingService.EXPECTED_ERROR_PREFIX);
}
}
|
BlockingClientCallOnEventLoopTest
|
java
|
reactor__reactor-core
|
reactor-core/src/main/java/reactor/core/publisher/MonoPublishMulticast.java
|
{
"start": 2616,
"end": 8335
}
|
class ____<T> extends Mono<T>
implements InnerConsumer<T>, FluxPublishMulticast.PublishMulticasterParent {
@SuppressWarnings("NotNullFieldNotInitialized") // s is initialized in onSubscribe
volatile Subscription s;
// https://github.com/uber/NullAway/issues/1157
@SuppressWarnings({"rawtypes", "DataFlowIssue"})
static final AtomicReferenceFieldUpdater<MonoPublishMulticaster, @Nullable Subscription> S =
AtomicReferenceFieldUpdater.newUpdater(MonoPublishMulticaster.class,
Subscription.class,
"s");
volatile int wip;
static final AtomicIntegerFieldUpdater<MonoPublishMulticaster> WIP =
AtomicIntegerFieldUpdater.newUpdater(MonoPublishMulticaster.class, "wip");
// lazy-initialized in constructor
@SuppressWarnings("NotNullFieldNotInitialized")
volatile PublishMulticastInner<T>[] subscribers;
@SuppressWarnings("rawtypes")
static final AtomicReferenceFieldUpdater<MonoPublishMulticaster, PublishMulticastInner[]> SUBSCRIBERS =
AtomicReferenceFieldUpdater.newUpdater(MonoPublishMulticaster.class, PublishMulticastInner[].class, "subscribers");
@SuppressWarnings("rawtypes")
static final PublishMulticastInner[] EMPTY = new PublishMulticastInner[0];
@SuppressWarnings("rawtypes")
static final PublishMulticastInner[] TERMINATED = new PublishMulticastInner[0];
volatile boolean done;
@Nullable T value;
@Nullable Throwable error;
volatile boolean connected;
final Context context;
@SuppressWarnings("unchecked")
MonoPublishMulticaster(Context ctx) {
SUBSCRIBERS.lazySet(this, EMPTY);
this.context = ctx;
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.PARENT) {
return s;
}
if (key == Attr.ERROR) {
return error;
}
if (key == Attr.CANCELLED) {
return s == Operators.cancelledSubscription();
}
if (key == Attr.TERMINATED) {
return done;
}
if (key == Attr.PREFETCH) {
return 1;
}
if (key == Attr.BUFFERED) {
return value != null ? 1 : 0;
}
if (key == Attr.RUN_STYLE) {
return Attr.RunStyle.SYNC;
}
return null;
}
@Override
public Stream<? extends Scannable> inners() {
return Stream.of(subscribers);
}
@Override
public Context currentContext() {
return context;
}
@Override
public void subscribe(CoreSubscriber<? super T> actual) {
PublishMulticastInner<T> pcs = new PublishMulticastInner<>(this, actual);
actual.onSubscribe(pcs);
if (add(pcs)) {
if (pcs.cancelled == 1) {
remove(pcs);
return;
}
drain();
}
else {
Throwable ex = error;
if (ex != null) {
actual.onError(ex);
}
else {
actual.onComplete();
}
}
}
@Override
public void onSubscribe(Subscription s) {
if (Operators.setOnce(S, this, s)) {
connected = true;
s.request(Long.MAX_VALUE);
}
}
@Override
public void onNext(T t) {
if (done) {
Operators.onNextDropped(t, context);
return;
}
value = t;
done = true;
drain();
}
@Override
public void onError(Throwable t) {
if (done) {
Operators.onErrorDropped(t, context);
return;
}
error = t;
done = true;
drain();
}
@Override
public void onComplete() {
done = true;
drain();
}
void drain() {
if (WIP.getAndIncrement(this) != 0) {
return;
}
int missed = 1;
for (; ; ) {
if (connected) {
if (s == Operators.cancelledSubscription()) {
value = null;
return;
}
final T v = value;
PublishMulticastInner<T>[] a = subscribers;
int n = a.length;
if (n != 0) {
if (s == Operators.cancelledSubscription()) {
value = null;
return;
}
@SuppressWarnings("unchecked")
PublishMulticastInner<T>[] castedArray = SUBSCRIBERS.getAndSet(this, TERMINATED);
a = castedArray;
n = a.length;
Throwable ex = error;
if (ex != null) {
for (int i = 0; i < n; i++) {
a[i].actual.onError(ex);
}
}
else if (v == null) {
for (int i = 0; i < n; i++) {
a[i].actual.onComplete();
}
}
else {
for (int i = 0; i < n; i++) {
a[i].actual.onNext(v);
a[i].actual.onComplete();
}
value = null;
}
return;
}
}
missed = WIP.addAndGet(this, -missed);
if (missed == 0) {
break;
}
}
}
boolean add(PublishMulticastInner<T> s) {
for (; ; ) {
PublishMulticastInner<T>[] a = subscribers;
if (a == TERMINATED) {
return false;
}
int n = a.length;
@SuppressWarnings("unchecked")
PublishMulticastInner<T>[] b = new PublishMulticastInner[n + 1];
System.arraycopy(a, 0, b, 0, n);
b[n] = s;
if (SUBSCRIBERS.compareAndSet(this, a, b)) {
return true;
}
}
}
@SuppressWarnings("unchecked")
void remove(PublishMulticastInner<T> s) {
for (; ; ) {
PublishMulticastInner<T>[] a = subscribers;
if (a == TERMINATED || a == EMPTY) {
return;
}
int n = a.length;
int j = -1;
for (int i = 0; i < n; i++) {
if (a[i] == s) {
j = i;
break;
}
}
if (j < 0) {
return;
}
PublishMulticastInner<T>[] b;
if (n == 1) {
b = EMPTY;
}
else {
b = new PublishMulticastInner[n - 1];
System.arraycopy(a, 0, b, 0, j);
System.arraycopy(a, j + 1, b, j, n - j - 1);
}
if (SUBSCRIBERS.compareAndSet(this, a, b)) {
return;
}
}
}
@Override
public void terminate() {
Operators.terminate(S, this);
if (WIP.getAndIncrement(this) == 0) {
if (connected) {
value = null;
}
}
}
}
static final
|
MonoPublishMulticaster
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/main/java/org/apache/hadoop/yarn/server/timelineservice/storage/TimelineReader.java
|
{
"start": 4221,
"end": 7979
}
|
class ____ fetch dataToRetrieve
* fields. All the dataToRetrieve fields are optional. Refer to
* {@link TimelineDataToRetrieve} for details.
* @return A <cite>TimelineEntity</cite> instance or null. The entity will
* contain the metadata plus the given fields to retrieve.<br>
* If entityType is YARN_FLOW_RUN, entity returned is of type
* <cite>FlowRunEntity</cite>.<br>
* For all other entity types, entity returned is of type
* <cite>TimelineEntity</cite>.
* @throws IOException if there is an exception encountered while fetching
* entity from backend storage.
*/
TimelineEntity getEntity(TimelineReaderContext context,
TimelineDataToRetrieve dataToRetrieve) throws IOException;
/**
* <p>The API to search for a set of entities of the given entity type in
* the scope of the given context which matches the given predicates. The
* predicates include the created time window, limit to number of entities to
* be returned, and the entities can be filtered by checking whether they
* contain the given info/configs entries in the form of key/value pairs,
* given metrics in the form of metricsIds and its relation with metric
* values, given events in the form of the Ids, and whether they relate to/are
* related to other entities. For those parameters which have multiple
* entries, the qualified entity needs to meet all or them.</p>
*
* @param context Context which defines the scope in which query has to be
* made. Use getters of {@link TimelineReaderContext} to fetch context
* fields. Context contains the following :<br>
* <ul>
* <li><b>entityType</b> - Entity type(mandatory).</li>
* <li><b>clusterId</b> - Identifies the cluster(mandatory).</li>
* <li><b>userId</b> - Identifies the user.</li>
* <li><b>flowName</b> - Context flow name.</li>
* <li><b>flowRunId</b> - Context flow run id.</li>
* <li><b>appId</b> - Context app id.</li>
* </ul>
* Although entityIdPrefix and entityId are also part of context,
* it has no meaning for getEntities.<br>
* Fields in context which are mandatory depends on entity type. Entity
* type is always mandatory. In addition to entity type, below is the list
* of context fields which are mandatory, based on entity type.<br>
* <ul>
* <li>If entity type is YARN_FLOW_ACTIVITY (i.e. query to fetch flows),
* only clusterId is mandatory.
* </li>
* <li>If entity type is YARN_FLOW_RUN (i.e. query to fetch flow runs),
* clusterId, userId and flowName are mandatory.</li>
* <li>If entity type is YARN_APPLICATION (i.e. query to fetch apps), we
* can either get all apps within the context of flow name or within the
* context of flow run. If apps are queried within the scope of flow name,
* clusterId, userId and flowName are supplied. If they are queried within
* the scope of flow run, clusterId, userId, flowName and flowRunId are
* supplied.</li>
* <li>For other entity types (i.e. query to fetch generic entities), query
* is within the scope of clusterId, userId, flowName, flowRunId, appId and
* entityType. But out of this, only clusterId, appId and entityType are
* mandatory. If flow context information is not supplied, backend storage
* must fetch the flow context information i.e. userId, flowName and
* flowRunId first and based on that, fetch the entities. If flow context
* information is also given, entities can be directly queried.
* </li>
* </ul>
* @param filters Specifies filters which restrict the number of entities
* to return. Use getters of TimelineEntityFilters
|
to
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest74_translate.java
|
{
"start": 976,
"end": 2823
}
|
class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = //
"SELECT TRANSLATE(SUBSTR(TRIM(T.BZ)||\n" +
" TRIM(T.BZ)||\n" +
" TRIM(T.MC)||\n" +
" TRIM(T.MLPH)||\n" +
" TRIM(T.MLXZ),1,35)\n" +
" USING CHAR_CS) FROM T";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
stmt.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(4, visitor.getColumns().size());
{
String text = SQLUtils.toOracleString(stmt);
assertEquals("SELECT TRANSLATE(SUBSTR(TRIM(T.BZ) || TRIM(T.BZ) || TRIM(T.MC) || TRIM(T.MLPH) || TRIM(T.MLXZ), 1, 35) USING CHAR_CS)\n" +
"FROM T", text);
}
// assertTrue(visitor.getColumns().contains(new TableStat.Column("acduser.vw_acd_info", "xzqh")));
// assertTrue(visitor.getOrderByColumns().contains(new TableStat.Column("employees", "last_name")));
}
}
|
OracleSelectTest74_translate
|
java
|
apache__camel
|
core/camel-cluster/src/main/java/org/apache/camel/impl/cluster/ClusteredRouteController.java
|
{
"start": 1947,
"end": 7555
}
|
class ____ extends DefaultRouteController {
private static final Logger LOGGER = LoggerFactory.getLogger(ClusteredRouteController.class);
private final Set<String> routes;
private final ConcurrentMap<String, ClusteredRouteConfiguration> configurations;
private final List<ClusteredRouteFilter> filters;
private final PolicyFactory policyFactory;
private final ClusteredRouteConfiguration defaultConfiguration;
private CamelClusterService clusterService;
private CamelClusterService.Selector clusterServiceSelector;
public ClusteredRouteController() {
this.routes = new CopyOnWriteArraySet<>();
this.configurations = new ConcurrentHashMap<>();
this.filters = new ArrayList<>();
this.clusterServiceSelector = ClusterServiceSelectors.DEFAULT_SELECTOR;
this.policyFactory = new PolicyFactory();
this.defaultConfiguration = new ClusteredRouteConfiguration();
this.defaultConfiguration.setInitialDelay(Duration.ofMillis(0));
}
// *******************************
// Properties.
// *******************************
/**
* Add a filter used to to filter cluster aware routes.
*/
public void addFilter(ClusteredRouteFilter filter) {
this.filters.add(filter);
}
/**
* Sets the filters used to filter cluster aware routes.
*/
public void setFilters(Collection<ClusteredRouteFilter> filters) {
this.filters.clear();
this.filters.addAll(filters);
}
public Collection<ClusteredRouteFilter> getFilters() {
return Collections.unmodifiableList(filters);
}
/**
* Add a configuration for the given route.
*/
public void addRouteConfiguration(String routeId, ClusteredRouteConfiguration configuration) {
configurations.put(routeId, configuration);
}
/**
* Sets the configurations for the routes.
*/
public void setRoutesConfiguration(Map<String, ClusteredRouteConfiguration> configurations) {
this.configurations.clear();
this.configurations.putAll(configurations);
}
public Map<String, ClusteredRouteConfiguration> getRoutesConfiguration() {
return Collections.unmodifiableMap(this.configurations);
}
public Duration getInitialDelay() {
return this.defaultConfiguration.getInitialDelay();
}
/**
* Set the amount of time the route controller should wait before to start the routes after the camel context is
* started.
*
* @param initialDelay the initial delay.
*/
public void setInitialDelay(Duration initialDelay) {
this.defaultConfiguration.setInitialDelay(initialDelay);
}
public String getNamespace() {
return this.defaultConfiguration.getNamespace();
}
/**
* Set the default namespace.
*/
public void setNamespace(String namespace) {
this.defaultConfiguration.setNamespace(namespace);
}
public CamelClusterService getClusterService() {
return clusterService;
}
/**
* Set the cluster service to use.
*/
public void setClusterService(CamelClusterService clusterService) {
ObjectHelper.notNull(clusterService, "CamelClusterService");
this.clusterService = clusterService;
}
public CamelClusterService.Selector getClusterServiceSelector() {
return clusterServiceSelector;
}
/**
* Set the selector strategy to look-up a {@link CamelClusterService}
*/
public void setClusterServiceSelector(CamelClusterService.Selector clusterServiceSelector) {
ObjectHelper.notNull(clusterService, "CamelClusterService.Selector");
this.clusterServiceSelector = clusterServiceSelector;
}
// *******************************
//
// *******************************
@Override
public Collection<Route> getControlledRoutes() {
return this.routes.stream().map(getCamelContext()::getRoute).filter(Objects::nonNull).toList();
}
@Override
public void doStart() throws Exception {
final CamelContext context = getCamelContext();
// Parameters validation
ObjectHelper.notNull(defaultConfiguration.getNamespace(), "Namespace");
ObjectHelper.notNull(defaultConfiguration.getInitialDelay(), "initialDelay");
ObjectHelper.notNull(context, "camelContext");
if (clusterService == null) {
// Finally try to grab it from the camel context.
clusterService = ClusterServiceHelper.mandatoryLookupService(context, clusterServiceSelector);
}
LOGGER.debug("Using ClusterService instance {} (id={}, type={})", clusterService, clusterService.getId(),
clusterService.getClass().getName());
if (!ServiceHelper.isStarted(clusterService)) {
// Start the cluster service if not yet started.
clusterService.start();
}
super.doStart();
}
@Override
public void doStop() throws Exception {
if (ServiceHelper.isStarted(clusterService)) {
// Stop the cluster service.
clusterService.stop();
}
}
@Override
public void setCamelContext(CamelContext camelContext) {
if (!camelContext.getRoutePolicyFactories().contains(this.policyFactory)) {
camelContext.addRoutePolicyFactory(this.policyFactory);
}
super.setCamelContext(camelContext);
}
// *******************************
// Factories
// *******************************
private final
|
ClusteredRouteController
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/cglib/transform/impl/UndeclaredThrowableTransformer.java
|
{
"start": 1144,
"end": 3142
}
|
class ____ extends ClassEmitterTransformer {
private final Type wrapper;
public UndeclaredThrowableTransformer(Class wrapper) {
this.wrapper = Type.getType(wrapper);
boolean found = false;
Constructor[] cstructs = wrapper.getConstructors();
for (Constructor cstruct : cstructs) {
Class[] types = cstruct.getParameterTypes();
if (types.length == 1 && types[0].equals(Throwable.class)) {
found = true;
break;
}
}
if (!found) {
throw new IllegalArgumentException(wrapper + " does not have a single-arg constructor that takes a Throwable");
}
}
@Override
public CodeEmitter begin_method(int access, final Signature sig, final Type[] exceptions) {
CodeEmitter e = super.begin_method(access, sig, exceptions);
if (TypeUtils.isAbstract(access) || sig.equals(Constants.SIG_STATIC)) {
return e;
}
return new CodeEmitter(e) {
private final boolean isConstructor = Constants.CONSTRUCTOR_NAME.equals(sig.getName());
private Block handler = begin_block();
private boolean callToSuperSeen;
@Override
public void visitMethodInsn(int opcode, String owner, String name, String descriptor, boolean isInterface) {
super.visitMethodInsn(opcode, owner, name, descriptor, isInterface);
if (isConstructor && !callToSuperSeen && Constants.CONSTRUCTOR_NAME.equals(name)) {
// we start the entry in the exception table after the call to super
handler = begin_block();
callToSuperSeen = true;
}
}
@Override
public void visitMaxs(int maxStack, int maxLocals) {
handler.end();
EmitUtils.wrap_undeclared_throwable(this, handler, exceptions, wrapper);
super.visitMaxs(maxStack, maxLocals);
}
};
}
}
|
UndeclaredThrowableTransformer
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/internal/Doubles.java
|
{
"start": 1235,
"end": 2476
}
|
class ____ on {@link StandardComparisonStrategy}.
*/
public static Doubles instance() {
return INSTANCE;
}
// TODO reduce the visibility of the fields annotated with @VisibleForTesting
Doubles() {
super();
}
public Doubles(ComparisonStrategy comparisonStrategy) {
super(comparisonStrategy);
}
@Override
protected Double zero() {
return 0.0d;
}
@Override
protected Double one() {
return 1.0d;
}
@Override
protected Double NaN() {
return Double.NaN;
}
@Override
protected Double absDiff(Double actual, Double other) {
return isNanOrInfinite(actual) || isNanOrInfinite(other)
? abs(actual - other)
: abs(absBigDecimalDiff(actual, other).doubleValue());
}
@Override
protected boolean isFinite(Double value) {
return Double.isFinite(value);
}
@Override
protected boolean isNotFinite(Double value) {
return !Double.isFinite(value);
}
@Override
protected boolean isInfinite(Double value) {
return Double.isInfinite(value);
}
@Override
protected boolean isNotInfinite(Double value) {
return !Double.isInfinite(value);
}
@Override
protected boolean isNaN(Double value) {
return Double.isNaN(value);
}
}
|
based
|
java
|
apache__dubbo
|
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ArrayUtils.java
|
{
"start": 904,
"end": 2491
}
|
class ____ {
private ArrayUtils() {}
/**
* <p>Checks if the array is null or empty. <p/>
*
* @param array th array to check
* @return {@code true} if the array is null or empty.
*/
public static boolean isEmpty(final Object[] array) {
return array == null || array.length == 0;
}
/**
* <p>Checks if the array is not null or empty. <p/>
*
* @param array th array to check
* @return {@code true} if the array is not null or empty.
*/
public static boolean isNotEmpty(final Object[] array) {
return !isEmpty(array);
}
public static boolean contains(final String[] array, String valueToFind) {
return indexOf(array, valueToFind, 0) != -1;
}
public static int indexOf(String[] array, String valueToFind, int startIndex) {
if (isEmpty(array) || valueToFind == null) {
return -1;
} else {
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; ++i) {
if (valueToFind.equals(array[i])) {
return i;
}
}
return -1;
}
}
/**
* Convert from variable arguments to array
*
* @param values variable arguments
* @param <T> The class
* @return array
* @since 2.7.9
*/
public static <T> T[] of(T... values) {
return values;
}
public static <T> T first(T[] data) {
return isEmpty(data) ? null : data[0];
}
}
|
ArrayUtils
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/BigListStringFieldTest_private.java
|
{
"start": 275,
"end": 1892
}
|
class ____ extends TestCase {
public void test_list() throws Exception {
Model model = new Model();
model.values = new ArrayList<String>(10000);
for (int i = 0; i < 10000; ++i) {
String value = random(100);
model.values.add(value);
}
String text = JSON.toJSONString(model);
Model model2 = JSON.parseObject(text, Model.class);
Assert.assertEquals(model.values, model2.values);
}
public void test_list_browserComptible() throws Exception {
Model model = new Model();
model.values = new ArrayList<String>(10000);
for (int i = 0; i < 10000; ++i) {
String value = random(100);
model.values.add(value);
}
String text = JSON.toJSONString(model, SerializerFeature.BrowserCompatible);
Model model2 = JSON.parseObject(text, Model.class);
Assert.assertEquals(model.values, model2.values);
}
public void test_list_browserSecure() throws Exception {
Model model = new Model();
model.values = new ArrayList<String>(10000);
for (int i = 0; i < 10000; ++i) {
String value = random(100);
model.values.add(value);
}
String text = JSON.toJSONString(model, SerializerFeature.BrowserSecure);
text = text.replaceAll("<", "<");
text = text.replaceAll(">", ">");
Model model2 = JSON.parseObject(text, Model.class);
Assert.assertEquals(model.values, model2.values);
}
private static
|
BigListStringFieldTest_private
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/asm/Frame.java
|
{
"start": 6422,
"end": 47186
}
|
class ____ {
// Constants used in the StackMapTable attribute.
// See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.4.
static final int SAME_FRAME = 0;
static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64;
static final int RESERVED = 128;
static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247;
static final int CHOP_FRAME = 248;
static final int SAME_FRAME_EXTENDED = 251;
static final int APPEND_FRAME = 252;
static final int FULL_FRAME = 255;
static final int ITEM_TOP = 0;
static final int ITEM_INTEGER = 1;
static final int ITEM_FLOAT = 2;
static final int ITEM_DOUBLE = 3;
static final int ITEM_LONG = 4;
static final int ITEM_NULL = 5;
static final int ITEM_UNINITIALIZED_THIS = 6;
static final int ITEM_OBJECT = 7;
static final int ITEM_UNINITIALIZED = 8;
// Additional, ASM specific constants used in abstract types below.
private static final int ITEM_ASM_BOOLEAN = 9;
private static final int ITEM_ASM_BYTE = 10;
private static final int ITEM_ASM_CHAR = 11;
private static final int ITEM_ASM_SHORT = 12;
// The size and offset in bits of each field of an abstract type.
private static final int DIM_SIZE = 6;
private static final int KIND_SIZE = 4;
private static final int FLAGS_SIZE = 2;
private static final int VALUE_SIZE = 32 - DIM_SIZE - KIND_SIZE - FLAGS_SIZE;
private static final int DIM_SHIFT = KIND_SIZE + FLAGS_SIZE + VALUE_SIZE;
private static final int KIND_SHIFT = FLAGS_SIZE + VALUE_SIZE;
private static final int FLAGS_SHIFT = VALUE_SIZE;
// Bitmasks to get each field of an abstract type.
private static final int DIM_MASK = ((1 << DIM_SIZE) - 1) << DIM_SHIFT;
private static final int KIND_MASK = ((1 << KIND_SIZE) - 1) << KIND_SHIFT;
private static final int VALUE_MASK = (1 << VALUE_SIZE) - 1;
// Constants to manipulate the DIM field of an abstract type.
/** The constant to be added to an abstract type to get one with one more array dimension. */
private static final int ARRAY_OF = +1 << DIM_SHIFT;
/** The constant to be added to an abstract type to get one with one less array dimension. */
private static final int ELEMENT_OF = -1 << DIM_SHIFT;
// Possible values for the KIND field of an abstract type.
private static final int CONSTANT_KIND = 1 << KIND_SHIFT;
private static final int REFERENCE_KIND = 2 << KIND_SHIFT;
private static final int UNINITIALIZED_KIND = 3 << KIND_SHIFT;
private static final int FORWARD_UNINITIALIZED_KIND = 4 << KIND_SHIFT;
private static final int LOCAL_KIND = 5 << KIND_SHIFT;
private static final int STACK_KIND = 6 << KIND_SHIFT;
// Possible flags for the FLAGS field of an abstract type.
/**
* A flag used for LOCAL_KIND and STACK_KIND abstract types, indicating that if the resolved,
* concrete type is LONG or DOUBLE, TOP should be used instead (because the value has been
* partially overridden with an xSTORE instruction).
*/
private static final int TOP_IF_LONG_OR_DOUBLE_FLAG = 1 << FLAGS_SHIFT;
// Useful predefined abstract types (all the possible CONSTANT_KIND types).
private static final int TOP = CONSTANT_KIND | ITEM_TOP;
private static final int BOOLEAN = CONSTANT_KIND | ITEM_ASM_BOOLEAN;
private static final int BYTE = CONSTANT_KIND | ITEM_ASM_BYTE;
private static final int CHAR = CONSTANT_KIND | ITEM_ASM_CHAR;
private static final int SHORT = CONSTANT_KIND | ITEM_ASM_SHORT;
private static final int INTEGER = CONSTANT_KIND | ITEM_INTEGER;
private static final int FLOAT = CONSTANT_KIND | ITEM_FLOAT;
private static final int LONG = CONSTANT_KIND | ITEM_LONG;
private static final int DOUBLE = CONSTANT_KIND | ITEM_DOUBLE;
private static final int NULL = CONSTANT_KIND | ITEM_NULL;
private static final int UNINITIALIZED_THIS = CONSTANT_KIND | ITEM_UNINITIALIZED_THIS;
// -----------------------------------------------------------------------------------------------
// Instance fields
// -----------------------------------------------------------------------------------------------
/** The basic block to which these input and output stack map frames correspond. */
Label owner;
/** The input stack map frame locals. This is an array of abstract types. */
private int[] inputLocals;
/** The input stack map frame stack. This is an array of abstract types. */
private int[] inputStack;
/** The output stack map frame locals. This is an array of abstract types. */
private int[] outputLocals;
/** The output stack map frame stack. This is an array of abstract types. */
private int[] outputStack;
/**
* The start of the output stack, relatively to the input stack. This offset is always negative or
* null. A null offset means that the output stack must be appended to the input stack. A -n
* offset means that the first n output stack elements must replace the top n input stack
* elements, and that the other elements must be appended to the input stack.
*/
private short outputStackStart;
/** The index of the top stack element in {@link #outputStack}. */
private short outputStackTop;
/** The number of types that are initialized in the basic block. See {@link #initializations}. */
private int initializationCount;
/**
* The abstract types that are initialized in the basic block. A constructor invocation on an
* UNINITIALIZED, FORWARD_UNINITIALIZED or UNINITIALIZED_THIS abstract type must replace <i>every
* occurrence</i> of this type in the local variables and in the operand stack. This cannot be
* done during the first step of the algorithm since, during this step, the local variables and
* the operand stack types are still abstract. It is therefore necessary to store the abstract
* types of the constructors which are invoked in the basic block, in order to do this replacement
* during the second step of the algorithm, where the frames are fully computed. Note that this
* array can contain abstract types that are relative to the input locals or to the input stack.
*/
private int[] initializations;
// -----------------------------------------------------------------------------------------------
// Constructor
// -----------------------------------------------------------------------------------------------
/**
* Constructs a new Frame.
*
* @param owner the basic block to which these input and output stack map frames correspond.
*/
Frame(final Label owner) {
this.owner = owner;
}
/**
* Sets this frame to the value of the given frame.
*
* <p>WARNING: after this method is called the two frames share the same data structures. It is
* recommended to discard the given frame to avoid unexpected side effects.
*
* @param frame The new frame value.
*/
final void copyFrom(final Frame frame) {
inputLocals = frame.inputLocals;
inputStack = frame.inputStack;
outputStackStart = 0;
outputLocals = frame.outputLocals;
outputStack = frame.outputStack;
outputStackTop = frame.outputStackTop;
initializationCount = frame.initializationCount;
initializations = frame.initializations;
}
// -----------------------------------------------------------------------------------------------
// Static methods to get abstract types from other type formats
// -----------------------------------------------------------------------------------------------
/**
* Returns the abstract type corresponding to the given public API frame element type.
*
* @param symbolTable the type table to use to lookup and store type {@link Symbol}.
* @param type a frame element type described using the same format as in {@link
* MethodVisitor#visitFrame}, i.e. either {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, {@link
* Opcodes#FLOAT}, {@link Opcodes#LONG}, {@link Opcodes#DOUBLE}, {@link Opcodes#NULL}, or
* {@link Opcodes#UNINITIALIZED_THIS}, or the internal name of a class, or a Label designating
* a NEW instruction (for uninitialized types).
* @return the abstract type corresponding to the given frame element type.
*/
static int getAbstractTypeFromApiFormat(final SymbolTable symbolTable, final Object type) {
if (type instanceof Integer) {
return CONSTANT_KIND | ((Integer) type).intValue();
} else if (type instanceof String) {
String descriptor = Type.getObjectType((String) type).getDescriptor();
return getAbstractTypeFromDescriptor(symbolTable, descriptor, 0);
} else {
Label label = (Label) type;
if ((label.flags & Label.FLAG_RESOLVED) != 0) {
return UNINITIALIZED_KIND | symbolTable.addUninitializedType("", label.bytecodeOffset);
} else {
return FORWARD_UNINITIALIZED_KIND | symbolTable.addForwardUninitializedType("", label);
}
}
}
/**
* Returns the abstract type corresponding to the internal name of a class.
*
* @param symbolTable the type table to use to lookup and store type {@link Symbol}.
* @param internalName the internal name of a class. This must <i>not</i> be an array type
* descriptor.
* @return the abstract type value corresponding to the given internal name.
*/
static int getAbstractTypeFromInternalName(
final SymbolTable symbolTable, final String internalName) {
return REFERENCE_KIND | symbolTable.addType(internalName);
}
/**
* Returns the abstract type corresponding to the given type descriptor.
*
* @param symbolTable the type table to use to lookup and store type {@link Symbol}.
* @param buffer a string ending with a type descriptor.
* @param offset the start offset of the type descriptor in buffer.
* @return the abstract type corresponding to the given type descriptor.
*/
private static int getAbstractTypeFromDescriptor(
final SymbolTable symbolTable, final String buffer, final int offset) {
String internalName;
switch (buffer.charAt(offset)) {
case 'V':
return 0;
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
return INTEGER;
case 'F':
return FLOAT;
case 'J':
return LONG;
case 'D':
return DOUBLE;
case 'L':
internalName = buffer.substring(offset + 1, buffer.length() - 1);
return REFERENCE_KIND | symbolTable.addType(internalName);
case '[':
int elementDescriptorOffset = offset + 1;
while (buffer.charAt(elementDescriptorOffset) == '[') {
++elementDescriptorOffset;
}
int typeValue;
switch (buffer.charAt(elementDescriptorOffset)) {
case 'Z':
typeValue = BOOLEAN;
break;
case 'C':
typeValue = CHAR;
break;
case 'B':
typeValue = BYTE;
break;
case 'S':
typeValue = SHORT;
break;
case 'I':
typeValue = INTEGER;
break;
case 'F':
typeValue = FLOAT;
break;
case 'J':
typeValue = LONG;
break;
case 'D':
typeValue = DOUBLE;
break;
case 'L':
internalName = buffer.substring(elementDescriptorOffset + 1, buffer.length() - 1);
typeValue = REFERENCE_KIND | symbolTable.addType(internalName);
break;
default:
throw new IllegalArgumentException(
"Invalid descriptor fragment: " + buffer.substring(elementDescriptorOffset));
}
return ((elementDescriptorOffset - offset) << DIM_SHIFT) | typeValue;
default:
throw new IllegalArgumentException("Invalid descriptor: " + buffer.substring(offset));
}
}
// -----------------------------------------------------------------------------------------------
// Methods related to the input frame
// -----------------------------------------------------------------------------------------------
/**
* Sets the input frame from the given method description. This method is used to initialize the
* first frame of a method, which is implicit (i.e. not stored explicitly in the StackMapTable
* attribute).
*
* @param symbolTable the type table to use to lookup and store type {@link Symbol}.
* @param access the method's access flags.
* @param descriptor the method descriptor.
* @param maxLocals the maximum number of local variables of the method.
*/
final void setInputFrameFromDescriptor(
final SymbolTable symbolTable,
final int access,
final String descriptor,
final int maxLocals) {
inputLocals = new int[maxLocals];
inputStack = new int[0];
int inputLocalIndex = 0;
if ((access & Opcodes.ACC_STATIC) == 0) {
if ((access & Constants.ACC_CONSTRUCTOR) == 0) {
inputLocals[inputLocalIndex++] =
REFERENCE_KIND | symbolTable.addType(symbolTable.getClassName());
} else {
inputLocals[inputLocalIndex++] = UNINITIALIZED_THIS;
}
}
for (Type argumentType : Type.getArgumentTypes(descriptor)) {
int abstractType =
getAbstractTypeFromDescriptor(symbolTable, argumentType.getDescriptor(), 0);
inputLocals[inputLocalIndex++] = abstractType;
if (abstractType == LONG || abstractType == DOUBLE) {
inputLocals[inputLocalIndex++] = TOP;
}
}
while (inputLocalIndex < maxLocals) {
inputLocals[inputLocalIndex++] = TOP;
}
}
/**
* Sets the input frame from the given public API frame description.
*
* @param symbolTable the type table to use to lookup and store type {@link Symbol}.
* @param numLocal the number of local variables.
* @param local the local variable types, described using the same format as in {@link
* MethodVisitor#visitFrame}.
* @param numStack the number of operand stack elements.
* @param stack the operand stack types, described using the same format as in {@link
* MethodVisitor#visitFrame}.
*/
final void setInputFrameFromApiFormat(
final SymbolTable symbolTable,
final int numLocal,
final Object[] local,
final int numStack,
final Object[] stack) {
int inputLocalIndex = 0;
for (int i = 0; i < numLocal; ++i) {
inputLocals[inputLocalIndex++] = getAbstractTypeFromApiFormat(symbolTable, local[i]);
if (local[i] == Opcodes.LONG || local[i] == Opcodes.DOUBLE) {
inputLocals[inputLocalIndex++] = TOP;
}
}
while (inputLocalIndex < inputLocals.length) {
inputLocals[inputLocalIndex++] = TOP;
}
int numStackTop = 0;
for (int i = 0; i < numStack; ++i) {
if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) {
++numStackTop;
}
}
inputStack = new int[numStack + numStackTop];
int inputStackIndex = 0;
for (int i = 0; i < numStack; ++i) {
inputStack[inputStackIndex++] = getAbstractTypeFromApiFormat(symbolTable, stack[i]);
if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) {
inputStack[inputStackIndex++] = TOP;
}
}
outputStackTop = 0;
initializationCount = 0;
}
final int getInputStackSize() {
return inputStack.length;
}
// -----------------------------------------------------------------------------------------------
// Methods related to the output frame
// -----------------------------------------------------------------------------------------------
/**
* Returns the abstract type stored at the given local variable index in the output frame.
*
* @param localIndex the index of the local variable whose value must be returned.
* @return the abstract type stored at the given local variable index in the output frame.
*/
private int getLocal(final int localIndex) {
if (outputLocals == null || localIndex >= outputLocals.length) {
// If this local has never been assigned in this basic block, it is still equal to its value
// in the input frame.
return LOCAL_KIND | localIndex;
} else {
int abstractType = outputLocals[localIndex];
if (abstractType == 0) {
// If this local has never been assigned in this basic block, so it is still equal to its
// value in the input frame.
abstractType = outputLocals[localIndex] = LOCAL_KIND | localIndex;
}
return abstractType;
}
}
/**
* Replaces the abstract type stored at the given local variable index in the output frame.
*
* @param localIndex the index of the output frame local variable that must be set.
* @param abstractType the value that must be set.
*/
private void setLocal(final int localIndex, final int abstractType) {
// Create and/or resize the output local variables array if necessary.
if (outputLocals == null) {
outputLocals = new int[10];
}
int outputLocalsLength = outputLocals.length;
if (localIndex >= outputLocalsLength) {
int[] newOutputLocals = new int[Math.max(localIndex + 1, 2 * outputLocalsLength)];
System.arraycopy(outputLocals, 0, newOutputLocals, 0, outputLocalsLength);
outputLocals = newOutputLocals;
}
// Set the local variable.
outputLocals[localIndex] = abstractType;
}
/**
* Pushes the given abstract type on the output frame stack.
*
* @param abstractType an abstract type.
*/
private void push(final int abstractType) {
// Create and/or resize the output stack array if necessary.
if (outputStack == null) {
outputStack = new int[10];
}
int outputStackLength = outputStack.length;
if (outputStackTop >= outputStackLength) {
int[] newOutputStack = new int[Math.max(outputStackTop + 1, 2 * outputStackLength)];
System.arraycopy(outputStack, 0, newOutputStack, 0, outputStackLength);
outputStack = newOutputStack;
}
// Pushes the abstract type on the output stack.
outputStack[outputStackTop++] = abstractType;
// Updates the maximum size reached by the output stack, if needed (note that this size is
// relative to the input stack size, which is not known yet).
short outputStackSize = (short) (outputStackStart + outputStackTop);
if (outputStackSize > owner.outputStackMax) {
owner.outputStackMax = outputStackSize;
}
}
/**
* Pushes the abstract type corresponding to the given descriptor on the output frame stack.
*
* @param symbolTable the type table to use to lookup and store type {@link Symbol}.
* @param descriptor a type or method descriptor (in which case its return type is pushed).
*/
private void push(final SymbolTable symbolTable, final String descriptor) {
int typeDescriptorOffset =
descriptor.charAt(0) == '(' ? Type.getReturnTypeOffset(descriptor) : 0;
int abstractType = getAbstractTypeFromDescriptor(symbolTable, descriptor, typeDescriptorOffset);
if (abstractType != 0) {
push(abstractType);
if (abstractType == LONG || abstractType == DOUBLE) {
push(TOP);
}
}
}
/**
* Pops an abstract type from the output frame stack and returns its value.
*
* @return the abstract type that has been popped from the output frame stack.
*/
private int pop() {
if (outputStackTop > 0) {
return outputStack[--outputStackTop];
} else {
// If the output frame stack is empty, pop from the input stack.
return STACK_KIND | -(--outputStackStart);
}
}
/**
* Pops the given number of abstract types from the output frame stack.
*
* @param elements the number of abstract types that must be popped.
*/
private void pop(final int elements) {
if (outputStackTop >= elements) {
outputStackTop -= elements;
} else {
// If the number of elements to be popped is greater than the number of elements in the output
// stack, clear it, and pop the remaining elements from the input stack.
outputStackStart -= elements - outputStackTop;
outputStackTop = 0;
}
}
/**
* Pops as many abstract types from the output frame stack as described by the given descriptor.
*
* @param descriptor a type or method descriptor (in which case its argument types are popped).
*/
private void pop(final String descriptor) {
char firstDescriptorChar = descriptor.charAt(0);
if (firstDescriptorChar == '(') {
pop((Type.getArgumentsAndReturnSizes(descriptor) >> 2) - 1);
} else if (firstDescriptorChar == 'J' || firstDescriptorChar == 'D') {
pop(2);
} else {
pop(1);
}
}
// -----------------------------------------------------------------------------------------------
// Methods to handle uninitialized types
// -----------------------------------------------------------------------------------------------
/**
* Adds an abstract type to the list of types on which a constructor is invoked in the basic
* block.
*
* @param abstractType an abstract type on a which a constructor is invoked.
*/
private void addInitializedType(final int abstractType) {
// Create and/or resize the initializations array if necessary.
if (initializations == null) {
initializations = new int[2];
}
int initializationsLength = initializations.length;
if (initializationCount >= initializationsLength) {
int[] newInitializations =
new int[Math.max(initializationCount + 1, 2 * initializationsLength)];
System.arraycopy(initializations, 0, newInitializations, 0, initializationsLength);
initializations = newInitializations;
}
// Store the abstract type.
initializations[initializationCount++] = abstractType;
}
/**
* Returns the "initialized" abstract type corresponding to the given abstract type.
*
* @param symbolTable the type table to use to lookup and store type {@link Symbol}.
* @param abstractType an abstract type.
* @return the REFERENCE_KIND abstract type corresponding to abstractType if it is
* UNINITIALIZED_THIS or an UNINITIALIZED_KIND or FORWARD_UNINITIALIZED_KIND abstract type for
* one of the types on which a constructor is invoked in the basic block. Otherwise returns
* abstractType.
*/
private int getInitializedType(final SymbolTable symbolTable, final int abstractType) {
if (abstractType == UNINITIALIZED_THIS
|| (abstractType & (DIM_MASK | KIND_MASK)) == UNINITIALIZED_KIND
|| (abstractType & (DIM_MASK | KIND_MASK)) == FORWARD_UNINITIALIZED_KIND) {
for (int i = 0; i < initializationCount; ++i) {
int initializedType = initializations[i];
int dim = initializedType & DIM_MASK;
int kind = initializedType & KIND_MASK;
int value = initializedType & VALUE_MASK;
if (kind == LOCAL_KIND) {
initializedType = dim + inputLocals[value];
} else if (kind == STACK_KIND) {
initializedType = dim + inputStack[inputStack.length - value];
}
if (abstractType == initializedType) {
if (abstractType == UNINITIALIZED_THIS) {
return REFERENCE_KIND | symbolTable.addType(symbolTable.getClassName());
} else {
return REFERENCE_KIND
| symbolTable.addType(symbolTable.getType(abstractType & VALUE_MASK).value);
}
}
}
}
return abstractType;
}
// -----------------------------------------------------------------------------------------------
// Main method, to simulate the execution of each instruction on the output frame
// -----------------------------------------------------------------------------------------------
/**
* Simulates the action of the given instruction on the output stack frame.
*
* @param opcode the opcode of the instruction.
* @param arg the numeric operand of the instruction, if any.
* @param argSymbol the Symbol operand of the instruction, if any.
* @param symbolTable the type table to use to lookup and store type {@link Symbol}.
*/
void execute(
final int opcode, final int arg, final Symbol argSymbol, final SymbolTable symbolTable) {
// Abstract types popped from the stack or read from local variables.
int abstractType1;
int abstractType2;
int abstractType3;
int abstractType4;
switch (opcode) {
case Opcodes.NOP:
case Opcodes.INEG:
case Opcodes.LNEG:
case Opcodes.FNEG:
case Opcodes.DNEG:
case Opcodes.I2B:
case Opcodes.I2C:
case Opcodes.I2S:
case Opcodes.GOTO:
case Opcodes.RETURN:
break;
case Opcodes.ACONST_NULL:
push(NULL);
break;
case Opcodes.ICONST_M1:
case Opcodes.ICONST_0:
case Opcodes.ICONST_1:
case Opcodes.ICONST_2:
case Opcodes.ICONST_3:
case Opcodes.ICONST_4:
case Opcodes.ICONST_5:
case Opcodes.BIPUSH:
case Opcodes.SIPUSH:
case Opcodes.ILOAD:
push(INTEGER);
break;
case Opcodes.LCONST_0:
case Opcodes.LCONST_1:
case Opcodes.LLOAD:
push(LONG);
push(TOP);
break;
case Opcodes.FCONST_0:
case Opcodes.FCONST_1:
case Opcodes.FCONST_2:
case Opcodes.FLOAD:
push(FLOAT);
break;
case Opcodes.DCONST_0:
case Opcodes.DCONST_1:
case Opcodes.DLOAD:
push(DOUBLE);
push(TOP);
break;
case Opcodes.LDC:
switch (argSymbol.tag) {
case Symbol.CONSTANT_INTEGER_TAG:
push(INTEGER);
break;
case Symbol.CONSTANT_LONG_TAG:
push(LONG);
push(TOP);
break;
case Symbol.CONSTANT_FLOAT_TAG:
push(FLOAT);
break;
case Symbol.CONSTANT_DOUBLE_TAG:
push(DOUBLE);
push(TOP);
break;
case Symbol.CONSTANT_CLASS_TAG:
push(REFERENCE_KIND | symbolTable.addType("java/lang/Class"));
break;
case Symbol.CONSTANT_STRING_TAG:
push(REFERENCE_KIND | symbolTable.addType("java/lang/String"));
break;
case Symbol.CONSTANT_METHOD_TYPE_TAG:
push(REFERENCE_KIND | symbolTable.addType("java/lang/invoke/MethodType"));
break;
case Symbol.CONSTANT_METHOD_HANDLE_TAG:
push(REFERENCE_KIND | symbolTable.addType("java/lang/invoke/MethodHandle"));
break;
case Symbol.CONSTANT_DYNAMIC_TAG:
push(symbolTable, argSymbol.value);
break;
default:
throw new AssertionError();
}
break;
case Opcodes.ALOAD:
push(getLocal(arg));
break;
case Opcodes.LALOAD:
case Opcodes.D2L:
pop(2);
push(LONG);
push(TOP);
break;
case Opcodes.DALOAD:
case Opcodes.L2D:
pop(2);
push(DOUBLE);
push(TOP);
break;
case Opcodes.AALOAD:
pop(1);
abstractType1 = pop();
push(abstractType1 == NULL ? abstractType1 : ELEMENT_OF + abstractType1);
break;
case Opcodes.ISTORE:
case Opcodes.FSTORE:
case Opcodes.ASTORE:
abstractType1 = pop();
setLocal(arg, abstractType1);
if (arg > 0) {
int previousLocalType = getLocal(arg - 1);
if (previousLocalType == LONG || previousLocalType == DOUBLE) {
setLocal(arg - 1, TOP);
} else if ((previousLocalType & KIND_MASK) == LOCAL_KIND
|| (previousLocalType & KIND_MASK) == STACK_KIND) {
// The type of the previous local variable is not known yet, but if it later appears
// to be LONG or DOUBLE, we should then use TOP instead.
setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG);
}
}
break;
case Opcodes.LSTORE:
case Opcodes.DSTORE:
pop(1);
abstractType1 = pop();
setLocal(arg, abstractType1);
setLocal(arg + 1, TOP);
if (arg > 0) {
int previousLocalType = getLocal(arg - 1);
if (previousLocalType == LONG || previousLocalType == DOUBLE) {
setLocal(arg - 1, TOP);
} else if ((previousLocalType & KIND_MASK) == LOCAL_KIND
|| (previousLocalType & KIND_MASK) == STACK_KIND) {
// The type of the previous local variable is not known yet, but if it later appears
// to be LONG or DOUBLE, we should then use TOP instead.
setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG);
}
}
break;
case Opcodes.IASTORE:
case Opcodes.BASTORE:
case Opcodes.CASTORE:
case Opcodes.SASTORE:
case Opcodes.FASTORE:
case Opcodes.AASTORE:
pop(3);
break;
case Opcodes.LASTORE:
case Opcodes.DASTORE:
pop(4);
break;
case Opcodes.POP:
case Opcodes.IFEQ:
case Opcodes.IFNE:
case Opcodes.IFLT:
case Opcodes.IFGE:
case Opcodes.IFGT:
case Opcodes.IFLE:
case Opcodes.IRETURN:
case Opcodes.FRETURN:
case Opcodes.ARETURN:
case Opcodes.TABLESWITCH:
case Opcodes.LOOKUPSWITCH:
case Opcodes.ATHROW:
case Opcodes.MONITORENTER:
case Opcodes.MONITOREXIT:
case Opcodes.IFNULL:
case Opcodes.IFNONNULL:
pop(1);
break;
case Opcodes.POP2:
case Opcodes.IF_ICMPEQ:
case Opcodes.IF_ICMPNE:
case Opcodes.IF_ICMPLT:
case Opcodes.IF_ICMPGE:
case Opcodes.IF_ICMPGT:
case Opcodes.IF_ICMPLE:
case Opcodes.IF_ACMPEQ:
case Opcodes.IF_ACMPNE:
case Opcodes.LRETURN:
case Opcodes.DRETURN:
pop(2);
break;
case Opcodes.DUP:
abstractType1 = pop();
push(abstractType1);
push(abstractType1);
break;
case Opcodes.DUP_X1:
abstractType1 = pop();
abstractType2 = pop();
push(abstractType1);
push(abstractType2);
push(abstractType1);
break;
case Opcodes.DUP_X2:
abstractType1 = pop();
abstractType2 = pop();
abstractType3 = pop();
push(abstractType1);
push(abstractType3);
push(abstractType2);
push(abstractType1);
break;
case Opcodes.DUP2:
abstractType1 = pop();
abstractType2 = pop();
push(abstractType2);
push(abstractType1);
push(abstractType2);
push(abstractType1);
break;
case Opcodes.DUP2_X1:
abstractType1 = pop();
abstractType2 = pop();
abstractType3 = pop();
push(abstractType2);
push(abstractType1);
push(abstractType3);
push(abstractType2);
push(abstractType1);
break;
case Opcodes.DUP2_X2:
abstractType1 = pop();
abstractType2 = pop();
abstractType3 = pop();
abstractType4 = pop();
push(abstractType2);
push(abstractType1);
push(abstractType4);
push(abstractType3);
push(abstractType2);
push(abstractType1);
break;
case Opcodes.SWAP:
abstractType1 = pop();
abstractType2 = pop();
push(abstractType1);
push(abstractType2);
break;
case Opcodes.IALOAD:
case Opcodes.BALOAD:
case Opcodes.CALOAD:
case Opcodes.SALOAD:
case Opcodes.IADD:
case Opcodes.ISUB:
case Opcodes.IMUL:
case Opcodes.IDIV:
case Opcodes.IREM:
case Opcodes.IAND:
case Opcodes.IOR:
case Opcodes.IXOR:
case Opcodes.ISHL:
case Opcodes.ISHR:
case Opcodes.IUSHR:
case Opcodes.L2I:
case Opcodes.D2I:
case Opcodes.FCMPL:
case Opcodes.FCMPG:
pop(2);
push(INTEGER);
break;
case Opcodes.LADD:
case Opcodes.LSUB:
case Opcodes.LMUL:
case Opcodes.LDIV:
case Opcodes.LREM:
case Opcodes.LAND:
case Opcodes.LOR:
case Opcodes.LXOR:
pop(4);
push(LONG);
push(TOP);
break;
case Opcodes.FALOAD:
case Opcodes.FADD:
case Opcodes.FSUB:
case Opcodes.FMUL:
case Opcodes.FDIV:
case Opcodes.FREM:
case Opcodes.L2F:
case Opcodes.D2F:
pop(2);
push(FLOAT);
break;
case Opcodes.DADD:
case Opcodes.DSUB:
case Opcodes.DMUL:
case Opcodes.DDIV:
case Opcodes.DREM:
pop(4);
push(DOUBLE);
push(TOP);
break;
case Opcodes.LSHL:
case Opcodes.LSHR:
case Opcodes.LUSHR:
pop(3);
push(LONG);
push(TOP);
break;
case Opcodes.IINC:
setLocal(arg, INTEGER);
break;
case Opcodes.I2L:
case Opcodes.F2L:
pop(1);
push(LONG);
push(TOP);
break;
case Opcodes.I2F:
pop(1);
push(FLOAT);
break;
case Opcodes.I2D:
case Opcodes.F2D:
pop(1);
push(DOUBLE);
push(TOP);
break;
case Opcodes.F2I:
case Opcodes.ARRAYLENGTH:
case Opcodes.INSTANCEOF:
pop(1);
push(INTEGER);
break;
case Opcodes.LCMP:
case Opcodes.DCMPL:
case Opcodes.DCMPG:
pop(4);
push(INTEGER);
break;
case Opcodes.JSR:
case Opcodes.RET:
throw new IllegalArgumentException("JSR/RET are not supported with computeFrames option");
case Opcodes.GETSTATIC:
push(symbolTable, argSymbol.value);
break;
case Opcodes.PUTSTATIC:
pop(argSymbol.value);
break;
case Opcodes.GETFIELD:
pop(1);
push(symbolTable, argSymbol.value);
break;
case Opcodes.PUTFIELD:
pop(argSymbol.value);
pop();
break;
case Opcodes.INVOKEVIRTUAL:
case Opcodes.INVOKESPECIAL:
case Opcodes.INVOKESTATIC:
case Opcodes.INVOKEINTERFACE:
pop(argSymbol.value);
if (opcode != Opcodes.INVOKESTATIC) {
abstractType1 = pop();
if (opcode == Opcodes.INVOKESPECIAL && argSymbol.name.charAt(0) == '<') {
addInitializedType(abstractType1);
}
}
push(symbolTable, argSymbol.value);
break;
case Opcodes.INVOKEDYNAMIC:
pop(argSymbol.value);
push(symbolTable, argSymbol.value);
break;
case Opcodes.NEW:
push(UNINITIALIZED_KIND | symbolTable.addUninitializedType(argSymbol.value, arg));
break;
case Opcodes.NEWARRAY:
pop();
switch (arg) {
case Opcodes.T_BOOLEAN:
push(ARRAY_OF | BOOLEAN);
break;
case Opcodes.T_CHAR:
push(ARRAY_OF | CHAR);
break;
case Opcodes.T_BYTE:
push(ARRAY_OF | BYTE);
break;
case Opcodes.T_SHORT:
push(ARRAY_OF | SHORT);
break;
case Opcodes.T_INT:
push(ARRAY_OF | INTEGER);
break;
case Opcodes.T_FLOAT:
push(ARRAY_OF | FLOAT);
break;
case Opcodes.T_DOUBLE:
push(ARRAY_OF | DOUBLE);
break;
case Opcodes.T_LONG:
push(ARRAY_OF | LONG);
break;
default:
throw new IllegalArgumentException();
}
break;
case Opcodes.ANEWARRAY:
String arrayElementType = argSymbol.value;
pop();
if (arrayElementType.charAt(0) == '[') {
push(symbolTable, '[' + arrayElementType);
} else {
push(ARRAY_OF | REFERENCE_KIND | symbolTable.addType(arrayElementType));
}
break;
case Opcodes.CHECKCAST:
String castType = argSymbol.value;
pop();
if (castType.charAt(0) == '[') {
push(symbolTable, castType);
} else {
push(REFERENCE_KIND | symbolTable.addType(castType));
}
break;
case Opcodes.MULTIANEWARRAY:
pop(arg);
push(symbolTable, argSymbol.value);
break;
default:
throw new IllegalArgumentException();
}
}
// -----------------------------------------------------------------------------------------------
// Frame merging methods, used in the second step of the stack map frame computation algorithm
// -----------------------------------------------------------------------------------------------
/**
* Computes the concrete output type corresponding to a given abstract output type.
*
* @param abstractOutputType an abstract output type.
* @param numStack the size of the input stack, used to resolve abstract output types of
* STACK_KIND kind.
* @return the concrete output type corresponding to 'abstractOutputType'.
*/
private int getConcreteOutputType(final int abstractOutputType, final int numStack) {
int dim = abstractOutputType & DIM_MASK;
int kind = abstractOutputType & KIND_MASK;
if (kind == LOCAL_KIND) {
// By definition, a LOCAL_KIND type designates the concrete type of a local variable at
// the beginning of the basic block corresponding to this frame (which is known when
// this method is called, but was not when the abstract type was computed).
int concreteOutputType = dim + inputLocals[abstractOutputType & VALUE_MASK];
if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0
&& (concreteOutputType == LONG || concreteOutputType == DOUBLE)) {
concreteOutputType = TOP;
}
return concreteOutputType;
} else if (kind == STACK_KIND) {
// By definition, a STACK_KIND type designates the concrete type of a local variable at
// the beginning of the basic block corresponding to this frame (which is known when
// this method is called, but was not when the abstract type was computed).
int concreteOutputType = dim + inputStack[numStack - (abstractOutputType & VALUE_MASK)];
if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0
&& (concreteOutputType == LONG || concreteOutputType == DOUBLE)) {
concreteOutputType = TOP;
}
return concreteOutputType;
} else {
return abstractOutputType;
}
}
/**
* Merges the input frame of the given {@link Frame} with the input and output frames of this
* {@link Frame}. Returns {@literal true} if the given frame has been changed by this operation
* (the input and output frames of this {@link Frame} are never changed).
*
* @param symbolTable the type table to use to lookup and store type {@link Symbol}.
* @param dstFrame the {@link Frame} whose input frame must be updated. This should be the frame
* of a successor, in the control flow graph, of the basic block corresponding to this frame.
* @param catchTypeIndex if 'frame' corresponds to an exception handler basic block, the type
* table index of the caught exception type, otherwise 0.
* @return {@literal true} if the input frame of 'frame' has been changed by this operation.
*/
final boolean merge(
final SymbolTable symbolTable, final Frame dstFrame, final int catchTypeIndex) {
boolean frameChanged = false;
// Compute the concrete types of the local variables at the end of the basic block corresponding
// to this frame, by resolving its abstract output types, and merge these concrete types with
// those of the local variables in the input frame of dstFrame.
int numLocal = inputLocals.length;
int numStack = inputStack.length;
if (dstFrame.inputLocals == null) {
dstFrame.inputLocals = new int[numLocal];
frameChanged = true;
}
for (int i = 0; i < numLocal; ++i) {
int concreteOutputType;
if (outputLocals != null && i < outputLocals.length) {
int abstractOutputType = outputLocals[i];
if (abstractOutputType == 0) {
// If the local variable has never been assigned in this basic block, it is equal to its
// value at the beginning of the block.
concreteOutputType = inputLocals[i];
} else {
concreteOutputType = getConcreteOutputType(abstractOutputType, numStack);
}
} else {
// If the local variable has never been assigned in this basic block, it is equal to its
// value at the beginning of the block.
concreteOutputType = inputLocals[i];
}
// concreteOutputType might be an uninitialized type from the input locals or from the input
// stack. However, if a constructor has been called for this
|
Frame
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/action/admin/indices/get/GetIndexRequestTests.java
|
{
"start": 993,
"end": 4226
}
|
class ____ extends ESTestCase {
public void testFeaturesFromRequest() {
int numFeatures = randomIntBetween(1, GetIndexRequest.DEFAULT_FEATURES.length);
List<String> featureNames = new ArrayList<>();
List<GetIndexRequest.Feature> expectedFeatures = new ArrayList<>();
for (int k = 0; k < numFeatures; k++) {
GetIndexRequest.Feature feature = randomValueOtherThanMany(
f -> featureNames.contains(f.name()),
() -> randomFrom(GetIndexRequest.DEFAULT_FEATURES)
);
featureNames.add(feature.name());
expectedFeatures.add(feature);
}
RestRequest request = RestRequestTests.contentRestRequest("", Map.of("features", String.join(",", featureNames)));
GetIndexRequest.Feature[] featureArray = GetIndexRequest.Feature.fromRequest(request);
assertThat(featureArray, arrayContainingInAnyOrder(expectedFeatures.toArray(GetIndexRequest.Feature[]::new)));
}
public void testDuplicateFeatures() {
int numFeatures = randomIntBetween(1, 5);
GetIndexRequest.Feature feature = randomFrom(GetIndexRequest.DEFAULT_FEATURES);
List<String> featureList = new ArrayList<>();
for (int k = 0; k < numFeatures; k++) {
featureList.add(feature.name());
}
RestRequest request = RestRequestTests.contentRestRequest("", Map.of("features", String.join(",", featureList)));
GetIndexRequest.Feature[] features = GetIndexRequest.Feature.fromRequest(request);
assertThat(features.length, equalTo(1));
assertThat(features[0], equalTo(feature));
}
public void testMissingFeatures() {
RestRequest request = RestRequestTests.contentRestRequest("", Map.of());
GetIndexRequest.Feature[] features = GetIndexRequest.Feature.fromRequest(request);
assertThat(features, arrayContainingInAnyOrder(GetIndexRequest.DEFAULT_FEATURES));
}
public void testInvalidFeatures() {
int numFeatures = randomIntBetween(1, 4);
List<String> invalidFeatures = new ArrayList<>();
for (int k = 0; k < numFeatures; k++) {
invalidFeatures.add(randomAlphaOfLength(5));
}
RestRequest request = RestRequestTests.contentRestRequest("", Map.of("features", String.join(",", invalidFeatures)));
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> GetIndexRequest.Feature.fromRequest(request));
assertThat(e.getMessage(), containsString(Strings.format("Invalid features specified [%s]", String.join(",", invalidFeatures))));
}
public void testIndicesOptions() {
GetIndexRequest getIndexRequest = new GetIndexRequest(TEST_REQUEST_TIMEOUT);
assertThat(
getIndexRequest.indicesOptions().concreteTargetOptions(),
equalTo(IndicesOptions.strictExpandOpen().concreteTargetOptions())
);
assertThat(getIndexRequest.indicesOptions().wildcardOptions(), equalTo(IndicesOptions.strictExpandOpen().wildcardOptions()));
assertThat(getIndexRequest.indicesOptions().gatekeeperOptions(), equalTo(IndicesOptions.strictExpandOpen().gatekeeperOptions()));
}
}
|
GetIndexRequestTests
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/placement/MultiNodeSortingManager.java
|
{
"start": 1744,
"end": 4340
}
|
class ____<N extends SchedulerNode>
extends AbstractService {
private static final Logger LOG = LoggerFactory
.getLogger(MultiNodeSortingManager.class);
private RMContext rmContext;
private Map<String, MultiNodeSorter<N>> runningMultiNodeSorters;
private Set<MultiNodePolicySpec> policySpecs = new HashSet<MultiNodePolicySpec>();
private Configuration conf;
private boolean multiNodePlacementEnabled;
private long skipNodeInterval;
public MultiNodeSortingManager() {
super("MultiNodeSortingManager");
this.runningMultiNodeSorters = new ConcurrentHashMap<>();
}
@Override
public void serviceInit(Configuration configuration) throws Exception {
LOG.info("Initializing NodeSortingService=" + getName());
super.serviceInit(configuration);
this.conf = configuration;
this.skipNodeInterval = YarnConfiguration.getSkipNodeInterval(conf);
}
@Override
public void serviceStart() throws Exception {
LOG.info("Starting NodeSortingService=" + getName());
createAllPolicies();
super.serviceStart();
}
@Override
public void serviceStop() throws Exception {
for (MultiNodeSorter<N> sorter : runningMultiNodeSorters.values()) {
sorter.stop();
}
super.serviceStop();
}
private void createAllPolicies() {
if (!multiNodePlacementEnabled) {
return;
}
for (MultiNodePolicySpec policy : policySpecs) {
MultiNodeSorter<N> mon = new MultiNodeSorter<N>(rmContext, policy);
mon.init(conf);
mon.start();
runningMultiNodeSorters.put(policy.getPolicyClassName(), mon);
}
}
public MultiNodeSorter<N> getMultiNodePolicy(String name) {
return runningMultiNodeSorters.get(name);
}
public void setRMContext(RMContext context) {
this.rmContext = context;
}
public void registerMultiNodePolicyNames(
boolean isMultiNodePlacementEnabled,
Set<MultiNodePolicySpec> multiNodePlacementPolicies) {
this.policySpecs.addAll(multiNodePlacementPolicies);
this.multiNodePlacementEnabled = isMultiNodePlacementEnabled;
LOG.info("MultiNode scheduling is '" + multiNodePlacementEnabled +
"', and configured policies are " + StringUtils
.join(policySpecs.iterator(), ","));
}
public Iterator<N> getMultiNodeSortIterator(Collection<N> nodes,
String partition, String policyName) {
// nodeLookupPolicy can be null if app is configured with invalid policy.
// in such cases, use the the first node.
if(policyName == null) {
LOG.warn("Multi Node scheduling is enabled, however invalid
|
MultiNodeSortingManager
|
java
|
spring-projects__spring-boot
|
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/testing/springbootapplications/springgraphqltests/GreetingControllerTests.java
|
{
"start": 1072,
"end": 1551
}
|
class ____ {
@Autowired
private GraphQlTester graphQlTester;
@Test
void shouldGreetWithSpecificName() {
this.graphQlTester.document("{ greeting(name: \"Alice\") } ")
.execute()
.path("greeting")
.entity(String.class)
.isEqualTo("Hello, Alice!");
}
@Test
void shouldGreetWithDefaultName() {
this.graphQlTester.document("{ greeting } ")
.execute()
.path("greeting")
.entity(String.class)
.isEqualTo("Hello, Spring!");
}
}
|
GreetingControllerTests
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/ConnectorFeatures.java
|
{
"start": 1292,
"end": 7633
}
|
class ____ implements Writeable, ToXContentObject {
@Nullable
private final FeatureEnabled documentLevelSecurityEnabled;
@Nullable
private final FeatureEnabled incrementalSyncEnabled;
@Nullable
private final FeatureEnabled nativeConnectorAPIKeysEnabled;
@Nullable
private final SyncRulesFeatures syncRulesFeatures;
/**
* Constructs a new instance of ConnectorFeatures.
*
* @param documentLevelSecurityEnabled A flag indicating whether document-level security is enabled.
* @param incrementalSyncEnabled A flag indicating whether incremental sync is enabled.
* @param nativeConnectorAPIKeysEnabled A flag indicating whether support for api keys is enabled for native connectors.
* @param syncRulesFeatures An {@link SyncRulesFeatures} object indicating if basic and advanced sync rules are enabled.
*/
private ConnectorFeatures(
FeatureEnabled documentLevelSecurityEnabled,
FeatureEnabled incrementalSyncEnabled,
FeatureEnabled nativeConnectorAPIKeysEnabled,
SyncRulesFeatures syncRulesFeatures
) {
this.documentLevelSecurityEnabled = documentLevelSecurityEnabled;
this.incrementalSyncEnabled = incrementalSyncEnabled;
this.nativeConnectorAPIKeysEnabled = nativeConnectorAPIKeysEnabled;
this.syncRulesFeatures = syncRulesFeatures;
}
public ConnectorFeatures(StreamInput in) throws IOException {
this.documentLevelSecurityEnabled = in.readOptionalWriteable(FeatureEnabled::new);
this.incrementalSyncEnabled = in.readOptionalWriteable(FeatureEnabled::new);
this.nativeConnectorAPIKeysEnabled = in.readOptionalWriteable(FeatureEnabled::new);
this.syncRulesFeatures = in.readOptionalWriteable(SyncRulesFeatures::new);
}
private static final ParseField DOCUMENT_LEVEL_SECURITY_ENABLED_FIELD = new ParseField("document_level_security");
private static final ParseField INCREMENTAL_SYNC_ENABLED_FIELD = new ParseField("incremental_sync");
private static final ParseField NATIVE_CONNECTOR_API_KEYS_ENABLED_FIELD = new ParseField("native_connector_api_keys");
private static final ParseField SYNC_RULES_FIELD = new ParseField("sync_rules");
private static final ConstructingObjectParser<ConnectorFeatures, Void> PARSER = new ConstructingObjectParser<>(
"connector_features",
true,
args -> new Builder().setDocumentLevelSecurityEnabled((FeatureEnabled) args[0])
.setIncrementalSyncEnabled((FeatureEnabled) args[1])
.setNativeConnectorAPIKeysEnabled((FeatureEnabled) args[2])
.setSyncRulesFeatures((SyncRulesFeatures) args[3])
.build()
);
static {
PARSER.declareObject(optionalConstructorArg(), (p, c) -> FeatureEnabled.fromXContent(p), DOCUMENT_LEVEL_SECURITY_ENABLED_FIELD);
PARSER.declareObject(optionalConstructorArg(), (p, c) -> FeatureEnabled.fromXContent(p), INCREMENTAL_SYNC_ENABLED_FIELD);
PARSER.declareObject(optionalConstructorArg(), (p, c) -> FeatureEnabled.fromXContent(p), NATIVE_CONNECTOR_API_KEYS_ENABLED_FIELD);
PARSER.declareObject(optionalConstructorArg(), (p, c) -> SyncRulesFeatures.fromXContent(p), SYNC_RULES_FIELD);
}
public static ConnectorFeatures fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
public static ConnectorFeatures fromXContentBytes(BytesReference source, XContentType xContentType) {
try (XContentParser parser = XContentHelper.createParser(XContentParserConfiguration.EMPTY, source, xContentType)) {
return ConnectorFeatures.fromXContent(parser);
} catch (IOException e) {
throw new ElasticsearchParseException("Failed to parse a connector features.", e);
}
}
public FeatureEnabled getDocumentLevelSecurityEnabled() {
return documentLevelSecurityEnabled;
}
public FeatureEnabled getIncrementalSyncEnabled() {
return incrementalSyncEnabled;
}
public FeatureEnabled getNativeConnectorAPIKeysEnabled() {
return nativeConnectorAPIKeysEnabled;
}
public SyncRulesFeatures getSyncRulesFeatures() {
return syncRulesFeatures;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
{
if (documentLevelSecurityEnabled != null) {
builder.field(DOCUMENT_LEVEL_SECURITY_ENABLED_FIELD.getPreferredName(), documentLevelSecurityEnabled);
}
if (incrementalSyncEnabled != null) {
builder.field(INCREMENTAL_SYNC_ENABLED_FIELD.getPreferredName(), incrementalSyncEnabled);
}
if (nativeConnectorAPIKeysEnabled != null) {
builder.field(NATIVE_CONNECTOR_API_KEYS_ENABLED_FIELD.getPreferredName(), nativeConnectorAPIKeysEnabled);
}
if (syncRulesFeatures != null) {
builder.field(SYNC_RULES_FIELD.getPreferredName(), syncRulesFeatures);
}
}
builder.endObject();
return builder;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeOptionalWriteable(documentLevelSecurityEnabled);
out.writeOptionalWriteable(incrementalSyncEnabled);
out.writeOptionalWriteable(nativeConnectorAPIKeysEnabled);
out.writeOptionalWriteable(syncRulesFeatures);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConnectorFeatures features = (ConnectorFeatures) o;
return Objects.equals(documentLevelSecurityEnabled, features.documentLevelSecurityEnabled)
&& Objects.equals(incrementalSyncEnabled, features.incrementalSyncEnabled)
&& Objects.equals(nativeConnectorAPIKeysEnabled, features.nativeConnectorAPIKeysEnabled)
&& Objects.equals(syncRulesFeatures, features.syncRulesFeatures);
}
@Override
public int hashCode() {
return Objects.hash(documentLevelSecurityEnabled, incrementalSyncEnabled, nativeConnectorAPIKeysEnabled, syncRulesFeatures);
}
public static
|
ConnectorFeatures
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/LexerConfig.java
|
{
"start": 388,
"end": 472
}
|
class ____ hooking versioning information into the ANTLR parser.
*/
public abstract
|
for
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/cglib/util/ParallelSorter.java
|
{
"start": 2069,
"end": 6401
}
|
class ____ extends SorterTemplate {
protected Object[] a;
private Comparer comparer;
protected ParallelSorter() {
}
abstract public ParallelSorter newInstance(Object[] arrays);
/**
* Create a new ParallelSorter object for a set of arrays. You may
* sort the arrays multiple times via the same ParallelSorter object.
* @param arrays An array of arrays to sort. The arrays may be a mix
* of primitive and non-primitive types, but should all be the same
* length.
*/
public static ParallelSorter create(Object[] arrays) {
Generator gen = new Generator();
gen.setArrays(arrays);
return gen.create();
}
private int len() {
return ((Object[])a[0]).length;
}
/**
* Sort the arrays using the quicksort algorithm.
* @param index array (column) to sort by
*/
public void quickSort(int index) {
quickSort(index, 0, len(), null);
}
/**
* Sort the arrays using the quicksort algorithm.
* @param index array (column) to sort by
* @param lo starting array index (row), inclusive
* @param hi ending array index (row), exclusive
*/
public void quickSort(int index, int lo, int hi) {
quickSort(index, lo, hi, null);
}
/**
* Sort the arrays using the quicksort algorithm.
* @param index array (column) to sort by
* @param cmp Comparator to use if the specified column is non-primitive
*/
public void quickSort(int index, Comparator cmp) {
quickSort(index, 0, len(), cmp);
}
/**
* Sort the arrays using the quicksort algorithm.
* @param index array (column) to sort by
* @param lo starting array index (row), inclusive
* @param hi ending array index (row), exclusive
* @param cmp Comparator to use if the specified column is non-primitive
*/
public void quickSort(int index, int lo, int hi, Comparator cmp) {
chooseComparer(index, cmp);
super.quickSort(lo, hi - 1);
}
/**
* @param index array (column) to sort by
*/
public void mergeSort(int index) {
mergeSort(index, 0, len(), null);
}
/**
* Sort the arrays using an in-place merge sort.
* @param index array (column) to sort by
* @param lo starting array index (row), inclusive
* @param hi ending array index (row), exclusive
*/
public void mergeSort(int index, int lo, int hi) {
mergeSort(index, lo, hi, null);
}
/**
* Sort the arrays using an in-place merge sort.
* @param index array (column) to sort by
* @param cmp Comparator to use if the specified column is non-primitive
*/
public void mergeSort(int index, Comparator cmp) {
mergeSort(index, 0, len(), cmp);
}
/**
* Sort the arrays using an in-place merge sort.
* @param index array (column) to sort by
* @param lo starting array index (row), inclusive
* @param hi ending array index (row), exclusive
* @param cmp Comparator to use if the specified column is non-primitive
*/
public void mergeSort(int index, int lo, int hi, Comparator cmp) {
chooseComparer(index, cmp);
super.mergeSort(lo, hi - 1);
}
private void chooseComparer(int index, Comparator cmp) {
Object array = a[index];
Class type = array.getClass().componentType();
if (type.equals(Integer.TYPE)) {
comparer = new IntComparer((int[])array);
} else if (type.equals(Long.TYPE)) {
comparer = new LongComparer((long[])array);
} else if (type.equals(Double.TYPE)) {
comparer = new DoubleComparer((double[])array);
} else if (type.equals(Float.TYPE)) {
comparer = new FloatComparer((float[])array);
} else if (type.equals(Short.TYPE)) {
comparer = new ShortComparer((short[])array);
} else if (type.equals(Byte.TYPE)) {
comparer = new ByteComparer((byte[])array);
} else if (cmp != null) {
comparer = new ComparatorComparer((Object[])array, cmp);
} else {
comparer = new ObjectComparer((Object[])array);
}
}
@Override
protected int compare(int i, int j) {
return comparer.compare(i, j);
}
|
ParallelSorter
|
java
|
apache__camel
|
core/camel-core-model/src/main/java/org/apache/camel/model/language/MethodCallExpression.java
|
{
"start": 8531,
"end": 12574
}
|
class ____ as the instance
if (instance instanceof Class) {
this.beanType = (Class<?>) instance;
this.instance = null;
} else {
this.beanType = null;
this.instance = instance;
}
return this;
}
public Builder beanType(Class<?> beanType) {
this.beanType = beanType;
this.instance = null;
return this;
}
/**
* Class name (fully qualified) of the bean to use
*
* Will lookup in registry and if there is a single instance of the same type, then the existing bean is used,
* otherwise a new bean is created (requires a default no-arg constructor).
*/
public Builder beanTypeName(String beanTypeName) {
this.beanTypeName = beanTypeName;
return this;
}
/**
* Scope of bean.
*
* When using singleton scope (default) the bean is created or looked up only once and reused for the lifetime
* of the endpoint. The bean should be thread-safe in case concurrent threads is calling the bean at the same
* time. When using request scope the bean is created or looked up once per request (exchange). This can be used
* if you want to store state on a bean while processing a request and you want to call the same bean instance
* multiple times while processing the request. The bean does not have to be thread-safe as the instance is only
* called from the same request. When using prototype scope, then the bean will be looked up or created per
* call. However in case of lookup then this is delegated to the bean registry such as Spring or CDI (if in
* use), which depends on their configuration can act as either singleton or prototype scope. So when using
* prototype scope then this depends on the bean registry implementation.
*/
public Builder scope(String scope) {
this.scope = scope;
return this;
}
/**
* Scope of bean.
*
* When using singleton scope (default) the bean is created or looked up only once and reused for the lifetime
* of the endpoint. The bean should be thread-safe in case concurrent threads is calling the bean at the same
* time. When using request scope the bean is created or looked up once per request (exchange). This can be used
* if you want to store state on a bean while processing a request and you want to call the same bean instance
* multiple times while processing the request. The bean does not have to be thread-safe as the instance is only
* called from the same request. When using prototype scope, then the bean will be looked up or created per
* call. However in case of lookup then this is delegated to the bean registry such as Spring or CDI (if in
* use), which depends on their configuration can act as either singleton or prototype scope. So when using
* prototype scope then this depends on the bean registry implementation.
*/
public Builder scope(Scope scope) {
this.scope = scope == null ? null : scope.value;
return this;
}
/**
* Whether to validate the bean has the configured method.
*/
public Builder validate(String validate) {
this.validate = validate;
return this;
}
/**
* Whether to validate the bean has the configured method.
*/
public Builder validate(boolean validate) {
this.validate = Boolean.toString(validate);
return this;
}
@Override
public MethodCallExpression end() {
return new MethodCallExpression(this);
}
}
/**
* {@code Scope} defines the possible bean scopes that can be used.
*/
@XmlTransient
public
|
type
|
java
|
alibaba__nacos
|
client/src/main/java/com/alibaba/nacos/client/config/impl/CacheData.java
|
{
"start": 19037,
"end": 22262
}
|
class ____ implements Runnable {
boolean async = false;
public boolean isAsync() {
return async;
}
public void setAsync(boolean async) {
this.async = async;
}
}
public static String getMd5String(String config) {
return (null == config) ? Constants.NULL : MD5Utils.md5Hex(config, Constants.ENCODE);
}
private String loadCacheContentFromDiskLocal(String name, String dataId, String group, String tenant) {
String content = LocalConfigInfoProcessor.getFailover(name, dataId, group, tenant);
content = (null != content) ? content : LocalConfigInfoProcessor.getSnapshot(name, dataId, group, tenant);
return content;
}
/**
* 1.first add listener.default is false;need to check. 2.receive config change notify,set false;need to check.
* 3.last listener is remove,set to false;need to check
*
* @return
*/
public boolean isConsistentWithServer() {
return isConsistentWithServer.get();
}
public void setConsistentWithServer(boolean consistentWithServer) {
isConsistentWithServer.set(consistentWithServer);
}
public boolean isDiscard() {
return isDiscard;
}
public void setDiscard(boolean discard) {
isDiscard = discard;
}
public CacheData(ConfigFilterChainManager configFilterChainManager, String envName, String dataId, String group) {
this(configFilterChainManager, envName, dataId, group, TenantUtil.getUserTenantForAcm());
}
public CacheData(ConfigFilterChainManager configFilterChainManager, String envName, String dataId, String group,
String tenant) {
if (null == dataId || null == group) {
throw new IllegalArgumentException("dataId=" + dataId + ", group=" + group);
}
this.configFilterChainManager = configFilterChainManager;
this.envName = envName;
this.dataId = dataId;
this.group = group;
this.tenant = tenant;
this.listeners = new CopyOnWriteArrayList<>();
this.isInitializing = true;
if (initSnapshot) {
this.content = loadCacheContentFromDiskLocal(envName, dataId, group, tenant);
this.encryptedDataKey = loadEncryptedDataKeyFromDiskLocal(envName, dataId, group, tenant);
this.md5 = getMd5String(this.content);
}
}
// ==================
public String getEncryptedDataKey() {
return encryptedDataKey;
}
public void setEncryptedDataKey(String encryptedDataKey) {
this.encryptedDataKey = encryptedDataKey;
}
private String loadEncryptedDataKeyFromDiskLocal(String envName, String dataId, String group, String tenant) {
String encryptedDataKey = LocalEncryptedDataKeyProcessor.getEncryptDataKeyFailover(envName, dataId, group,
tenant);
if (encryptedDataKey != null) {
return encryptedDataKey;
}
return LocalEncryptedDataKeyProcessor.getEncryptDataKeySnapshot(envName, dataId, group, tenant);
}
private static
|
NotifyTask
|
java
|
apache__spark
|
examples/src/main/java/org/apache/spark/examples/sql/JavaUserDefinedTypedAggregation.java
|
{
"start": 1813,
"end": 2425
}
|
class ____ implements Serializable {
private long sum;
private long count;
// Constructors, getters, setters...
// $example off:typed_custom_aggregation$
public Average() {
}
public Average(long sum, long count) {
this.sum = sum;
this.count = count;
}
public long getSum() {
return sum;
}
public void setSum(long sum) {
this.sum = sum;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
// $example on:typed_custom_aggregation$
}
public static
|
Average
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/date/MonthNameMillisEvaluator.java
|
{
"start": 4289,
"end": 5103
}
|
class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory val;
private final ZoneId zoneId;
private final Locale locale;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory val, ZoneId zoneId,
Locale locale) {
this.source = source;
this.val = val;
this.zoneId = zoneId;
this.locale = locale;
}
@Override
public MonthNameMillisEvaluator get(DriverContext context) {
return new MonthNameMillisEvaluator(source, val.get(context), zoneId, locale, context);
}
@Override
public String toString() {
return "MonthNameMillisEvaluator[" + "val=" + val + ", zoneId=" + zoneId + ", locale=" + locale + "]";
}
}
}
|
Factory
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/TemplateUtils.java
|
{
"start": 1768,
"end": 7559
}
|
class ____ {
/** Retrieve global templates from function class. */
static Set<FunctionTemplate> extractGlobalFunctionTemplates(
DataTypeFactory typeFactory, Class<? extends UserDefinedFunction> function) {
return asFunctionTemplates(
typeFactory, collectAnnotationsOfClass(FunctionHint.class, function));
}
/** Retrieve global templates from procedure class. */
static Set<FunctionTemplate> extractProcedureGlobalFunctionTemplates(
DataTypeFactory typeFactory, Class<? extends Procedure> procedure) {
return asFunctionTemplatesForProcedure(
typeFactory, collectAnnotationsOfClass(ProcedureHint.class, procedure));
}
/** Retrieve local templates from function method. */
static Set<FunctionTemplate> extractLocalFunctionTemplates(
DataTypeFactory typeFactory, Method method) {
return asFunctionTemplates(
typeFactory, collectAnnotationsOfMethod(FunctionHint.class, method));
}
/** Retrieve local templates from procedure method. */
static Set<FunctionTemplate> extractProcedureLocalFunctionTemplates(
DataTypeFactory typeFactory, Method method) {
return asFunctionTemplatesForProcedure(
typeFactory, collectAnnotationsOfMethod(ProcedureHint.class, method));
}
/** Converts {@link FunctionHint}s to {@link FunctionTemplate}. */
static Set<FunctionTemplate> asFunctionTemplates(
DataTypeFactory typeFactory, Set<FunctionHint> hints) {
return hints.stream()
.map(
hint -> {
try {
return FunctionTemplate.fromAnnotation(typeFactory, hint);
} catch (Throwable t) {
throw extractionError(t, "Error in function hint annotation.");
}
})
.collect(Collectors.toCollection(LinkedHashSet::new));
}
/** Converts {@link ProcedureHint}s to {@link FunctionTemplate}. */
static Set<FunctionTemplate> asFunctionTemplatesForProcedure(
DataTypeFactory typeFactory, Set<ProcedureHint> hints) {
return hints.stream()
.map(
hint -> {
try {
return FunctionTemplate.fromAnnotation(typeFactory, hint);
} catch (Throwable t) {
throw extractionError(t, "Error in procedure hint annotation.");
}
})
.collect(Collectors.toCollection(LinkedHashSet::new));
}
/** Find a template that only specifies a result. */
static Set<FunctionResultTemplate> findResultOnlyTemplates(
Set<FunctionTemplate> functionTemplates,
Function<FunctionTemplate, FunctionResultTemplate> accessor) {
return functionTemplates.stream()
.filter(t -> t.getSignatureTemplate() == null && accessor.apply(t) != null)
.map(accessor)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
/** Hints that only declare a result (either accumulator or output). */
static @Nullable FunctionResultTemplate findResultOnlyTemplate(
Set<FunctionResultTemplate> globalResultOnly,
Set<FunctionResultTemplate> localResultOnly,
Set<FunctionTemplate> explicitMappings,
Function<FunctionTemplate, FunctionResultTemplate> accessor,
String hintType) {
final Set<FunctionResultTemplate> resultOnly =
Stream.concat(globalResultOnly.stream(), localResultOnly.stream())
.collect(Collectors.toCollection(LinkedHashSet::new));
final Set<FunctionResultTemplate> allResults =
Stream.concat(resultOnly.stream(), explicitMappings.stream().map(accessor))
.collect(Collectors.toCollection(LinkedHashSet::new));
if (resultOnly.size() == 1 && allResults.size() == 1) {
return resultOnly.stream().findFirst().orElse(null);
}
// different results is only fine as long as those come from a mapping
if (resultOnly.size() > 1 || (!resultOnly.isEmpty() && !explicitMappings.isEmpty())) {
throw extractionError(
String.format(
"%s hints that lead to ambiguous results are not allowed.", hintType));
}
return null;
}
/** Hints that map a signature to a result. */
static Set<FunctionTemplate> findResultMappingTemplates(
Set<FunctionTemplate> globalTemplates,
Set<FunctionTemplate> localTemplates,
Function<FunctionTemplate, FunctionResultTemplate> accessor) {
return Stream.concat(globalTemplates.stream(), localTemplates.stream())
.filter(t -> t.getSignatureTemplate() != null && accessor.apply(t) != null)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
/** Hints that only declare an input. */
static Set<FunctionSignatureTemplate> findInputOnlyTemplates(
Set<FunctionTemplate> global,
Set<FunctionTemplate> local,
Function<FunctionTemplate, FunctionResultTemplate> accessor) {
return Stream.concat(global.stream(), local.stream())
.filter(t -> t.getSignatureTemplate() != null && accessor.apply(t) == null)
.map(FunctionTemplate::getSignatureTemplate)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
private TemplateUtils() {
// no instantiation
}
}
|
TemplateUtils
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/type/descriptor/java/UrlJavaType.java
|
{
"start": 488,
"end": 1903
}
|
class ____ extends AbstractClassJavaType<URL> {
public static final UrlJavaType INSTANCE = new UrlJavaType();
public UrlJavaType() {
super( URL.class );
}
@Override
public boolean isInstance(Object value) {
return value instanceof URL;
}
@Override
public JdbcType getRecommendedJdbcType(JdbcTypeIndicators context) {
return context.getJdbcType( SqlTypes.VARCHAR );
}
@Override
public boolean useObjectEqualsHashCode() {
return true;
}
public String toString(URL value) {
return value.toExternalForm();
}
public URL fromString(CharSequence string) {
try {
return new URL( string.toString() );
}
catch ( MalformedURLException e ) {
throw new CoercionException( "Unable to convert string [" + string + "] to URL : " + e );
}
}
@SuppressWarnings("unchecked")
public <X> X unwrap(URL value, Class<X> type, WrapperOptions options) {
if ( value == null ) {
return null;
}
if ( URL.class.isAssignableFrom( type ) ) {
return (X) value;
}
if ( String.class.isAssignableFrom( type ) ) {
return (X) toString( value );
}
throw unknownUnwrap( type );
}
public <X> URL wrap(X value, WrapperOptions options) {
if ( value == null ) {
return null;
}
if (value instanceof URL url) {
return url;
}
if (value instanceof CharSequence charSequence) {
return fromString( charSequence );
}
throw unknownWrap( value.getClass() );
}
}
|
UrlJavaType
|
java
|
apache__maven
|
its/core-it-suite/src/test/resources/mng-4189/src/main/java/org/apache/maven/its/mng4189/App.java
|
{
"start": 1741,
"end": 1937
}
|
class ____ {
public void testDependency() {
Calculator calculator = new Calculator();
int total = calculator.add(1, 2);
System.out.println("Total : " + total);
}
}
|
App
|
java
|
FasterXML__jackson-core
|
src/main/java/tools/jackson/core/base/BinaryTSFactory.java
|
{
"start": 363,
"end": 7812
}
|
class ____
extends DecorableTSFactory
implements java.io.Serializable
{
private static final long serialVersionUID = 3L;
/*
/**********************************************************************
/* Construction
/**********************************************************************
*/
protected BinaryTSFactory(StreamReadConstraints src,
StreamWriteConstraints swc, ErrorReportConfiguration erc,
int formatPF, int formatGF) {
super(src, swc, erc, formatPF, formatGF);
}
/**
* Constructor used by builders for instantiation.
*
* @param baseBuilder Builder with configurations to use
*
* @since 3.0
*/
protected BinaryTSFactory(DecorableTSFBuilder<?,?> baseBuilder)
{
super(baseBuilder);
}
// Copy constructor.
protected BinaryTSFactory(BinaryTSFactory src) {
super(src);
}
/*
/**********************************************************************
/* Default introspection
/**********************************************************************
*/
@Override
public boolean canHandleBinaryNatively() {
// binary formats tend to support native inclusion:
return true;
}
/*
/**********************************************************************
/* Factory methods: parsers
/**********************************************************************
*/
@Override
public JsonParser createParser(ObjectReadContext readCtxt,
File f) throws JacksonException
{
final InputStream in = _fileInputStream(f);
// true, since we create InputStream from File
final IOContext ioCtxt = _createContext(_createContentReference(f), true);
return _createParser(readCtxt, ioCtxt,
_decorate(ioCtxt, in));
}
@Override
public JsonParser createParser(ObjectReadContext readCtxt,
Path p) throws JacksonException
{
// true, since we create InputStream from Path
IOContext ioCtxt = _createContext(_createContentReference(p), true);
return _createParser(readCtxt, ioCtxt,
_decorate(ioCtxt, _pathInputStream(p)));
}
@Override
public JsonParser createParser(ObjectReadContext readCtxt, InputStream in) throws JacksonException {
IOContext ioCtxt = _createContext(_createContentReference(in), false);
return _createParser(readCtxt, ioCtxt, _decorate(ioCtxt, in));
}
@Override
public JsonParser createParser(ObjectReadContext readCtxt, Reader r) throws JacksonException {
return _nonByteSource();
}
@Override
public JsonParser createParser(ObjectReadContext readCtxt,
byte[] data, int offset, int len) throws JacksonException
{
IOContext ioCtxt = _createContext(_createContentReference(data, offset, len),
true, null);
if (_inputDecorator != null) {
InputStream in = _inputDecorator.decorate(ioCtxt, data, offset, len);
if (in != null) {
return _createParser(readCtxt, ioCtxt, in);
}
}
return _createParser(readCtxt, ioCtxt, data, offset, len);
}
@Override
public JsonParser createParser(ObjectReadContext readCtxt,
String content) throws JacksonException {
return _nonByteSource();
}
@Override
public JsonParser createParser(ObjectReadContext readCtxt,
char[] content, int offset, int len) throws JacksonException {
return _nonByteSource();
}
@Override
public JsonParser createParser(ObjectReadContext readCtxt,
DataInput in) throws JacksonException {
IOContext ioCtxt = _createContext(_createContentReference(in), false);
return _createParser(readCtxt, ioCtxt, _decorate(ioCtxt, in));
}
protected abstract JsonParser _createParser(ObjectReadContext readCtxt,
IOContext ioCtxt, InputStream in) throws JacksonException;
protected abstract JsonParser _createParser(ObjectReadContext readCtxt,
IOContext ioCtxt, byte[] data, int offset, int len) throws JacksonException;
protected abstract JsonParser _createParser(ObjectReadContext readCtxt,
IOContext ioCtxt, DataInput input) throws JacksonException;
/*
/**********************************************************************
/* Factory methods: generators
/**********************************************************************
*/
@Override
public JsonGenerator createGenerator(ObjectWriteContext writeCtxt,
OutputStream out, JsonEncoding enc)
throws JacksonException
{
// false -> we won't manage the stream unless explicitly directed to
IOContext ioCtxt = _createContext(_createContentReference(out), false, enc);
return _decorate(
_createGenerator(writeCtxt, ioCtxt, _decorate(ioCtxt, out))
);
}
@Override
public JsonGenerator createGenerator(ObjectWriteContext writeCtxt,
Writer w) throws JacksonException
{
return _nonByteTarget();
}
@Override
public JsonGenerator createGenerator(ObjectWriteContext writeCtxt,
File f, JsonEncoding enc) throws JacksonException
{
final OutputStream out = _fileOutputStream(f);
// true -> yes, we have to manage the stream since we created it
final IOContext ioCtxt = _createContext(_createContentReference(out), true, enc);
return _decorate(
_createGenerator(writeCtxt, ioCtxt, _decorate(ioCtxt, out))
);
}
@Override
public JsonGenerator createGenerator(ObjectWriteContext writeCtxt,
Path p, JsonEncoding enc)
throws JacksonException
{
final OutputStream out = _pathOutputStream(p);
final IOContext ioCtxt = _createContext(_createContentReference(p), true, enc);
return _decorate(
_createGenerator(writeCtxt, ioCtxt, _decorate(ioCtxt, out))
);
}
/*
/**********************************************************************
/* Factory methods: context objects
/**********************************************************************
*/
@Override
protected ContentReference _createContentReference(Object contentRef) {
// false -> not textual
return ContentReference.construct(false, contentRef, _errorReportConfiguration);
}
@Override
protected ContentReference _createContentReference(Object contentRef,
int offset, int length)
{
// false -> not textual
return ContentReference.construct(false, contentRef, offset, length,
_errorReportConfiguration);
}
/*
/**********************************************************************
/* Factory methods: abstract, for sub-classes to implement
/**********************************************************************
*/
/**
* Overridable factory method that actually instantiates generator for
* given {@link OutputStream} and context object, using UTF-8 encoding.
*<p>
* This method is specifically designed to remain
* compatible between minor versions so that sub-classes can count
* on it being called as expected. That is, it is part of official
*
|
BinaryTSFactory
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/main/java/io/vertx/core/eventbus/impl/MessageConsumerImpl.java
|
{
"start": 830,
"end": 5949
}
|
class ____<T> extends HandlerRegistration<T> implements MessageConsumer<T> {
private static final Logger log = LoggerFactory.getLogger(MessageConsumerImpl.class);
private final boolean localOnly;
private Handler<Message<T>> handler;
private Handler<Void> endHandler;
private Handler<Message<T>> discardHandler;
private final int maxBufferedMessages;
private final InboundMessageQueue<Message<T>> pending;
private Promise<Void> result;
private boolean registered;
private boolean full;
MessageConsumerImpl(ContextInternal context, EventBusImpl eventBus, String address, boolean localOnly, int maxBufferedMessages) {
super(context, eventBus, address, false);
this.localOnly = localOnly;
this.result = context.promise();
this.maxBufferedMessages = maxBufferedMessages;
this.pending = new InboundMessageQueue<>(context.executor(), context.executor(), maxBufferedMessages, maxBufferedMessages) {
@Override
protected void handleResume() {
full = false;
}
@Override
protected void handlePause() {
full = true;
}
@Override
protected void handleMessage(Message<T> msg) {
Handler<Message<T>> handler;
synchronized (MessageConsumerImpl.this) {
handler = MessageConsumerImpl.this.handler;
}
if (handler != null) {
dispatchMessage(handler, (MessageImpl<?, T>) msg, context.duplicate());
} else {
handleDiscard(msg, false);
}
}
@Override
protected void handleDispose(Message<T> msg) {
handleDiscard(msg, false);
}
};
}
@Override
public synchronized Future<Void> completion() {
return result.future();
}
@Override
public synchronized Future<Void> unregister() {
handler = null;
if (endHandler != null) {
endHandler.handle(null);
}
pending.close();
Future<Void> fut = super.unregister();
if (registered) {
registered = false;
Promise<Void> res = result; // Alias reference because result can become null when the onComplete callback executes
fut.onComplete(ar -> res.tryFail("Consumer unregistered before registration completed"));
result = context.promise();
}
return fut;
}
private void handleDiscard(Message<T> message, boolean isFull) {
if (discardHandler != null) {
discardHandler.handle(message);
} else if (isFull) {
if (log.isWarnEnabled()) {
log.warn("Discarding message as more than " + maxBufferedMessages + " buffered in paused consumer. address: " + address);
}
} else {
if (log.isWarnEnabled()) {
log.warn("Discarding message since the consumer is not registered. address: " + address);
}
}
// Cleanup message
discardMessage(message);
}
protected void doReceive(Message<T> message) {
if (full) {
handleDiscard(message, true);
} else {
pending.write(message);
}
}
@Override
protected void dispatchMessage(Message<T> msg, ContextInternal context, Handler<Message<T>> handler) {
if (handler == null) {
throw new NullPointerException();
}
context.dispatch(msg, handler);
}
/*
* Internal API for testing purposes, handle dropped messages instead of logging them.
*/
public synchronized void discardHandler(Handler<Message<T>> handler) {
this.discardHandler = handler;
}
@Override
public synchronized MessageConsumer<T> handler(Handler<Message<T>> h) {
if (h != null) {
synchronized (this) {
handler = h;
if (!registered) {
registered = true;
Promise<Void> p = result;
Promise<Void> registration = context.promise();
register(true, localOnly, registration);
registration.future().onComplete(ar -> {
if (ar.succeeded()) {
p.tryComplete();
} else {
p.tryFail(ar.cause());
}
});
}
}
} else {
unregister();
}
return this;
}
@Override
public ReadStream<T> bodyStream() {
return new BodyReadStream<>(this);
}
@Override
public synchronized MessageConsumer<T> pause() {
pending.pause();
return this;
}
@Override
public MessageConsumer<T> resume() {
return fetch(Long.MAX_VALUE);
}
@Override
public synchronized MessageConsumer<T> fetch(long amount) {
pending.fetch(amount);
return this;
}
@Override
public synchronized MessageConsumer<T> endHandler(Handler<Void> endHandler) {
if (endHandler != null) {
// We should use the HandlerHolder context to properly do this (needs small refactoring)
Context endCtx = context.owner().getOrCreateContext();
this.endHandler = v1 -> endCtx.runOnContext(v2 -> endHandler.handle(null));
} else {
this.endHandler = null;
}
return this;
}
@Override
public synchronized MessageConsumer<T> exceptionHandler(Handler<Throwable> handler) {
return this;
}
public synchronized Handler<Message<T>> getHandler() {
return handler;
}
}
|
MessageConsumerImpl
|
java
|
apache__flink
|
flink-python/src/main/java/org/apache/flink/table/runtime/arrow/sources/ArrowSourceFunction.java
|
{
"start": 3060,
"end": 9526
}
|
class ____ extends RichParallelSourceFunction<RowData>
implements ResultTypeQueryable<RowData>, CheckpointedFunction {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(ArrowSourceFunction.class);
static {
ArrowUtils.checkArrowUsable();
}
/** The type of the records produced by this source. */
private final DataType dataType;
/**
* The array of byte array of the source data. Each element is an array representing an arrow
* batch.
*/
private final byte[][] arrowData;
/** Allocator which is used for byte buffer allocation. */
private transient BufferAllocator allocator;
/** Container that holds a set of vectors for the source data to emit. */
private transient VectorSchemaRoot root;
private transient volatile boolean running;
/**
* The indexes of the collection of source data to emit. Each element is a tuple of the index of
* the arrow batch and the staring index inside the arrow batch.
*/
private transient Deque<Tuple2<Integer, Integer>> indexesToEmit;
/** The indexes of the source data which have not been emitted. */
private transient ListState<Tuple2<Integer, Integer>> checkpointedState;
ArrowSourceFunction(DataType dataType, byte[][] arrowData) {
this.dataType = Preconditions.checkNotNull(dataType);
this.arrowData = Preconditions.checkNotNull(arrowData);
}
@Override
public void open(OpenContext openContext) throws Exception {
allocator =
ArrowUtils.getRootAllocator()
.newChildAllocator("ArrowSourceFunction", 0, Long.MAX_VALUE);
root =
VectorSchemaRoot.create(
ArrowUtils.toArrowSchema((RowType) dataType.getLogicalType()), allocator);
running = true;
}
@Override
public void close() throws Exception {
try {
super.close();
} finally {
if (root != null) {
root.close();
root = null;
}
if (allocator != null) {
allocator.close();
allocator = null;
}
}
}
@Override
public void initializeState(FunctionInitializationContext context) throws Exception {
Preconditions.checkState(
this.checkpointedState == null,
"The " + getClass().getSimpleName() + " has already been initialized.");
this.checkpointedState =
context.getOperatorStateStore()
.getListState(
new ListStateDescriptor<>(
"arrow-source-state",
new TupleSerializer<>(
(Class<Tuple2<Integer, Integer>>)
(Class<?>) Tuple2.class,
new TypeSerializer[] {
IntSerializer.INSTANCE, IntSerializer.INSTANCE
})));
this.indexesToEmit = new ArrayDeque<>();
if (context.isRestored()) {
// upon restoring
for (Tuple2<Integer, Integer> v : this.checkpointedState.get()) {
this.indexesToEmit.add(v);
}
LOG.info(
"Subtask {} restored state: {}.",
getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(),
indexesToEmit);
} else {
// the first time the job is executed
final int stepSize = getRuntimeContext().getTaskInfo().getNumberOfParallelSubtasks();
final int taskIdx = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask();
for (int i = taskIdx; i < arrowData.length; i += stepSize) {
this.indexesToEmit.add(Tuple2.of(i, 0));
}
LOG.info(
"Subtask {} has no restore state, initialized with {}.",
taskIdx,
indexesToEmit);
}
}
@Override
public void snapshotState(FunctionSnapshotContext context) throws Exception {
Preconditions.checkState(
this.checkpointedState != null,
"The " + getClass().getSimpleName() + " state has not been properly initialized.");
this.checkpointedState.update(new ArrayList<>(indexesToEmit));
}
@Override
public void run(SourceContext<RowData> ctx) throws Exception {
VectorLoader vectorLoader = new VectorLoader(root);
while (running && !indexesToEmit.isEmpty()) {
Tuple2<Integer, Integer> indexToEmit = indexesToEmit.peek();
ArrowRecordBatch arrowRecordBatch = loadBatch(indexToEmit.f0);
vectorLoader.load(arrowRecordBatch);
arrowRecordBatch.close();
ArrowReader arrowReader = createArrowReader(root);
int rowCount = root.getRowCount();
int nextRowId = indexToEmit.f1;
while (nextRowId < rowCount) {
RowData element = arrowReader.read(nextRowId);
synchronized (ctx.getCheckpointLock()) {
ctx.collect(element);
indexToEmit.setField(++nextRowId, 1);
}
}
synchronized (ctx.getCheckpointLock()) {
indexesToEmit.pop();
}
}
}
@Override
public void cancel() {
running = false;
}
@Override
public TypeInformation<RowData> getProducedType() {
return (TypeInformation<RowData>)
TypeInfoDataTypeConverter.fromDataTypeToTypeInfo(dataType);
}
private ArrowReader createArrowReader(VectorSchemaRoot root) {
return ArrowUtils.createArrowReader(root, (RowType) dataType.getLogicalType());
}
/** Load the specified batch of data to process. */
private ArrowRecordBatch loadBatch(int nextIndexOfArrowDataToProcess) throws IOException {
ByteArrayInputStream bais =
new ByteArrayInputStream(arrowData[nextIndexOfArrowDataToProcess]);
return MessageSerializer.deserializeRecordBatch(
new ReadChannel(Channels.newChannel(bais)), allocator);
}
}
|
ArrowSourceFunction
|
java
|
apache__camel
|
components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/spring/tx/error/JMXTXUseOriginalBodyWithDLCErrorHandlerIT.java
|
{
"start": 1470,
"end": 3726
}
|
class ____ extends JMXTXUseOriginalBodyIT {
@EndpointInject("mock:end")
protected MockEndpoint endpoint;
@EndpointInject("mock:error")
protected MockEndpoint error;
@EndpointInject("mock:dead")
protected MockEndpoint dead;
@EndpointInject("mock:checkpoint1")
protected MockEndpoint checkpoint1;
@EndpointInject("mock:checkpoint2")
protected MockEndpoint checkpoint2;
@Produce("activemq:JMXTXUseOriginalBodyWithDLCErrorHandlerIT.start")
protected ProducerTemplate start;
@Produce("activemq:JMXTXUseOriginalBodyWithDLCErrorHandlerIT.broken")
protected ProducerTemplate broken;
@Produce("activemq:JMXTXUseOriginalBodyWithDLCErrorHandlerIT.ok")
protected ProducerTemplate ok;
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext(
"/org/apache/camel/component/jms/integration/spring/tx/error/JMXTXUseOriginalBodyWithDLCErrorHandlerIT.xml");
}
@Override
@Test
public void testWithConstant() throws InterruptedException {
endpoint.expectedMessageCount(0);
dead.expectedMessageCount(0);
error.expectedBodiesReceived("foo");
checkpoint1.expectedBodiesReceived("foo");
checkpoint2.expectedBodiesReceived("oh no");
start.sendBody("foo");
MockEndpoint.assertIsSatisfied(context);
}
@Override
@Test
public void testWithBean() throws InterruptedException {
endpoint.expectedMessageCount(0);
dead.expectedMessageCount(0);
error.expectedBodiesReceived("foo");
checkpoint1.expectedBodiesReceived("foo");
checkpoint2.expectedBodiesReceived("oh no");
broken.sendBody("foo");
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testOk() throws InterruptedException {
endpoint.expectedMessageCount(1);
dead.expectedMessageCount(0);
error.expectedMessageCount(0);
checkpoint1.expectedBodiesReceived("foo");
checkpoint2.expectedBodiesReceived("oh no");
ok.sendBody("foo");
MockEndpoint.assertIsSatisfied(context);
}
public static
|
JMXTXUseOriginalBodyWithDLCErrorHandlerIT
|
java
|
micronaut-projects__micronaut-core
|
core/src/main/java/io/micronaut/core/util/ArrayUtils.java
|
{
"start": 10142,
"end": 10917
}
|
class ____<T> implements Iterator<T>, Iterable<T> {
private final T[] array;
private int index;
private ReverseArrayIterator(T[] a) {
array = a;
index = a.length > 0 ? a.length - 1 : -1;
}
@Override
public boolean hasNext() {
return index > -1;
}
@Override
public T next() {
if (index <= -1) {
throw new NoSuchElementException();
}
return array[index--];
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
@Override public Iterator<T> iterator() {
return new ReverseArrayIterator<>(array);
}
}
}
|
ReverseArrayIterator
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/LocalDateMappingTests.java
|
{
"start": 976,
"end": 1980
}
|
class ____ {
@Test
public void verifyMappings(SessionFactoryScope scope) {
final MappingMetamodelImplementor mappingMetamodel = scope.getSessionFactory()
.getRuntimeMetamodels()
.getMappingMetamodel();
final EntityPersister entityDescriptor = mappingMetamodel.findEntityDescriptor(EntityWithLocalDate.class);
final BasicAttributeMapping duration = (BasicAttributeMapping) entityDescriptor.findAttributeMapping("localDate");
final JdbcMapping jdbcMapping = duration.getJdbcMapping();
assertThat(jdbcMapping.getJavaTypeDescriptor().getJavaTypeClass(), equalTo(LocalDate.class));
assertThat( jdbcMapping.getJdbcType().getJdbcTypeCode(), equalTo( Types.DATE));
scope.inTransaction(
(session) -> {
session.persist(new EntityWithLocalDate(1, LocalDate.now()));
}
);
scope.inTransaction(
(session) -> session.find(EntityWithLocalDate.class, 1)
);
}
@Entity(name = "EntityWithLocalDate")
@Table(name = "EntityWithLocalDate")
public static
|
LocalDateMappingTests
|
java
|
apache__camel
|
core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/BootstrapFactoryFinder.java
|
{
"start": 978,
"end": 1400
}
|
class ____ extends DefaultFactoryFinder implements BootstrapCloseable {
public BootstrapFactoryFinder(ClassResolver classResolver, String resourcePath) {
super(classResolver, resourcePath);
}
@Override
public void close() {
clear();
classResolver = null;
classMap = null;
classesNotFound = null;
classesNotFoundExceptions = null;
}
}
|
BootstrapFactoryFinder
|
java
|
spring-projects__spring-boot
|
module/spring-boot-security/src/main/java/org/springframework/boot/security/autoconfigure/web/servlet/ServletWebSecurityAutoConfiguration.java
|
{
"start": 3559,
"end": 4611
}
|
class ____ {
@Bean
@Order(SecurityFilterProperties.BASIC_AUTH_ORDER)
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) {
http.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated());
http.formLogin(withDefaults());
http.httpBasic(withDefaults());
return http.build();
}
}
/**
* Adds the {@link EnableWebSecurity @EnableWebSecurity} annotation if Spring Security
* is on the classpath. This will make sure that the annotation is present with
* default security auto-configuration and also if the user adds custom security and
* forgets to add the annotation. If {@link EnableWebSecurity @EnableWebSecurity} has
* already been added or if a bean with name
* {@value BeanIds#SPRING_SECURITY_FILTER_CHAIN} has been configured by the user, this
* will back-off.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(name = BeanIds.SPRING_SECURITY_FILTER_CHAIN)
@ConditionalOnClass(EnableWebSecurity.class)
@EnableWebSecurity
static
|
SecurityFilterChainConfiguration
|
java
|
apache__maven
|
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng2739RequiredRepositoryElementsTest.java
|
{
"start": 1258,
"end": 3356
}
|
class ____ extends AbstractMavenIntegrationTestCase {
@Test
public void testitMNG2739RepositoryId() throws Exception {
File testDir = extractResources("/mng-2739/repo-id");
Verifier verifier;
verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
try {
verifier.addCliArgument("validate");
verifier.execute();
fail("POM should NOT validate: repository <id/> element is missing in: " + new File(testDir, "pom.xml"));
} catch (VerificationException e) {
// expected
}
List<String> listing = verifier.loadFile(new File(testDir, "log.txt"), false);
boolean foundNpe = false;
for (String line : listing) {
if (line.contains("NullPointerException")) {
foundNpe = true;
break;
}
}
assertFalse(foundNpe, "Missing repository-id should not result in a NullPointerException.");
}
@Test
public void testitMNG2739RepositoryUrl() throws Exception {
// The testdir is computed from the location of this
// file.
File testDir = extractResources("/mng-2739/repo-url");
Verifier verifier;
verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
try {
verifier.addCliArgument("validate");
verifier.execute();
fail("POM should NOT validate: repository <url/> element is missing in: " + new File(testDir, "pom.xml"));
} catch (VerificationException e) {
// expected
}
List<String> listing = verifier.loadFile(new File(testDir, "log.txt"), false);
boolean foundNpe = false;
for (String line : listing) {
if (line.contains("NullPointerException")) {
foundNpe = true;
break;
}
}
assertFalse(foundNpe, "Missing repository-url should not result in a NullPointerException.");
}
}
|
MavenITmng2739RequiredRepositoryElementsTest
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/RequiredModifiersCheckerTest.java
|
{
"start": 7725,
"end": 7990
}
|
class ____ {}
""")
.addOutputLines(
"test/RequiredModifiersTestCase.java",
"""
package test;
import test.AbstractRequired;
@AbstractRequired
abstract
|
RequiredModifiersTestCase
|
java
|
quarkusio__quarkus
|
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/PostResource.java
|
{
"start": 150,
"end": 405
}
|
class ____ {
@POST
public String modify(String data) {
return "Hello: " + data;
}
@PreDestroy
void destroy() {
throw new IllegalStateException("Something bad happened but dev mode should work fine");
}
}
|
PostResource
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/resources/StoragePolicyParam.java
|
{
"start": 886,
"end": 1450
}
|
class ____ extends StringParam {
/** Parameter name. */
public static final String NAME = "storagepolicy";
/** Default parameter value. */
public static final String DEFAULT = "";
private static final Domain DOMAIN = new Domain(NAME, null);
/**
* Constructor.
*
* @param str
* a string representation of the parameter value.
*/
public StoragePolicyParam(final String str) {
super(DOMAIN, str == null || str.equals(DEFAULT) ? null : str);
}
@Override
public String getName() {
return NAME;
}
}
|
StoragePolicyParam
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/consumer/IteratorWrappingTestSingleInputGate.java
|
{
"start": 1977,
"end": 5402
}
|
class ____<T extends IOReadableWritable>
extends TestSingleInputGate {
private final TestInputChannel inputChannel = new TestInputChannel(inputGate, 0);
private final int bufferSize;
private MutableObjectIterator<T> inputIterator;
private DataOutputSerializer serializer;
private final T reuse;
public IteratorWrappingTestSingleInputGate(
int bufferSize, int gateIndex, MutableObjectIterator<T> iterator, Class<T> recordType)
throws IOException, InterruptedException {
super(1, gateIndex, false);
this.bufferSize = bufferSize;
this.reuse = InstantiationUtil.instantiate(recordType);
wrapIterator(iterator);
}
private IteratorWrappingTestSingleInputGate<T> wrapIterator(MutableObjectIterator<T> iterator)
throws IOException, InterruptedException {
inputIterator = iterator;
serializer = new DataOutputSerializer(128);
// The input iterator can produce an infinite stream. That's why we have to serialize each
// record on demand and cannot do it upfront.
final BufferAndAvailabilityProvider answer =
new BufferAndAvailabilityProvider() {
private boolean hasData = inputIterator.next(reuse) != null;
@Override
public Optional<BufferAndAvailability> getBufferAvailability()
throws IOException {
if (hasData) {
ByteBuffer serializedRecord =
RecordWriter.serializeRecord(serializer, reuse);
BufferBuilder bufferBuilder = createBufferBuilder(bufferSize);
BufferConsumer bufferConsumer = bufferBuilder.createBufferConsumer();
bufferBuilder.appendAndCommit(serializedRecord);
hasData = inputIterator.next(reuse) != null;
// Call getCurrentBuffer to ensure size is set
final Buffer.DataType nextDataType =
hasData
? Buffer.DataType.DATA_BUFFER
: Buffer.DataType.EVENT_BUFFER;
return Optional.of(
new BufferAndAvailability(
bufferConsumer.build(), nextDataType, 0, 0));
} else {
inputChannel.setReleased();
return Optional.of(
new BufferAndAvailability(
EventSerializer.toBuffer(
EndOfPartitionEvent.INSTANCE, false),
Buffer.DataType.NONE,
0,
0));
}
}
};
inputChannel.addBufferAndAvailability(answer);
inputGate.setInputChannels(inputChannel);
return this;
}
public IteratorWrappingTestSingleInputGate<T> notifyNonEmpty() {
inputGate.notifyChannelNonEmpty(inputChannel);
return this;
}
}
|
IteratorWrappingTestSingleInputGate
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/response/SETATTR3Response.java
|
{
"start": 978,
"end": 1669
}
|
class ____ extends NFS3Response {
private final WccData wccData;
public SETATTR3Response(int status) {
this(status, new WccData(null, null));
}
public SETATTR3Response(int status, WccData wccData) {
super(status);
this.wccData = wccData;
}
public WccData getWccData() {
return wccData;
}
public static SETATTR3Response deserialize(XDR xdr) {
int status = xdr.readInt();
WccData wccData = WccData.deserialize(xdr);
return new SETATTR3Response(status, wccData);
}
@Override
public XDR serialize(XDR out, int xid, Verifier verifier) {
super.serialize(out, xid, verifier);
wccData.serialize(out);
return out;
}
}
|
SETATTR3Response
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/decorators/interceptor/InterceptorAndDecoratorTest.java
|
{
"start": 990,
"end": 1711
}
|
class ____ {
@RegisterExtension
public ArcTestContainer container = new ArcTestContainer(Converter.class, ToUpperCaseConverter.class,
TrimConverterDecorator.class, LoggingInterceptor.class, Logging.class);
@Test
public void testInterceptionAndDecoration() {
LoggingInterceptor.LOG.set(null);
ToUpperCaseConverter converter = Arc.container().instance(ToUpperCaseConverter.class).get();
assertEquals("HOLA!", converter.convert(" holA!"));
assertEquals("HOLA!", LoggingInterceptor.LOG.get());
assertEquals(" HOLA!", converter.convertNoDelegation(" holA!"));
assertEquals(" HOLA!", LoggingInterceptor.LOG.get());
}
|
InterceptorAndDecoratorTest
|
java
|
elastic__elasticsearch
|
x-pack/qa/runtime-fields/core-with-search/src/yamlRestTest/java/org/elasticsearch/xpack/runtimefields/test/search/CoreTestsWithSearchRuntimeFieldsIT.java
|
{
"start": 2146,
"end": 11835
}
|
class ____ extends CoreTestTranslater {
@Override
protected Map<String, Object> dynamicTemplateFor() {
return dynamicTemplateToDisableRuntimeCompatibleFields();
}
@Override
protected Suite suite(ClientYamlTestCandidate candidate) {
return new Suite(candidate) {
private Map<String, Map<String, Object>> runtimeMappingsAfterSetup;
private Map<String, Set<String>> mappedFieldsAfterSetup;
private Map<String, Map<String, Object>> runtimeMappings;
private Map<String, Set<String>> mappedFields;
@Override
public boolean modifySections(List<ExecutableSection> executables) {
if (runtimeMappingsAfterSetup == null) {
// We're modifying the setup section
runtimeMappings = new HashMap<>();
mappedFields = new HashMap<>();
if (false == super.modifySections(executables)) {
return false;
}
runtimeMappingsAfterSetup = unmodifiableMap(runtimeMappings);
runtimeMappings = null;
mappedFieldsAfterSetup = unmodifiableMap(mappedFields);
mappedFields = null;
return true;
}
runtimeMappings = new HashMap<>(runtimeMappingsAfterSetup);
mappedFields = new HashMap<>(mappedFieldsAfterSetup);
return super.modifySections(executables);
}
@Override
protected boolean modifyMappingProperties(String index, Map<String, Object> properties, Map<String, Object> runtimeFields) {
if (false == runtimeifyMappingProperties(properties, runtimeFields)) {
return false;
}
mappedFields.put(index, properties.keySet());
runtimeMappings.put(index, runtimeFields);
return true;
}
@Override
protected boolean modifySearch(ApiCallSection search) {
if (search.getBodies().isEmpty()) {
search.addBody(new HashMap<>());
}
boolean changed = false;
for (Map<String, Object> body : search.getBodies()) {
Map<?, ?> runtimeMapping = runtimeMappings(search.getParams().get("index"));
if (runtimeMapping != null) {
changed = true;
body.compute("runtime_mappings", (k, curr) -> {
if (curr == null) {
return runtimeMapping;
} else {
Map<Object, Object> mergedMappings = new HashMap<>((Map<?, ?>) curr);
mergedMappings.putAll(runtimeMapping);
return mergedMappings;
}
});
}
}
return changed;
}
private Map<?, ?> runtimeMappings(String index) {
if (index == null) {
return mergeMappings(new String[] { "*" });
}
String[] patterns = Arrays.stream(index.split(",")).map(m -> m.equals("_all") ? "*" : m).toArray(String[]::new);
if (patterns.length == 1 && Regex.isSimpleMatchPattern(patterns[0])) {
return runtimeMappings.get(patterns[0]);
}
return mergeMappings(patterns);
}
private Map<?, ?> mergeMappings(String[] patterns) {
Map<String, Object> merged = new HashMap<>();
for (Map.Entry<String, Map<String, Object>> indexEntry : runtimeMappings.entrySet()) {
if (false == Regex.simpleMatch(patterns, indexEntry.getKey())) {
continue;
}
for (Map.Entry<String, Object> field : indexEntry.getValue().entrySet()) {
@SuppressWarnings("unchecked")
Map<String, Object> mergedConfig = (Map<String, Object>) merged.get(field.getKey());
if (mergedConfig == null) {
merged.put(field.getKey(), field.getValue());
} else if (false == mergedConfig.equals(field.getValue())) {
// The two indices have different runtime mappings for a field so we have to give up on running the test.
return null;
}
}
}
for (Map.Entry<String, Set<String>> indexEntry : mappedFields.entrySet()) {
if (false == Regex.simpleMatch(patterns, indexEntry.getKey())) {
continue;
}
for (String mappedField : indexEntry.getValue()) {
if (merged.containsKey(mappedField)) {
// We have a runtime mappings for a field *and* regular mapping. We can't make this test work so skip it.
return null;
}
}
}
return merged;
}
@Override
protected boolean handleIndex(IndexRequest index) {
/*
* Ok! Let's reverse engineer dynamic mapping. Sort of. We're
* really just looking to figure out which of the runtime fields
* is "close enough" to what dynamic mapping would do.
*/
if (index.getPipeline() != null) {
// We can't attempt local dynamic mappings with pipelines
return false;
}
Map<String, Object> map = XContentHelper.convertToMap(index.source(), false, index.getContentType()).v2();
Map<String, Object> indexRuntimeMappings = runtimeMappings.computeIfAbsent(index.index(), i -> new HashMap<>());
Set<String> indexMappedfields = mappedFields.computeIfAbsent(index.index(), i -> Set.of());
for (Map.Entry<String, Object> e : map.entrySet()) {
String name = e.getKey();
if (indexRuntimeMappings.containsKey(name) || indexMappedfields.contains(name)) {
continue;
}
Object value = e.getValue();
if (value == null) {
continue;
}
if (value instanceof Boolean) {
indexRuntimeMappings.put(name, runtimeFieldLoadingFromSource("boolean"));
continue;
}
if (value instanceof Long || value instanceof Integer) {
indexRuntimeMappings.put(name, runtimeFieldLoadingFromSource("long"));
continue;
}
if (value instanceof Double) {
indexRuntimeMappings.put(name, runtimeFieldLoadingFromSource("double"));
continue;
}
if (false == value instanceof String) {
continue;
}
try {
Long.parseLong(value.toString());
indexRuntimeMappings.put(name, runtimeFieldLoadingFromSource("long"));
continue;
} catch (IllegalArgumentException iae) {
// Try the next one
}
try {
Double.parseDouble(value.toString());
indexRuntimeMappings.put(name, runtimeFieldLoadingFromSource("double"));
continue;
} catch (IllegalArgumentException iae) {
// Try the next one
}
try {
DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.parse(value.toString());
indexRuntimeMappings.put(name, runtimeFieldLoadingFromSource("date"));
continue;
} catch (IllegalArgumentException iae) {
// Try the next one
}
// Strings are funny, the regular dynamic mapping puts them in "name.keyword" so we follow along.
Map<String, Object> keyword = new HashMap<>(runtimeFieldLoadingFromSource("keyword"));
keyword.put("script", "emit(params._source['" + name + "']);");
indexRuntimeMappings.put(name + ".keyword", keyword);
}
return true;
}
};
}
}
}
|
SearchRequestRuntimeFieldTranslater
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFlatMapSingleTest.java
|
{
"start": 1261,
"end": 15135
}
|
class ____ extends RxJavaTest {
@Test
public void normal() {
Observable.range(1, 10)
.flatMapSingle(new Function<Integer, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(Integer v) throws Exception {
return Single.just(v);
}
})
.test()
.assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
@Test
public void normalDelayError() {
Observable.range(1, 10)
.flatMapSingle(new Function<Integer, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(Integer v) throws Exception {
return Single.just(v);
}
}, true)
.test()
.assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
@Test
public void normalAsync() {
TestObserverEx<Integer> to = Observable.range(1, 10)
.flatMapSingle(new Function<Integer, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(Integer v) throws Exception {
return Single.just(v).subscribeOn(Schedulers.computation());
}
})
.to(TestHelper.<Integer>testConsumer())
.awaitDone(5, TimeUnit.SECONDS)
.assertSubscribed()
.assertNoErrors()
.assertComplete();
TestHelper.assertValueSet(to, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
@Test
public void mapperThrowsObservable() {
PublishSubject<Integer> ps = PublishSubject.create();
TestObserver<Integer> to = ps
.flatMapSingle(new Function<Integer, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(Integer v) throws Exception {
throw new TestException();
}
})
.test();
assertTrue(ps.hasObservers());
ps.onNext(1);
to.assertFailure(TestException.class);
assertFalse(ps.hasObservers());
}
@Test
public void mapperReturnsNullObservable() {
PublishSubject<Integer> ps = PublishSubject.create();
TestObserver<Integer> to = ps
.flatMapSingle(new Function<Integer, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(Integer v) throws Exception {
return null;
}
})
.test();
assertTrue(ps.hasObservers());
ps.onNext(1);
to.assertFailure(NullPointerException.class);
assertFalse(ps.hasObservers());
}
@Test
public void normalDelayErrorAll() {
TestObserverEx<Integer> to = Observable.range(1, 10).concatWith(Observable.<Integer>error(new TestException()))
.flatMapSingle(new Function<Integer, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(Integer v) throws Exception {
return Single.error(new TestException());
}
}, true)
.to(TestHelper.<Integer>testConsumer())
.assertFailure(CompositeException.class);
List<Throwable> errors = TestHelper.compositeList(to.errors().get(0));
for (int i = 0; i < 11; i++) {
TestHelper.assertError(errors, i, TestException.class);
}
}
@Test
public void takeAsync() {
TestObserverEx<Integer> to = Observable.range(1, 10)
.flatMapSingle(new Function<Integer, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(Integer v) throws Exception {
return Single.just(v).subscribeOn(Schedulers.computation());
}
})
.take(2)
.to(TestHelper.<Integer>testConsumer())
.awaitDone(5, TimeUnit.SECONDS)
.assertSubscribed()
.assertValueCount(2)
.assertNoErrors()
.assertComplete();
TestHelper.assertValueSet(to, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
@Test
public void take() {
Observable.range(1, 10)
.flatMapSingle(new Function<Integer, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(Integer v) throws Exception {
return Single.just(v);
}
})
.take(2)
.test()
.assertResult(1, 2);
}
@Test
public void middleError() {
Observable.fromArray(new String[]{"1", "a", "2"}).flatMapSingle(new Function<String, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(final String s) throws NumberFormatException {
//return Single.just(Integer.valueOf(s)); //This works
return Single.fromCallable(new Callable<Integer>() {
@Override
public Integer call() throws NumberFormatException {
return Integer.valueOf(s);
}
});
}
})
.test()
.assertFailure(NumberFormatException.class, 1);
}
@Test
public void asyncFlatten() {
Observable.range(1, 1000)
.flatMapSingle(new Function<Integer, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(Integer v) throws Exception {
return Single.just(1).subscribeOn(Schedulers.computation());
}
})
.take(500)
.to(TestHelper.<Integer>testConsumer())
.awaitDone(5, TimeUnit.SECONDS)
.assertSubscribed()
.assertValueCount(500)
.assertNoErrors()
.assertComplete();
}
@Test
public void successError() {
final PublishSubject<Integer> ps = PublishSubject.create();
TestObserver<Integer> to = Observable.range(1, 2)
.flatMapSingle(new Function<Integer, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(Integer v) throws Exception {
if (v == 2) {
return ps.singleOrError();
}
return Single.error(new TestException());
}
}, true)
.test();
ps.onNext(1);
ps.onComplete();
to
.assertFailure(TestException.class, 1);
}
@Test
public void disposed() {
TestHelper.checkDisposed(PublishSubject.<Integer>create().flatMapSingle(new Function<Integer, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(Integer v) throws Exception {
return Single.<Integer>just(1);
}
}));
}
@Test
public void innerSuccessCompletesAfterMain() {
PublishSubject<Integer> ps = PublishSubject.create();
TestObserver<Integer> to = Observable.just(1).flatMapSingle(Functions.justFunction(ps.singleOrError()))
.test();
ps.onNext(2);
ps.onComplete();
to
.assertResult(2);
}
@Test
public void doubleOnSubscribe() {
TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, ObservableSource<Integer>>() {
@Override
public ObservableSource<Integer> apply(Observable<Object> f) throws Exception {
return f.flatMapSingle(Functions.justFunction(Single.just(2)));
}
});
}
@Test
public void badSource() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
new Observable<Integer>() {
@Override
protected void subscribeActual(Observer<? super Integer> observer) {
observer.onSubscribe(Disposable.empty());
observer.onError(new TestException("First"));
observer.onError(new TestException("Second"));
}
}
.flatMapSingle(Functions.justFunction(Single.just(2)))
.to(TestHelper.<Integer>testConsumer())
.assertFailureAndMessage(TestException.class, "First");
TestHelper.assertUndeliverable(errors, 0, TestException.class, "Second");
} finally {
RxJavaPlugins.reset();
}
}
@Test
public void badInnerSource() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
Observable.just(1)
.flatMapSingle(Functions.justFunction(new Single<Integer>() {
@Override
protected void subscribeActual(SingleObserver<? super Integer> observer) {
observer.onSubscribe(Disposable.empty());
observer.onError(new TestException("First"));
observer.onError(new TestException("Second"));
}
}))
.to(TestHelper.<Integer>testConsumer())
.assertFailureAndMessage(TestException.class, "First");
TestHelper.assertUndeliverable(errors, 0, TestException.class, "Second");
} finally {
RxJavaPlugins.reset();
}
}
@Test
public void emissionQueueTrigger() {
final PublishSubject<Integer> ps1 = PublishSubject.create();
final PublishSubject<Integer> ps2 = PublishSubject.create();
TestObserver<Integer> to = new TestObserver<Integer>() {
@Override
public void onNext(Integer t) {
super.onNext(t);
if (t == 1) {
ps2.onNext(2);
ps2.onComplete();
}
}
};
Observable.just(ps1, ps2)
.flatMapSingle(new Function<PublishSubject<Integer>, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(PublishSubject<Integer> v) throws Exception {
return v.singleOrError();
}
})
.subscribe(to);
ps1.onNext(1);
ps1.onComplete();
to.assertResult(1, 2);
}
@Test
public void disposeInner() {
final TestObserver<Object> to = new TestObserver<>();
Observable.just(1).flatMapSingle(new Function<Integer, SingleSource<Object>>() {
@Override
public SingleSource<Object> apply(Integer v) throws Exception {
return new Single<Object>() {
@Override
protected void subscribeActual(SingleObserver<? super Object> observer) {
observer.onSubscribe(Disposable.empty());
assertFalse(((Disposable)observer).isDisposed());
to.dispose();
assertTrue(((Disposable)observer).isDisposed());
}
};
}
})
.subscribe(to);
to
.assertEmpty();
}
@Test
public void undeliverableUponCancel() {
TestHelper.checkUndeliverableUponCancel(new ObservableConverter<Integer, Observable<Integer>>() {
@Override
public Observable<Integer> apply(Observable<Integer> upstream) {
return upstream.flatMapSingle(new Function<Integer, Single<Integer>>() {
@Override
public Single<Integer> apply(Integer v) throws Throwable {
return Single.just(v).hide();
}
});
}
});
}
@Test
public void undeliverableUponCancelDelayError() {
TestHelper.checkUndeliverableUponCancel(new ObservableConverter<Integer, Observable<Integer>>() {
@Override
public Observable<Integer> apply(Observable<Integer> upstream) {
return upstream.flatMapSingle(new Function<Integer, Single<Integer>>() {
@Override
public Single<Integer> apply(Integer v) throws Throwable {
return Single.just(v).hide();
}
}, true);
}
});
}
@Test
public void innerErrorOuterCompleteRace() {
TestException ex = new TestException();
for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
PublishSubject<Integer> ps1 = PublishSubject.create();
SingleSubject<Integer> ps2 = SingleSubject.create();
TestObserver<Integer> to = ps1.flatMapSingle(v -> ps2)
.test();
ps1.onNext(1);
TestHelper.race(
() -> ps1.onComplete(),
() -> ps2.onError(ex)
);
to.assertFailure(TestException.class);
}
}
@Test
public void cancelWhileMapping() throws Throwable {
for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
PublishSubject<Integer> ps1 = PublishSubject.create();
TestObserver<Integer> to = new TestObserver<>();
CountDownLatch cdl = new CountDownLatch(1);
ps1.flatMapSingle(v -> {
TestHelper.raceOther(() -> {
to.dispose();
}, cdl);
return Single.just(1);
})
.subscribe(to);
ps1.onNext(1);
cdl.await();
}
}
@Test
public void onNextDrainCancel() {
SingleSubject<Integer> ss1 = SingleSubject.create();
SingleSubject<Integer> ss2 = SingleSubject.create();
TestObserver<Integer> to = new TestObserver<>();
Observable.just(1, 2)
.flatMapSingle(v -> v == 1 ? ss1 : ss2)
.doOnNext(v -> {
if (v == 1) {
ss2.onSuccess(2);
to.dispose();
}
})
.subscribe(to);
ss1.onSuccess(1);
to.assertValuesOnly(1);
}
}
|
ObservableFlatMapSingleTest
|
java
|
google__guava
|
android/guava-testlib/src/com/google/common/collect/testing/google/MultimapAsMapTester.java
|
{
"start": 2530,
"end": 5892
}
|
class ____<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
public void testAsMapGet() {
for (K key : sampleKeys()) {
List<V> expectedValues = new ArrayList<>();
for (Entry<K, V> entry : getSampleElements()) {
if (entry.getKey().equals(key)) {
expectedValues.add(entry.getValue());
}
}
Collection<V> collection = multimap().asMap().get(key);
if (expectedValues.isEmpty()) {
assertNull(collection);
} else {
assertEqualIgnoringOrder(expectedValues, collection);
}
}
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testAsMapGetNullKeyPresent() {
initMultimapWithNullKey();
assertContentsAnyOrder(multimap().asMap().get(null), getValueForNullKey());
}
@MapFeature.Require(ALLOWS_NULL_KEY_QUERIES)
public void testAsMapGetNullKeyAbsent() {
assertNull(multimap().asMap().get(null));
}
@MapFeature.Require(absent = ALLOWS_NULL_KEY_QUERIES)
public void testAsMapGetNullKeyUnsupported() {
assertThrows(NullPointerException.class, () -> multimap().asMap().get(null));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testAsMapRemove() {
assertContentsInOrder(multimap().asMap().remove(k0()), v0());
assertGet(k0());
assertEquals(getNumElements() - 1, multimap().size());
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require(SUPPORTS_PUT)
public void testAsMapEntrySetReflectsPutSameKey() {
resetContainer(mapEntry(k0(), v0()), mapEntry(k0(), v3()));
Set<Entry<K, Collection<V>>> asMapEntrySet = multimap().asMap().entrySet();
Collection<V> valueCollection = getOnlyElement(asMapEntrySet).getValue();
assertContentsAnyOrder(valueCollection, v0(), v3());
assertTrue(multimap().put(k0(), v4()));
assertContentsAnyOrder(valueCollection, v0(), v3(), v4());
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require(SUPPORTS_PUT)
public void testAsMapEntrySetReflectsPutDifferentKey() {
resetContainer(mapEntry(k0(), v0()), mapEntry(k0(), v3()));
Set<Entry<K, Collection<V>>> asMapEntrySet = multimap().asMap().entrySet();
assertTrue(multimap().put(k1(), v4()));
assertEquals(2, asMapEntrySet.size());
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require({SUPPORTS_PUT, SUPPORTS_REMOVE})
public void testAsMapEntrySetRemovePropagatesToMultimap() {
resetContainer(mapEntry(k0(), v0()), mapEntry(k0(), v3()));
Set<Entry<K, Collection<V>>> asMapEntrySet = multimap().asMap().entrySet();
Entry<K, Collection<V>> asMapEntry0 = getOnlyElement(asMapEntrySet);
assertTrue(multimap().put(k1(), v4()));
assertTrue(asMapEntrySet.remove(asMapEntry0));
assertEquals(1, multimap().size());
assertContentsInOrder(multimap().keySet(), k1());
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
public void testAsMapEntrySetIteratorRemovePropagatesToMultimap() {
resetContainer(mapEntry(k0(), v0()), mapEntry(k0(), v3()));
Set<Entry<K, Collection<V>>> asMapEntrySet = multimap().asMap().entrySet();
Iterator<Entry<K, Collection<V>>> asMapEntryItr = asMapEntrySet.iterator();
asMapEntryItr.next();
asMapEntryItr.remove();
assertTrue(multimap().isEmpty());
}
}
|
MultimapAsMapTester
|
java
|
apache__rocketmq
|
example/src/main/java/org/apache/rocketmq/example/benchmark/Producer.java
|
{
"start": 2510,
"end": 19943
}
|
class ____ {
private static final Logger log = LoggerFactory.getLogger(Producer.class);
private static byte[] msgBody;
private static final int MAX_LENGTH_ASYNC_QUEUE = 10000;
private static final int SLEEP_FOR_A_WHILE = 100;
public static void main(String[] args) throws MQClientException {
System.setProperty(RemotingCommand.SERIALIZE_TYPE_PROPERTY, SerializeType.ROCKETMQ.name());
Options options = ServerUtil.buildCommandlineOptions(new Options());
CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkProducer", args, buildCommandlineOptions(options), new DefaultParser());
if (null == commandLine) {
System.exit(-1);
}
final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest";
final int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s')) : 128;
final boolean keyEnable = commandLine.hasOption('k') && Boolean.parseBoolean(commandLine.getOptionValue('k'));
final int propertySize = commandLine.hasOption('p') ? Integer.parseInt(commandLine.getOptionValue('p')) : 0;
final int tagCount = commandLine.hasOption('l') ? Integer.parseInt(commandLine.getOptionValue('l')) : 0;
final boolean msgTraceEnable = commandLine.hasOption('m') && Boolean.parseBoolean(commandLine.getOptionValue('m'));
final boolean aclEnable = commandLine.hasOption('a') && Boolean.parseBoolean(commandLine.getOptionValue('a'));
final long messageNum = commandLine.hasOption('q') ? Long.parseLong(commandLine.getOptionValue('q')) : 0;
final boolean delayEnable = commandLine.hasOption('d') && Boolean.parseBoolean(commandLine.getOptionValue('d'));
final int delayLevel = commandLine.hasOption('e') ? Integer.parseInt(commandLine.getOptionValue('e')) : 1;
final boolean asyncEnable = commandLine.hasOption('y') && Boolean.parseBoolean(commandLine.getOptionValue('y'));
final int threadCount = asyncEnable ? 1 : commandLine.hasOption('w') ? Integer.parseInt(commandLine.getOptionValue('w')) : 64;
final boolean enableCompress = commandLine.hasOption('c') && Boolean.parseBoolean(commandLine.getOptionValue('c'));
final int reportInterval = commandLine.hasOption("ri") ? Integer.parseInt(commandLine.getOptionValue("ri")) : 10000;
System.out.printf("topic: %s, threadCount: %d, messageSize: %d, keyEnable: %s, propertySize: %d, tagCount: %d, " +
"traceEnable: %s, aclEnable: %s, messageQuantity: %d, delayEnable: %s, delayLevel: %s, " +
"asyncEnable: %s%n compressEnable: %s, reportInterval: %d%n",
topic, threadCount, messageSize, keyEnable, propertySize, tagCount, msgTraceEnable, aclEnable, messageNum,
delayEnable, delayLevel, asyncEnable, enableCompress, reportInterval);
StringBuilder sb = new StringBuilder(messageSize);
for (int i = 0; i < messageSize; i++) {
sb.append(RandomStringUtils.randomAlphanumeric(1));
}
msgBody = sb.toString().getBytes(StandardCharsets.UTF_8);
final ExecutorService sendThreadPool = Executors.newFixedThreadPool(threadCount);
final StatsBenchmarkProducer statsBenchmark = new StatsBenchmarkProducer();
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("BenchmarkTimerThread-%d").daemon(true).build());
final LinkedList<Long[]> snapshotList = new LinkedList<>();
final long[] msgNums = new long[threadCount];
if (messageNum > 0) {
Arrays.fill(msgNums, messageNum / threadCount);
long mod = messageNum % threadCount;
if (mod > 0) {
msgNums[0] += mod;
}
}
executorService.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
snapshotList.addLast(statsBenchmark.createSnapshot());
if (snapshotList.size() > 10) {
snapshotList.removeFirst();
}
}
}, 1000, 1000, TimeUnit.MILLISECONDS);
executorService.scheduleAtFixedRate(new TimerTask() {
private void printStats() {
if (snapshotList.size() >= 10) {
doPrintStats(snapshotList, statsBenchmark, false);
}
}
@Override
public void run() {
try {
this.printStats();
} catch (Exception e) {
e.printStackTrace();
}
}
}, reportInterval, reportInterval, TimeUnit.MILLISECONDS);
RPCHook rpcHook = null;
if (aclEnable) {
String ak = commandLine.hasOption("ak") ? String.valueOf(commandLine.getOptionValue("ak")) : AclClient.ACL_ACCESS_KEY;
String sk = commandLine.hasOption("sk") ? String.valueOf(commandLine.getOptionValue("sk")) : AclClient.ACL_SECRET_KEY;
rpcHook = AclClient.getAclRPCHook(ak, sk);
}
final DefaultMQProducer producer = new DefaultMQProducer("benchmark_producer", rpcHook, msgTraceEnable, null);
producer.setInstanceName(Long.toString(System.currentTimeMillis()));
if (commandLine.hasOption('n')) {
String ns = commandLine.getOptionValue('n');
producer.setNamesrvAddr(ns);
}
if (enableCompress) {
String compressType = commandLine.hasOption("ct") ? commandLine.getOptionValue("ct").trim() : "ZLIB";
int compressLevel = commandLine.hasOption("cl") ? Integer.parseInt(commandLine.getOptionValue("cl")) : 5;
int compressOverHowMuch = commandLine.hasOption("ch") ? Integer.parseInt(commandLine.getOptionValue("ch")) : 4096;
producer.setCompressType(CompressionType.of(compressType));
producer.setCompressLevel(compressLevel);
producer.setCompressMsgBodyOverHowmuch(compressOverHowMuch);
System.out.printf("compressType: %s compressLevel: %s%n", compressType, compressLevel);
} else {
producer.setCompressMsgBodyOverHowmuch(Integer.MAX_VALUE);
}
producer.start();
for (int i = 0; i < threadCount; i++) {
final long msgNumLimit = msgNums[i];
if (messageNum > 0 && msgNumLimit == 0) {
break;
}
sendThreadPool.execute(new Runnable() {
@Override
public void run() {
int num = 0;
while (true) {
try {
final Message msg = buildMessage(topic);
final long beginTimestamp = System.currentTimeMillis();
if (keyEnable) {
msg.setKeys(String.valueOf(beginTimestamp / 1000));
}
if (delayEnable) {
msg.setDelayTimeLevel(delayLevel);
}
if (tagCount > 0) {
msg.setTags(String.format("tag%d", System.currentTimeMillis() % tagCount));
}
if (propertySize > 0) {
if (msg.getProperties() != null) {
msg.getProperties().clear();
}
int i = 0;
int startValue = (new Random(System.currentTimeMillis())).nextInt(100);
int size = 0;
while (true) {
String prop1 = "prop" + i, prop1V = "hello" + startValue;
String prop2 = "prop" + (i + 1), prop2V = String.valueOf(startValue);
msg.putUserProperty(prop1, prop1V);
msg.putUserProperty(prop2, prop2V);
size += prop1.length() + prop2.length() + prop1V.length() + prop2V.length();
if (size > propertySize) {
break;
}
i += 2;
startValue += 2;
}
}
if (asyncEnable) {
ThreadPoolExecutor e = (ThreadPoolExecutor) producer.getDefaultMQProducerImpl().getAsyncSenderExecutor();
// Flow control
while (e.getQueue().size() > MAX_LENGTH_ASYNC_QUEUE) {
Thread.sleep(SLEEP_FOR_A_WHILE);
}
producer.send(msg, new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
updateStatsSuccess(statsBenchmark, beginTimestamp);
}
@Override
public void onException(Throwable e) {
statsBenchmark.getSendRequestFailedCount().increment();
}
});
} else {
producer.send(msg);
updateStatsSuccess(statsBenchmark, beginTimestamp);
}
} catch (RemotingException e) {
statsBenchmark.getSendRequestFailedCount().increment();
log.error("[BENCHMARK_PRODUCER] Send Exception", e);
try {
Thread.sleep(3000);
} catch (InterruptedException ignored) {
}
} catch (InterruptedException e) {
statsBenchmark.getSendRequestFailedCount().increment();
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
}
} catch (MQClientException e) {
statsBenchmark.getSendRequestFailedCount().increment();
log.error("[BENCHMARK_PRODUCER] Send Exception", e);
} catch (MQBrokerException e) {
statsBenchmark.getReceiveResponseFailedCount().increment();
log.error("[BENCHMARK_PRODUCER] Send Exception", e);
try {
Thread.sleep(3000);
} catch (InterruptedException ignored) {
}
}
if (messageNum > 0 && ++num >= msgNumLimit) {
break;
}
}
}
});
}
try {
sendThreadPool.shutdown();
sendThreadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
executorService.shutdown();
try {
executorService.awaitTermination(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
if (snapshotList.size() > 1) {
doPrintStats(snapshotList, statsBenchmark, true);
} else {
System.out.printf("[Complete] Send Total: %d Send Failed: %d Response Failed: %d%n",
statsBenchmark.getSendRequestSuccessCount().longValue() + statsBenchmark.getSendRequestFailedCount().longValue(),
statsBenchmark.getSendRequestFailedCount().longValue(), statsBenchmark.getReceiveResponseFailedCount().longValue());
}
producer.shutdown();
} catch (InterruptedException e) {
log.error("[Exit] Thread Interrupted Exception", e);
}
}
private static void updateStatsSuccess(StatsBenchmarkProducer statsBenchmark, long beginTimestamp) {
statsBenchmark.getSendRequestSuccessCount().increment();
statsBenchmark.getReceiveResponseSuccessCount().increment();
final long currentRT = System.currentTimeMillis() - beginTimestamp;
statsBenchmark.getSendMessageSuccessTimeTotal().add(currentRT);
long prevMaxRT = statsBenchmark.getSendMessageMaxRT().longValue();
while (currentRT > prevMaxRT) {
boolean updated = statsBenchmark.getSendMessageMaxRT().compareAndSet(prevMaxRT, currentRT);
if (updated)
break;
prevMaxRT = statsBenchmark.getSendMessageMaxRT().longValue();
}
}
public static Options buildCommandlineOptions(final Options options) {
Option opt = new Option("w", "threadCount", true, "Thread count, Default: 64");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("s", "messageSize", true, "Message Size, Default: 128");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("k", "keyEnable", true, "Message Key Enable, Default: false");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("t", "topic", true, "Topic name, Default: BenchmarkTest");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("l", "tagCount", true, "Tag count, Default: 0");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("m", "msgTraceEnable", true, "Message Trace Enable, Default: false");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("a", "aclEnable", true, "Acl Enable, Default: false");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("ak", "accessKey", true, "Acl access key, Default: 12345678");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("sk", "secretKey", true, "Acl secret key, Default: rocketmq2");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("q", "messageQuantity", true, "Send message quantity, Default: 0, running forever");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("d", "delayEnable", true, "Delay message Enable, Default: false");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("e", "delayLevel", true, "Delay message level, Default: 1");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("y", "asyncEnable", true, "Enable async produce, Default: false");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "compressEnable", true, "Enable compress msg over 4K, Default: false");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("ct", "compressType", true, "Message compressed type, Default: ZLIB");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("cl", "compressLevel", true, "Message compressed level, Default: 5");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("ch", "compressOverHowMuch", true, "Compress message when body over how much(unit Byte), Default: 4096");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("ri", "reportInterval", true, "The number of ms between reports, Default: 10000");
opt.setRequired(false);
options.addOption(opt);
return options;
}
private static Message buildMessage(final String topic) {
return new Message(topic, msgBody);
}
private static void doPrintStats(final LinkedList<Long[]> snapshotList, final StatsBenchmarkProducer statsBenchmark, boolean done) {
Long[] begin = snapshotList.getFirst();
Long[] end = snapshotList.getLast();
final long sendTps = (long) (((end[3] - begin[3]) / (double) (end[0] - begin[0])) * 1000L);
final double averageRT = (end[5] - begin[5]) / (double) (end[3] - begin[3]);
if (done) {
System.out.printf("[Complete] Send Total: %d | Send TPS: %d | Max RT(ms): %d | Average RT(ms): %7.3f | Send Failed: %d | Response Failed: %d%n",
statsBenchmark.getSendRequestSuccessCount().longValue() + statsBenchmark.getSendRequestFailedCount().longValue(),
sendTps, statsBenchmark.getSendMessageMaxRT().longValue(), averageRT, end[2], end[4]);
} else {
System.out.printf("Current Time: %s | Send TPS: %d | Max RT(ms): %d | Average RT(ms): %7.3f | Send Failed: %d | Response Failed: %d%n",
UtilAll.timeMillisToHumanString2(System.currentTimeMillis()), sendTps, statsBenchmark.getSendMessageMaxRT().longValue(), averageRT, end[2], end[4]);
}
}
}
|
Producer
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionElementConversionTest.java
|
{
"start": 2264,
"end": 2487
}
|
class ____ {
@Id
private Integer id;
@ElementCollection
@Column(name = "`set`")
private Set<Color> set;
@ElementCollection
@Enumerated(EnumType.STRING)
private Map<Color, Status> map;
}
public static
|
Customer
|
java
|
apache__camel
|
components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpSocketConsumerRunnable.java
|
{
"start": 4207,
"end": 11328
}
|
class ____>[endpoint key] - [local socket address] -> [remote socket address]
*
* @return the thread name
*/
String createThreadName() {
// Get the URI without options
String fullEndpointKey = consumer.getEndpoint().getEndpointKey();
String endpointKey = StringHelper.before(fullEndpointKey, "?", fullEndpointKey);
// Now put it all together
return String.format("%s[%s] - %s", this.getClass().getSimpleName(), endpointKey, combinedAddress);
}
@Override
public void run() {
running = true;
String originalThreadName = Thread.currentThread().getName();
Thread.currentThread().setName(createThreadName());
MDC.put(UnitOfWork.MDC_CAMEL_CONTEXT_ID, consumer.getEndpoint().getCamelContext().getName());
Route route = consumer.getRoute();
if (route != null) {
String routeId = route.getId();
if (routeId != null) {
MDC.put(UnitOfWork.MDC_ROUTE_ID, route.getId());
}
}
log.debug("Starting {} for {}", this.getClass().getSimpleName(), combinedAddress);
try {
byte[] hl7MessageBytes = null;
if (mllpBuffer.hasCompleteEnvelope()) {
// If we got a complete message on the validation read, process it
hl7MessageBytes = mllpBuffer.toMllpPayload();
mllpBuffer.reset();
consumer.processMessage(hl7MessageBytes, this);
}
while (running && null != clientSocket && clientSocket.isConnected() && !clientSocket.isClosed()) {
log.debug("Checking for data ....");
try {
mllpBuffer.readFrom(clientSocket);
if (mllpBuffer.hasCompleteEnvelope()) {
hl7MessageBytes = mllpBuffer.toMllpPayload();
if (log.isDebugEnabled()) {
log.debug("Received {} byte message {}", hl7MessageBytes.length,
hl7Util.convertToPrintFriendlyString(hl7MessageBytes));
}
if (mllpBuffer.hasLeadingOutOfBandData()) {
// TODO: Move the conversion utilities to the MllpSocketBuffer to avoid a byte[] copy
log.warn("Ignoring leading out-of-band data: {}",
hl7Util.convertToPrintFriendlyString(mllpBuffer.getLeadingOutOfBandData()));
}
if (mllpBuffer.hasTrailingOutOfBandData()) {
log.warn("Ignoring trailing out-of-band data: {}",
hl7Util.convertToPrintFriendlyString(mllpBuffer.getTrailingOutOfBandData()));
}
mllpBuffer.reset();
consumer.processMessage(hl7MessageBytes, this);
} else if (!mllpBuffer.hasStartOfBlock()) {
byte[] payload = mllpBuffer.toByteArray();
log.warn("Ignoring {} byte un-enveloped payload {}", payload.length,
hl7Util.convertToPrintFriendlyString(payload));
mllpBuffer.reset();
} else if (!mllpBuffer.isEmpty()) {
byte[] payload = mllpBuffer.toByteArray();
log.warn("Partial {} byte payload received {}", payload.length,
hl7Util.convertToPrintFriendlyString(payload));
}
} catch (SocketTimeoutException timeoutEx) {
if (mllpBuffer.isEmpty()) {
if (consumer.getConfiguration().hasIdleTimeout()) {
long currentTicks = System.currentTimeMillis();
long lastReceivedMessageTicks = consumer.getConsumerRunnables().get(this);
long idleTime = currentTicks - lastReceivedMessageTicks;
if (idleTime >= consumer.getConfiguration().getIdleTimeout()) {
String resetMessage = String.format("Connection idle time %d exceeded idleTimeout %d", idleTime,
consumer.getConfiguration().getIdleTimeout());
mllpBuffer.resetSocket(clientSocket, resetMessage);
}
}
log.debug("No data received - ignoring timeout");
} else {
mllpBuffer.resetSocket(clientSocket);
consumer.handleMessageTimeout("Timeout receiving complete message payload",
mllpBuffer.toByteArrayAndReset(), timeoutEx);
}
} catch (MllpSocketException mllpSocketEx) {
mllpBuffer.resetSocket(clientSocket);
if (!mllpBuffer.isEmpty()) {
consumer.handleMessageException("Exception encountered reading payload",
mllpBuffer.toByteArrayAndReset(), mllpSocketEx);
} else {
log.debug("Ignoring exception encountered checking for data", mllpSocketEx);
}
}
}
} catch (Exception unexpectedEx) {
log.error("Unexpected exception encountered receiving messages", unexpectedEx);
} finally {
consumer.getConsumerRunnables().remove(this);
log.debug("{} for {} completed", this.getClass().getSimpleName(), combinedAddress);
Thread.currentThread().setName(originalThreadName);
MDC.remove(UnitOfWork.MDC_ROUTE_ID);
MDC.remove(UnitOfWork.MDC_CAMEL_CONTEXT_ID);
mllpBuffer.resetSocket(clientSocket);
}
}
public Socket getSocket() {
return clientSocket;
}
public MllpSocketBuffer getMllpBuffer() {
return mllpBuffer;
}
public void closeSocket() {
mllpBuffer.closeSocket(clientSocket);
}
public void closeSocket(String logMessage) {
mllpBuffer.closeSocket(clientSocket, logMessage);
}
public void resetSocket() {
mllpBuffer.resetSocket(clientSocket);
}
public void resetSocket(String logMessage) {
mllpBuffer.resetSocket(clientSocket, logMessage);
}
public void stop() {
running = false;
}
public boolean hasLocalAddress() {
return localAddress != null && !localAddress.isEmpty();
}
public String getLocalAddress() {
return localAddress;
}
public boolean hasRemoteAddress() {
return remoteAddress != null && !remoteAddress.isEmpty();
}
public String getRemoteAddress() {
return remoteAddress;
}
public boolean hasCombinedAddress() {
return combinedAddress != null && combinedAddress.isEmpty();
}
public String getCombinedAddress() {
return combinedAddress;
}
}
|
name
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlMigrateStatement.java
|
{
"start": 899,
"end": 3904
}
|
class ____ extends MySqlStatementImpl {
private SQLName schema;
private SQLCharExpr shardNames;
private SQLIntegerExpr migrateType;
private SQLCharExpr fromInsId;
private SQLCharExpr fromInsIp;
private SQLIntegerExpr fromInsPort;
private SQLCharExpr fromInsStatus;
private SQLCharExpr toInsId;
private SQLCharExpr toInsIp;
private SQLIntegerExpr toInsPort;
private SQLCharExpr toInsStatus;
@Override
public void accept0(MySqlASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, schema);
acceptChild(visitor, shardNames);
acceptChild(visitor, migrateType);
acceptChild(visitor, fromInsId);
acceptChild(visitor, fromInsIp);
acceptChild(visitor, fromInsPort);
acceptChild(visitor, fromInsStatus);
acceptChild(visitor, toInsId);
acceptChild(visitor, toInsIp);
acceptChild(visitor, toInsPort);
acceptChild(visitor, toInsStatus);
}
visitor.endVisit(this);
}
public SQLName getSchema() {
return schema;
}
public void setSchema(SQLName schema) {
this.schema = schema;
}
public SQLCharExpr getShardNames() {
return shardNames;
}
public void setShardNames(SQLCharExpr shardNames) {
this.shardNames = shardNames;
}
public SQLIntegerExpr getMigrateType() {
return migrateType;
}
public void setMigrateType(SQLIntegerExpr migrateType) {
this.migrateType = migrateType;
}
public SQLCharExpr getFromInsId() {
return fromInsId;
}
public void setFromInsId(SQLCharExpr fromInsId) {
this.fromInsId = fromInsId;
}
public SQLCharExpr getFromInsIp() {
return fromInsIp;
}
public void setFromInsIp(SQLCharExpr fromInsIp) {
this.fromInsIp = fromInsIp;
}
public SQLIntegerExpr getFromInsPort() {
return fromInsPort;
}
public void setFromInsPort(SQLIntegerExpr fromInsPort) {
this.fromInsPort = fromInsPort;
}
public SQLCharExpr getFromInsStatus() {
return fromInsStatus;
}
public void setFromInsStatus(SQLCharExpr fromInsStatus) {
this.fromInsStatus = fromInsStatus;
}
public SQLCharExpr getToInsId() {
return toInsId;
}
public void setToInsId(SQLCharExpr toInsId) {
this.toInsId = toInsId;
}
public SQLCharExpr getToInsIp() {
return toInsIp;
}
public void setToInsIp(SQLCharExpr toInsIp) {
this.toInsIp = toInsIp;
}
public SQLIntegerExpr getToInsPort() {
return toInsPort;
}
public void setToInsPort(SQLIntegerExpr toInsPort) {
this.toInsPort = toInsPort;
}
public SQLCharExpr getToInsStatus() {
return toInsStatus;
}
public void setToInsStatus(SQLCharExpr toInsStatus) {
this.toInsStatus = toInsStatus;
}
}
|
MySqlMigrateStatement
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/client/protocol/decoder/StringReplayDecoder.java
|
{
"start": 861,
"end": 1139
}
|
class ____ implements Decoder<String> {
@Override
public String decode(ByteBuf buf, State state) {
String status = buf.readBytes(buf.bytesBefore((byte) '\r')).toString(CharsetUtil.UTF_8);
buf.skipBytes(2);
return status;
}
}
|
StringReplayDecoder
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/JobManagerLogUrlHeaders.java
|
{
"start": 1063,
"end": 2312
}
|
class ____
implements RuntimeMessageHeaders<EmptyRequestBody, LogUrlResponse, JobMessageParameters> {
private static final JobManagerLogUrlHeaders INSTANCE = new JobManagerLogUrlHeaders();
private static final String URL = "/jobs/:" + JobIDPathParameter.KEY + "/jobmanager/log-url";
private JobManagerLogUrlHeaders() {}
@Override
public Class<EmptyRequestBody> getRequestClass() {
return EmptyRequestBody.class;
}
@Override
public Class<LogUrlResponse> getResponseClass() {
return LogUrlResponse.class;
}
@Override
public HttpResponseStatus getResponseStatusCode() {
return HttpResponseStatus.OK;
}
@Override
public JobMessageParameters getUnresolvedMessageParameters() {
return new JobMessageParameters();
}
@Override
public HttpMethodWrapper getHttpMethod() {
return HttpMethodWrapper.GET;
}
@Override
public String getTargetRestEndpointURL() {
return URL;
}
public static JobManagerLogUrlHeaders getInstance() {
return INSTANCE;
}
@Override
public String getDescription() {
return "Returns the log url of jobmanager of a specific job.";
}
}
|
JobManagerLogUrlHeaders
|
java
|
quarkusio__quarkus
|
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/security/HttpUpgradePermissionCheckerArgsValidationFailureTest.java
|
{
"start": 1580,
"end": 1746
}
|
class ____ {
@OnTextMessage
String echo(String message) {
return message;
}
}
@ApplicationScoped
public static
|
Endpoint
|
java
|
quarkusio__quarkus
|
extensions/quartz/runtime/src/main/java/io/quarkus/quartz/Nonconcurrent.java
|
{
"start": 514,
"end": 1339
}
|
class ____ with {@link DisallowConcurrentExecution}.
* <p>
* If {@code quarkus.quartz.run-blocking-scheduled-method-on-quartz-thread} is set to
* {@code false} the execution of a scheduled method is offloaded to a specific Quarkus thread pool but the triggering Quartz
* thread is blocked until the execution is finished. Therefore, make sure the Quartz thread pool is configured appropriately.
* <p>
* If {@code quarkus.quartz.run-blocking-scheduled-method-on-quartz-thread} is set to {@code true} the scheduled method is
* invoked on a thread managed by Quartz.
* <p>
* Unlike with {@link Scheduled.ConcurrentExecution#SKIP} the {@link SkippedExecution} event is never fired if a method
* execution is skipped by Quartz.
*
* @see DisallowConcurrentExecution
*/
@Target(METHOD)
@Retention(RUNTIME)
public @
|
annotated
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/erroneous/annotationnotfound/AnnotationNotFoundTest.java
|
{
"start": 793,
"end": 1251
}
|
class ____ {
@ProcessorTest
@IssueKey( "298" )
@ExpectedCompilationOutcome(
value = CompilationResult.FAILED,
diagnostics = {
@Diagnostic( type = ErroneousMapper.class,
kind = Kind.ERROR,
line = 17,
messageRegExp = "NotFoundAnnotation")
}
)
public void shouldFailToGenerateMappings() {
}
}
|
AnnotationNotFoundTest
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/netty/TestingNettyServiceProducer.java
|
{
"start": 1130,
"end": 2262
}
|
class ____ implements NettyServiceProducer {
private final BiConsumer<TieredStorageSubpartitionId, NettyConnectionWriter>
connectionEstablishedConsumer;
private final Consumer<NettyConnectionId> connectionBrokenConsumer;
private TestingNettyServiceProducer(
BiConsumer<TieredStorageSubpartitionId, NettyConnectionWriter>
connectionEstablishedConsumer,
Consumer<NettyConnectionId> connectionBrokenConsumer) {
this.connectionEstablishedConsumer = connectionEstablishedConsumer;
this.connectionBrokenConsumer = connectionBrokenConsumer;
}
@Override
public void connectionEstablished(
TieredStorageSubpartitionId subpartitionId,
NettyConnectionWriter nettyConnectionWriter) {
connectionEstablishedConsumer.accept(subpartitionId, nettyConnectionWriter);
}
@Override
public void connectionBroken(NettyConnectionId connectionId) {
connectionBrokenConsumer.accept(connectionId);
}
/** Builder for {@link TestingNettyServiceProducer}. */
public static
|
TestingNettyServiceProducer
|
java
|
quarkusio__quarkus
|
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/EventBean.java
|
{
"start": 241,
"end": 884
}
|
class ____ extends BuiltInBean<Event<?>> {
public static final Set<Type> EVENT_TYPES = Set.of(Event.class, Object.class);
@Override
public Set<Type> getTypes() {
return EVENT_TYPES;
}
@Override
public Event<?> get(CreationalContext<Event<?>> creationalContext) {
// Obtain current IP to get the required type and qualifiers
InjectionPoint ip = InjectionPointProvider.getCurrent(creationalContext);
return ArcContainerImpl.instance().getEvent(ip.getType(), ip.getQualifiers(), ip);
}
@Override
public Class<?> getBeanClass() {
return EventImpl.class;
}
}
|
EventBean
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/sql/exec/spi/JdbcParameterBinder.java
|
{
"start": 329,
"end": 718
}
|
interface ____ {
JdbcParameterBinder NOOP = (statement, startPosition, jdbcParameterBindings, executionContext) -> {};
/**
* Bind the appropriate value in the JDBC statement
*/
void bindParameterValue(
PreparedStatement statement,
int startPosition,
JdbcParameterBindings jdbcParameterBindings,
ExecutionContext executionContext) throws SQLException;
}
|
JdbcParameterBinder
|
java
|
apache__kafka
|
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/ConnectMetrics.java
|
{
"start": 10072,
"end": 12739
}
|
class ____ {
private final String groupName;
private final Map<String, String> tags;
private final int hc;
private final String str;
public MetricGroupId(String groupName, Map<String, String> tags) {
Objects.requireNonNull(groupName);
Objects.requireNonNull(tags);
this.groupName = groupName;
this.tags = Collections.unmodifiableMap(new LinkedHashMap<>(tags)); // To ensure the order of insertion, we have to use Collections.
this.hc = Objects.hash(this.groupName, this.tags);
StringBuilder sb = new StringBuilder(this.groupName);
for (Map.Entry<String, String> entry : this.tags.entrySet()) {
sb.append(";").append(entry.getKey()).append('=').append(entry.getValue());
}
this.str = sb.toString();
}
/**
* Get the group name.
*
* @return the group name; never null
*/
public String groupName() {
return groupName;
}
/**
* Get the immutable map of tag names and values.
*
* @return the tags; never null
*/
public Map<String, String> tags() {
return tags;
}
/**
* Determine if the supplied metric name is part of this group identifier.
*
* @param metricName the metric name
* @return true if the metric name's group and tags match this group identifier, or false otherwise
*/
public boolean includes(MetricName metricName) {
return metricName != null && groupName.equals(metricName.group()) && tags.equals(metricName.tags());
}
@Override
public int hashCode() {
return hc;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj instanceof MetricGroupId that) {
return this.groupName.equals(that.groupName) && this.tags.equals(that.tags);
}
return false;
}
@Override
public String toString() {
return str;
}
}
/**
* A group of metrics. Each group maps to a JMX MBean and each metric maps to an MBean attribute.
* <p>
* Sensors should be added via the {@code sensor} methods on this class, rather than directly through
* the {@link Metrics} class, so that the sensor names are made to be unique (based on the group name)
* and so the sensors are removed when this group is {@link #close() closed}.
*/
public
|
MetricGroupId
|
java
|
quarkusio__quarkus
|
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/management/ManagementWithP12WithAliasTest.java
|
{
"start": 1270,
"end": 3311
}
|
class ____ {
private static final String configuration = """
quarkus.management.enabled=true
quarkus.management.root-path=/management
quarkus.management.ssl.certificate.key-store-file=server-keystore.p12
quarkus.management.ssl.certificate.key-store-password=secret
quarkus.management.ssl.certificate.key-store-alias=alias
quarkus.management.ssl.certificate.key-store-alias-password=alias-password
""";
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addAsResource(new StringAsset(configuration), "application.properties")
.addAsResource(new File("target/certs/ssl-management-interface-alias-test-keystore.p12"),
"server-keystore.p12")
.addClasses(ManagementWithJksTest.MyObserver.class))
.addBuildChainCustomizer(buildCustomizer());
static Consumer<BuildChainBuilder> buildCustomizer() {
return new Consumer<BuildChainBuilder>() {
@Override
public void accept(BuildChainBuilder builder) {
builder.addBuildStep(new BuildStep() {
@Override
public void execute(BuildContext context) {
NonApplicationRootPathBuildItem buildItem = context.consume(NonApplicationRootPathBuildItem.class);
context.produce(buildItem.routeBuilder()
.management()
.route("my-route")
.handler(new MyHandler())
.blockingRoute()
.build());
}
}).produces(RouteBuildItem.class)
.consumes(NonApplicationRootPathBuildItem.class)
.build();
}
};
}
public static
|
ManagementWithP12WithAliasTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchTest.java
|
{
"start": 1063,
"end": 3871
}
|
class ____ {
@Test
public void testBatchInsertUpdate(SessionFactoryScope factoryScope) {
long start = System.currentTimeMillis();
final int N = 5000; //26 secs with batch flush, 26 without
//final int N = 100000; //53 secs with batch flush, OOME without
//final int N = 250000; //137 secs with batch flush, OOME without
int batchSize = factoryScope.getSessionFactory().getSessionFactoryOptions().getJdbcBatchSize();
doBatchInsertUpdate( N, batchSize, factoryScope );
System.out.println( System.currentTimeMillis() - start );
}
@Test
public void testBatchInsertUpdateSizeEqJdbcBatchSize(SessionFactoryScope factoryScope) {
int batchSize = factoryScope.getSessionFactory().getSessionFactoryOptions().getJdbcBatchSize();
doBatchInsertUpdate( 50, batchSize, factoryScope );
}
@Test
public void testBatchInsertUpdateSizeLtJdbcBatchSize(SessionFactoryScope factoryScope) {
int batchSize = factoryScope.getSessionFactory().getSessionFactoryOptions().getJdbcBatchSize();
doBatchInsertUpdate( 50, batchSize - 1, factoryScope );
}
@Test
public void testBatchInsertUpdateSizeGtJdbcBatchSize(SessionFactoryScope factoryScope) {
int batchSize = factoryScope.getSessionFactory().getSessionFactoryOptions().getJdbcBatchSize();
doBatchInsertUpdate( 50, batchSize + 1, factoryScope );
}
public void doBatchInsertUpdate(int nEntities, int nBeforeFlush, SessionFactoryScope factoryScope) {
factoryScope.inTransaction( (session) -> {
session.setCacheMode( CacheMode.IGNORE );
for ( int i = 0; i < nEntities; i++ ) {
DataPoint dp = new DataPoint();
dp.setX( new BigDecimal( i * 0.1d ).setScale( 19, RoundingMode.DOWN ) );
dp.setY( BigDecimal.valueOf( Math.cos( dp.getX().doubleValue() ) ).setScale( 19, RoundingMode.DOWN ) );
session.persist( dp );
if ( ( i + 1 ) % nBeforeFlush == 0 ) {
session.flush();
session.clear();
}
}
} );
factoryScope.inTransaction( (session) -> {
session.setCacheMode( CacheMode.IGNORE );
int i = 0;
try (ScrollableResults sr = session.createQuery( "from DataPoint dp order by dp.x asc" )
.scroll( ScrollMode.FORWARD_ONLY )) {
while ( sr.next() ) {
DataPoint dp = (DataPoint) sr.get();
dp.setDescription( "done!" );
if ( ++i % nBeforeFlush == 0 ) {
session.flush();
session.clear();
}
}
}
} );
factoryScope.inTransaction( (session) -> {
session.setCacheMode( CacheMode.IGNORE );
int i = 0;
try (ScrollableResults sr = session.createQuery( "from DataPoint dp order by dp.x asc" )
.scroll( ScrollMode.FORWARD_ONLY )) {
while ( sr.next() ) {
DataPoint dp = (DataPoint) sr.get();
session.remove( dp );
if ( ++i % nBeforeFlush == 0 ) {
session.flush();
session.clear();
}
}
}
} );
}
}
|
BatchTest
|
java
|
spring-projects__spring-boot
|
module/spring-boot-jdbc/src/test/java/org/springframework/boot/jdbc/autoconfigure/DataSourceAutoConfigurationTests.java
|
{
"start": 13355,
"end": 13562
}
|
class ____ {
@Bean
JdbcConnectionDetails sqlJdbcConnectionDetails() {
return new TestJdbcConnectionDetails();
}
}
@Configuration(proxyBeanMethods = false)
static
|
JdbcConnectionDetailsConfiguration
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/clients/producer/ProducerConfig.java
|
{
"start": 26865,
"end": 27294
}
|
interface ____ you to plug in a custom partitioner.";
/** <code>interceptor.classes</code> */
public static final String INTERCEPTOR_CLASSES_CONFIG = "interceptor.classes";
public static final String INTERCEPTOR_CLASSES_DOC = "A list of classes to use as interceptors. "
+ "Implementing the <code>org.apache.kafka.clients.producer.ProducerInterceptor</code>
|
allows
|
java
|
elastic__elasticsearch
|
modules/analysis-common/src/test/java/org/elasticsearch/analysis/common/SynonymsAnalysisTests.java
|
{
"start": 2011,
"end": 25541
}
|
class ____ extends ESTestCase {
private IndexAnalyzers indexAnalyzers;
public void testSynonymsAnalysis() throws IOException {
InputStream synonyms = getClass().getResourceAsStream("synonyms.txt");
InputStream synonymsWordnet = getClass().getResourceAsStream("synonyms_wordnet.txt");
Path home = createTempDir();
Path config = home.resolve("config");
Files.createDirectory(config);
Files.copy(synonyms, config.resolve("synonyms.txt"));
Files.copy(synonymsWordnet, config.resolve("synonyms_wordnet.txt"));
String json = "/org/elasticsearch/analysis/common/synonyms.json";
Settings settings = Settings.builder()
.loadFromStream(json, getClass().getResourceAsStream(json), false)
.put(Environment.PATH_HOME_SETTING.getKey(), home)
.put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current())
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
match("synonymAnalyzer", "kimchy is the dude abides", "shay is the elasticsearch man!");
match("synonymAnalyzer_file", "kimchy is the dude abides", "shay is the elasticsearch man!");
match("synonymAnalyzerWordnet", "abstain", "abstain refrain desist");
match("synonymAnalyzerWordnet_file", "abstain", "abstain refrain desist");
match("synonymAnalyzerWithsettings", "kimchy", "sha hay");
match("synonymAnalyzerWithStopAfterSynonym", "kimchy is the dude abides , stop", "shay is the elasticsearch man! ,");
match("synonymAnalyzerWithStopBeforeSynonym", "kimchy is the dude abides , stop", "shay is the elasticsearch man! ,");
match("synonymAnalyzerWithStopSynonymAfterSynonym", "kimchy is the dude abides", "shay is the man!");
match("synonymAnalyzerExpand", "kimchy is the dude abides", "kimchy shay is the dude elasticsearch abides man!");
match("synonymAnalyzerExpandWithStopAfterSynonym", "kimchy is the dude abides", "shay is the dude abides man!");
}
public void testSynonymWordDeleteByAnalyzer() throws IOException {
Settings.Builder settingsBuilder = Settings.builder()
.put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current())
.put("path.home", createTempDir().toString())
.put("index.analysis.filter.my_synonym.type", "synonym")
.putList("index.analysis.filter.my_synonym.synonyms", "kimchy => shay", "dude => elasticsearch", "abides => man!")
.put("index.analysis.filter.stop_within_synonym.type", "stop")
.putList("index.analysis.filter.stop_within_synonym.stopwords", "kimchy", "elasticsearch")
.put("index.analysis.analyzer.synonymAnalyzerWithStopSynonymBeforeSynonym.tokenizer", "whitespace")
.putList("index.analysis.analyzer.synonymAnalyzerWithStopSynonymBeforeSynonym.filter", "stop_within_synonym", "my_synonym");
CheckedBiConsumer<IndexVersion, Boolean, IOException> assertIsLenient = (iv, updateable) -> {
Settings settings = settingsBuilder.put(IndexMetadata.SETTING_VERSION_CREATED, iv)
.put("index.analysis.filter.my_synonym.updateable", updateable)
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
match("synonymAnalyzerWithStopSynonymBeforeSynonym", "kimchy is the dude abides", "is the dude man!");
};
BiConsumer<IndexVersion, Boolean> assertIsNotLenient = (iv, updateable) -> {
Settings settings = settingsBuilder.put(IndexMetadata.SETTING_VERSION_CREATED, iv)
.put("index.analysis.filter.my_synonym.updateable", updateable)
.build();
try {
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
fail("fail! due to synonym word deleted by analyzer");
} catch (Exception e) {
assertThat(e, instanceOf(IllegalArgumentException.class));
assertThat(e.getMessage(), startsWith("failed to build synonyms"));
assertThat(e.getMessage(), containsString("['my_synonym' analyzer settings]"));
}
};
// Test with an index version where lenient should always be false by default
IndexVersion randomNonLenientIndexVersion = IndexVersionUtils.randomVersionBetween(
random(),
IndexVersions.MINIMUM_READONLY_COMPATIBLE,
IndexVersions.INDEX_SORTING_ON_NESTED
);
assertIsNotLenient.accept(randomNonLenientIndexVersion, false);
assertIsNotLenient.accept(randomNonLenientIndexVersion, true);
// Test with an index version where the default lenient value is based on updateable
IndexVersion randomLenientIndexVersion = IndexVersionUtils.randomVersionBetween(
random(),
IndexVersions.LENIENT_UPDATEABLE_SYNONYMS,
IndexVersion.current()
);
assertIsNotLenient.accept(randomLenientIndexVersion, false);
assertIsLenient.accept(randomLenientIndexVersion, true);
}
public void testSynonymWordDeleteByAnalyzerFromFile() throws IOException {
InputStream synonyms = getClass().getResourceAsStream("synonyms.txt");
Path home = createTempDir();
Path config = home.resolve("config");
Files.createDirectory(config);
Files.copy(synonyms, config.resolve("synonyms.txt"));
Settings.Builder settingsBuilder = Settings.builder()
.put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current())
.put("path.home", home)
.put("index.analysis.filter.my_synonym.type", "synonym")
.put("index.analysis.filter.my_synonym.synonyms_path", "synonyms.txt")
.put("index.analysis.filter.stop_within_synonym.type", "stop")
.putList("index.analysis.filter.stop_within_synonym.stopwords", "kimchy", "elasticsearch")
.put("index.analysis.analyzer.synonymAnalyzerWithStopSynonymBeforeSynonym.tokenizer", "whitespace")
.putList("index.analysis.analyzer.synonymAnalyzerWithStopSynonymBeforeSynonym.filter", "stop_within_synonym", "my_synonym");
CheckedBiConsumer<IndexVersion, Boolean, IOException> assertIsLenient = (iv, updateable) -> {
Settings settings = settingsBuilder.put(IndexMetadata.SETTING_VERSION_CREATED, iv)
.put("index.analysis.filter.my_synonym.updateable", updateable)
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
match("synonymAnalyzerWithStopSynonymBeforeSynonym", "kimchy is the dude abides", "is the dude man!");
};
BiConsumer<IndexVersion, Boolean> assertIsNotLenient = (iv, updateable) -> {
Settings settings = settingsBuilder.put(IndexMetadata.SETTING_VERSION_CREATED, iv)
.put("index.analysis.filter.my_synonym.updateable", updateable)
.build();
try {
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
fail("fail! due to synonym word deleted by analyzer");
} catch (Exception e) {
assertThat(e, instanceOf(IllegalArgumentException.class));
assertThat(e.getMessage(), equalTo("failed to build synonyms from [synonyms.txt]"));
}
};
// Test with an index version where lenient should always be false by default
IndexVersion randomNonLenientIndexVersion = IndexVersionUtils.randomVersionBetween(
random(),
IndexVersions.MINIMUM_READONLY_COMPATIBLE,
IndexVersions.INDEX_SORTING_ON_NESTED
);
assertIsNotLenient.accept(randomNonLenientIndexVersion, false);
assertIsNotLenient.accept(randomNonLenientIndexVersion, true);
// Test with an index version where the default lenient value is based on updateable
IndexVersion randomLenientIndexVersion = IndexVersionUtils.randomVersionBetween(
random(),
IndexVersions.LENIENT_UPDATEABLE_SYNONYMS,
IndexVersion.current()
);
assertIsNotLenient.accept(randomLenientIndexVersion, false);
assertIsLenient.accept(randomLenientIndexVersion, true);
}
public void testExpandSynonymWordDeleteByAnalyzer() throws IOException {
Settings.Builder settingsBuilder = Settings.builder()
.put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current())
.put("path.home", createTempDir().toString())
.put("index.analysis.filter.synonym_expand.type", "synonym")
.putList("index.analysis.filter.synonym_expand.synonyms", "kimchy, shay", "dude, elasticsearch", "abides, man!")
.put("index.analysis.filter.stop_within_synonym.type", "stop")
.putList("index.analysis.filter.stop_within_synonym.stopwords", "kimchy", "elasticsearch")
.put("index.analysis.analyzer.synonymAnalyzerExpandWithStopBeforeSynonym.tokenizer", "whitespace")
.putList("index.analysis.analyzer.synonymAnalyzerExpandWithStopBeforeSynonym.filter", "stop_within_synonym", "synonym_expand");
CheckedBiConsumer<IndexVersion, Boolean, IOException> assertIsLenient = (iv, updateable) -> {
Settings settings = settingsBuilder.put(IndexMetadata.SETTING_VERSION_CREATED, iv)
.put("index.analysis.filter.synonym_expand.updateable", updateable)
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
match("synonymAnalyzerExpandWithStopBeforeSynonym", "kimchy is the dude abides", "is the dude abides man!");
};
BiConsumer<IndexVersion, Boolean> assertIsNotLenient = (iv, updateable) -> {
Settings settings = settingsBuilder.put(IndexMetadata.SETTING_VERSION_CREATED, iv)
.put("index.analysis.filter.synonym_expand.updateable", updateable)
.build();
try {
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
fail("fail! due to synonym word deleted by analyzer");
} catch (Exception e) {
assertThat(e, instanceOf(IllegalArgumentException.class));
assertThat(e.getMessage(), startsWith("failed to build synonyms"));
assertThat(e.getMessage(), containsString("['synonym_expand' analyzer settings]"));
}
};
// Test with an index version where lenient should always be false by default
IndexVersion randomNonLenientIndexVersion = IndexVersionUtils.randomVersionBetween(
random(),
IndexVersions.MINIMUM_READONLY_COMPATIBLE,
IndexVersions.INDEX_SORTING_ON_NESTED
);
assertIsNotLenient.accept(randomNonLenientIndexVersion, false);
assertIsNotLenient.accept(randomNonLenientIndexVersion, true);
// Test with an index version where the default lenient value is based on updateable
IndexVersion randomLenientIndexVersion = IndexVersionUtils.randomVersionBetween(
random(),
IndexVersions.LENIENT_UPDATEABLE_SYNONYMS,
IndexVersion.current()
);
assertIsNotLenient.accept(randomLenientIndexVersion, false);
assertIsLenient.accept(randomLenientIndexVersion, true);
}
public void testSynonymsWrappedByMultiplexer() throws IOException {
Settings settings = Settings.builder()
.put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current())
.put("path.home", createTempDir().toString())
.put("index.analysis.filter.synonyms.type", "synonym")
.putList("index.analysis.filter.synonyms.synonyms", "programmer, developer")
.put("index.analysis.filter.my_english.type", "stemmer")
.put("index.analysis.filter.my_english.language", "porter2")
.put("index.analysis.filter.stem_repeat.type", "multiplexer")
.putList("index.analysis.filter.stem_repeat.filters", "my_english, synonyms")
.put("index.analysis.analyzer.synonymAnalyzer.tokenizer", "standard")
.putList("index.analysis.analyzer.synonymAnalyzer.filter", "lowercase", "stem_repeat")
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
BaseTokenStreamTestCase.assertAnalyzesTo(
indexAnalyzers.get("synonymAnalyzer"),
"Some developers are odd",
new String[] { "some", "developers", "develop", "programm", "are", "odd" },
new int[] { 1, 1, 0, 0, 1, 1 }
);
}
public void testAsciiFoldingFilterForSynonyms() throws IOException {
Settings settings = Settings.builder()
.put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current())
.put("path.home", createTempDir().toString())
.put("index.analysis.filter.synonyms.type", "synonym")
.putList("index.analysis.filter.synonyms.synonyms", "hoj, height")
.put("index.analysis.analyzer.synonymAnalyzer.tokenizer", "standard")
.putList("index.analysis.analyzer.synonymAnalyzer.filter", "lowercase", "asciifolding", "synonyms")
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
BaseTokenStreamTestCase.assertAnalyzesTo(
indexAnalyzers.get("synonymAnalyzer"),
"høj",
new String[] { "hoj", "height" },
new int[] { 1, 0 }
);
}
public void testPreconfigured() throws IOException {
Settings settings = Settings.builder()
.put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current())
.put("path.home", createTempDir().toString())
.put("index.analysis.filter.synonyms.type", "synonym")
.putList("index.analysis.filter.synonyms.synonyms", "würst, sausage")
.put("index.analysis.analyzer.my_analyzer.tokenizer", "standard")
.putList("index.analysis.analyzer.my_analyzer.filter", "lowercase", "asciifolding", "synonyms")
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
BaseTokenStreamTestCase.assertAnalyzesTo(
indexAnalyzers.get("my_analyzer"),
"würst",
new String[] { "wurst", "sausage" },
new int[] { 1, 0 }
);
}
public void testChainedSynonymFilters() throws IOException {
Settings settings = Settings.builder()
.put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current())
.put("path.home", createTempDir().toString())
.put("index.analysis.filter.synonyms1.type", "synonym")
.putList("index.analysis.filter.synonyms1.synonyms", "term1, term2")
.put("index.analysis.filter.synonyms2.type", "synonym")
.putList("index.analysis.filter.synonyms2.synonyms", "term1, term3")
.put("index.analysis.analyzer.syn.tokenizer", "standard")
.putList("index.analysis.analyzer.syn.filter", "lowercase", "synonyms1", "synonyms2")
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
BaseTokenStreamTestCase.assertAnalyzesTo(
indexAnalyzers.get("syn"),
"term1",
new String[] { "term1", "term3", "term2" },
new int[] { 1, 0, 0 }
);
}
public void testShingleFilters() {
Settings settings = Settings.builder()
.put(
IndexMetadata.SETTING_VERSION_CREATED,
IndexVersionUtils.randomVersionBetween(random(), IndexVersions.MINIMUM_READONLY_COMPATIBLE, IndexVersion.current())
)
.put("path.home", createTempDir().toString())
.put("index.analysis.filter.synonyms.type", "synonym")
.putList("index.analysis.filter.synonyms.synonyms", "programmer, developer")
.put("index.analysis.filter.my_shingle.type", "shingle")
.put("index.analysis.analyzer.my_analyzer.tokenizer", "standard")
.putList("index.analysis.analyzer.my_analyzer.filter", "my_shingle", "synonyms")
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
expectThrows(IllegalArgumentException.class, () -> {
indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
});
}
public void testTokenFiltersBypassSynonymAnalysis() throws IOException {
Settings settings = Settings.builder()
.put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current())
.put("path.home", createTempDir().toString())
.putList("word_list", "a")
.put("hyphenation_patterns_path", "foo")
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
String[] bypassingFactories = new String[] { "dictionary_decompounder" };
CommonAnalysisPlugin plugin = new CommonAnalysisPlugin();
for (String factory : bypassingFactories) {
TokenFilterFactory tff = plugin.getTokenFilters().get(factory).get(idxSettings, null, factory, settings);
TokenizerFactory tok = new KeywordTokenizerFactory(idxSettings, null, "keyword", settings);
Analyzer analyzer = SynonymTokenFilterFactory.buildSynonymAnalyzer(
tok,
Collections.emptyList(),
Collections.singletonList(tff)
);
try (TokenStream ts = analyzer.tokenStream("field", "text")) {
assertThat(ts, instanceOf(KeywordTokenizer.class));
}
}
}
public void testPreconfiguredTokenFilters() throws IOException {
Set<String> disallowedFilters = new HashSet<>(
Arrays.asList("common_grams", "edge_ngram", "keyword_repeat", "ngram", "shingle", "word_delimiter", "word_delimiter_graph")
);
Settings settings = Settings.builder()
.put(
IndexMetadata.SETTING_VERSION_CREATED,
IndexVersionUtils.randomVersionBetween(random(), IndexVersions.MINIMUM_READONLY_COMPATIBLE, IndexVersion.current())
)
.put("path.home", createTempDir().toString())
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
Set<String> disallowedFiltersTested = new HashSet<String>();
try (CommonAnalysisPlugin plugin = new CommonAnalysisPlugin()) {
for (PreConfiguredTokenFilter tf : plugin.getPreConfiguredTokenFilters()) {
if (disallowedFilters.contains(tf.getName())) {
IllegalArgumentException e = expectThrows(
IllegalArgumentException.class,
"Expected exception for factory " + tf.getName(),
() -> {
tf.get(idxSettings, null, tf.getName(), settings).getSynonymFilter();
}
);
assertEquals(tf.getName(), "Token filter [" + tf.getName() + "] cannot be used to parse synonyms", e.getMessage());
disallowedFiltersTested.add(tf.getName());
} else {
tf.get(idxSettings, null, tf.getName(), settings).getSynonymFilter();
}
}
}
assertEquals("Set of dissallowed filters contains more filters than tested", disallowedFiltersTested, disallowedFilters);
}
public void testDisallowedTokenFilters() throws IOException {
Settings settings = Settings.builder()
.put(
IndexMetadata.SETTING_VERSION_CREATED,
IndexVersionUtils.randomVersionBetween(random(), IndexVersions.MINIMUM_READONLY_COMPATIBLE, IndexVersion.current())
)
.put("path.home", createTempDir().toString())
.putList("common_words", "a", "b")
.put("output_unigrams", "true")
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
CommonAnalysisPlugin plugin = new CommonAnalysisPlugin();
String[] disallowedFactories = new String[] {
"multiplexer",
"cjk_bigram",
"common_grams",
"ngram",
"edge_ngram",
"word_delimiter",
"word_delimiter_graph",
"fingerprint" };
for (String factory : disallowedFactories) {
TokenFilterFactory tff = plugin.getTokenFilters().get(factory).get(idxSettings, null, factory, settings);
TokenizerFactory tok = new KeywordTokenizerFactory(idxSettings, null, "keyword", settings);
IllegalArgumentException e = expectThrows(
IllegalArgumentException.class,
"Expected IllegalArgumentException for factory " + factory,
() -> SynonymTokenFilterFactory.buildSynonymAnalyzer(tok, Collections.emptyList(), Collections.singletonList(tff))
);
assertEquals(factory, "Token filter [" + factory + "] cannot be used to parse synonyms", e.getMessage());
}
}
private void match(String analyzerName, String source, String target) throws IOException {
Analyzer analyzer = indexAnalyzers.get(analyzerName).analyzer();
TokenStream stream = analyzer.tokenStream("", source);
stream.reset();
CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class);
StringBuilder sb = new StringBuilder();
while (stream.incrementToken()) {
sb.append(termAtt.toString()).append(" ");
}
MatcherAssert.assertThat(sb.toString().trim(), equalTo(target));
}
}
|
SynonymsAnalysisTests
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/CustomHttpOptionsViaInjectedRestClientTest.java
|
{
"start": 2729,
"end": 3137
}
|
class ____ implements ContextResolver<HttpClientOptions> {
@Override
public HttpClientOptions getContext(Class<?> aClass) {
HttpClientOptions options = new HttpClientOptions();
options.setMaxHeaderSize(1); // this is just to verify that this HttpClientOptions is indeed used.
return options;
}
}
public static
|
CustomHttpClientOptionsWithLimit
|
java
|
netty__netty
|
handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslServerContext.java
|
{
"start": 12505,
"end": 13886
}
|
class ____ implements CertificateCallback {
private final Map<Long, ReferenceCountedOpenSslEngine> engines;
private final OpenSslKeyMaterialManager keyManagerHolder;
OpenSslServerCertificateCallback(Map<Long, ReferenceCountedOpenSslEngine> engines,
OpenSslKeyMaterialManager keyManagerHolder) {
this.engines = engines;
this.keyManagerHolder = keyManagerHolder;
}
@Override
public void handle(long ssl, byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals) throws Exception {
final ReferenceCountedOpenSslEngine engine = engines.get(ssl);
if (engine == null) {
// Maybe null if destroyed in the meantime.
return;
}
try {
// For now we just ignore the asn1DerEncodedPrincipals as this is kind of inline with what the
// OpenJDK SSLEngineImpl does.
keyManagerHolder.setKeyMaterialServerSide(engine);
} catch (Throwable cause) {
engine.initHandshakeException(cause);
if (cause instanceof Exception) {
throw (Exception) cause;
}
throw new SSLException(cause);
}
}
}
private static final
|
OpenSslServerCertificateCallback
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.java
|
{
"start": 21108,
"end": 21415
}
|
class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.securityMatcher(new RegexRequestMatcher("/regex/.*", null));
return http.build();
// @formatter:on
}
}
@Configuration
@EnableWebSecurity
static
|
RequestMatcherRegexConfig
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/NodeAllocationInfo.java
|
{
"start": 1376,
"end": 2300
}
|
class ____ {
private String partition;
private String updatedContainerId;
private String finalAllocationState;
private ActivityNodeInfo root = null;
private static final Logger LOG =
LoggerFactory.getLogger(NodeAllocationInfo.class);
NodeAllocationInfo() {
}
NodeAllocationInfo(NodeAllocation allocation,
RMWSConsts.ActivitiesGroupBy groupBy) {
this.partition = allocation.getPartition();
this.updatedContainerId = allocation.getContainerId();
this.finalAllocationState = allocation.getFinalAllocationState().name();
root = new ActivityNodeInfo(allocation.getRoot(), groupBy);
}
public String getPartition() {
return partition;
}
public String getUpdatedContainerId() {
return updatedContainerId;
}
public String getFinalAllocationState() {
return finalAllocationState;
}
public ActivityNodeInfo getRoot() {
return root;
}
}
|
NodeAllocationInfo
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/validators/ParamValidationCheckerTest.java
|
{
"start": 67631,
"end": 67800
}
|
class ____ a placeholder default value
}
@Override
public String toString() {
return "NeverSingle";
}
}
static final
|
is
|
java
|
elastic__elasticsearch
|
x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/saml/rest/action/IdpBaseRestHandlerTests.java
|
{
"start": 756,
"end": 2337
}
|
class ____ extends ESTestCase {
public void testIdpAvailableOnTrialOrEnterprise() {
final IdpBaseRestHandler handler = buildHandler(randomFrom(License.OperationMode.ENTERPRISE, License.OperationMode.TRIAL));
assertThat(handler.isIdpFeatureAllowed(), equalTo(true));
}
public void testIdpNotAvailableOnOtherLicenses() {
License.OperationMode mode = randomValueOtherThanMany(
m -> m == License.OperationMode.ENTERPRISE || m == License.OperationMode.TRIAL,
() -> randomFrom(License.OperationMode.values())
);
final IdpBaseRestHandler handler = buildHandler(mode);
assertThat(handler.isIdpFeatureAllowed(), equalTo(false));
}
private IdpBaseRestHandler buildHandler(License.OperationMode licenseMode) {
final Settings settings = Settings.builder().put("xpack.idp.enabled", true).build();
final TestUtils.UpdatableLicenseState licenseState = new TestUtils.UpdatableLicenseState(settings);
licenseState.update(new XPackLicenseStatus(licenseMode, true, null));
return new IdpBaseRestHandler(licenseState) {
@Override
protected RestChannelConsumer innerPrepareRequest(RestRequest request, NodeClient client) throws IOException {
return null;
}
@Override
public String getName() {
return "idp-rest-test";
}
@Override
public List<Route> routes() {
return List.of();
}
};
}
}
|
IdpBaseRestHandlerTests
|
java
|
apache__kafka
|
storage/src/main/java/org/apache/kafka/server/log/remote/metadata/storage/BrokerReadyCallback.java
|
{
"start": 929,
"end": 1167
}
|
interface ____ {
/**
* This method will be called during broker startup for the implementation,
* which needs delayed initialization until the broker can process requests.
*/
void onBrokerReady();
}
|
BrokerReadyCallback
|
java
|
elastic__elasticsearch
|
test/framework/src/main/java/org/elasticsearch/datageneration/matchers/ArrayEqualMatcher.java
|
{
"start": 843,
"end": 3785
}
|
class ____ extends GenericEqualsMatcher<Object[]> {
ArrayEqualMatcher(
final XContentBuilder actualMappings,
final Settings.Builder actualSettings,
final XContentBuilder expectedMappings,
final Settings.Builder expectedSettings,
final Object[] actual,
final Object[] expected,
boolean ignoringSort
) {
super(actualMappings, actualSettings, expectedMappings, expectedSettings, actual, expected, ignoringSort);
}
@Override
public MatchResult match() {
return matchArraysEqual(actual, expected, ignoringSort);
}
private MatchResult matchArraysEqual(final Object[] actualArray, final Object[] expectedArray, boolean ignoreSorting) {
if (actualArray.length != expectedArray.length) {
return MatchResult.noMatch(
formatErrorMessage(
actualMappings,
actualSettings,
expectedMappings,
expectedSettings,
"Array lengths do no match, " + prettyPrintArrays(actualArray, expectedArray)
)
);
}
if (ignoreSorting) {
return matchArraysEqualIgnoringSorting(actualArray, expectedArray)
? MatchResult.match()
: MatchResult.noMatch(
formatErrorMessage(
actualMappings,
actualSettings,
expectedMappings,
expectedSettings,
"Arrays do not match when ignoring sort order, " + prettyPrintArrays(actualArray, expectedArray)
)
);
} else {
return matchArraysEqualExact(actualArray, expectedArray)
? MatchResult.match()
: MatchResult.noMatch(
formatErrorMessage(
actualMappings,
actualSettings,
expectedMappings,
expectedSettings,
"Arrays do not match exactly, " + prettyPrintArrays(actualArray, expectedArray)
)
);
}
}
private static boolean matchArraysEqualIgnoringSorting(final Object[] actualArray, final Object[] expectedArray) {
final List<Object> actualList = Arrays.asList(actualArray);
final List<Object> expectedList = Arrays.asList(expectedArray);
return actualList.containsAll(expectedList) && expectedList.containsAll(actualList);
}
private static <T> boolean matchArraysEqualExact(T[] actualArray, T[] expectedArray) {
for (int i = 0; i < actualArray.length; i++) {
boolean isEqual = actualArray[i].equals(expectedArray[i]);
if (isEqual == false) {
return false;
}
}
return true;
}
}
|
ArrayEqualMatcher
|
java
|
apache__kafka
|
clients/src/test/java/org/apache/kafka/common/utils/SanitizerTest.java
|
{
"start": 1317,
"end": 2969
}
|
class ____ {
@Test
public void testSanitize() {
String principal = "CN=Some characters !@#$%&*()_-+=';:,/~";
String sanitizedPrincipal = Sanitizer.sanitize(principal);
assertTrue(sanitizedPrincipal.replace('%', '_').matches("[a-zA-Z0-9\\._\\-]+"));
assertEquals(principal, Sanitizer.desanitize(sanitizedPrincipal));
}
@Test
public void testJmxSanitize() throws MalformedObjectNameException {
int unquoted = 0;
for (int i = 0; i < 65536; i++) {
char c = (char) i;
String value = "value" + c;
String jmxSanitizedValue = Sanitizer.jmxSanitize(value);
if (jmxSanitizedValue.equals(value))
unquoted++;
verifyJmx(jmxSanitizedValue, i);
String encodedValue = Sanitizer.sanitize(value);
verifyJmx(encodedValue, i);
// jmxSanitize should not sanitize URL-encoded values
assertEquals(encodedValue, Sanitizer.jmxSanitize(encodedValue));
}
assertEquals(68, unquoted); // a-zA-Z0-9-_% space and tab
}
private void verifyJmx(String sanitizedValue, int c) throws MalformedObjectNameException {
Object mbean = new TestStat();
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName = new ObjectName("test:key=" + sanitizedValue);
try {
server.registerMBean(mbean, objectName);
server.unregisterMBean(objectName);
} catch (OperationsException | MBeanException e) {
fail("Could not register char=\\u" + c);
}
}
public
|
SanitizerTest
|
java
|
quarkusio__quarkus
|
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/subresource/PingResource.java
|
{
"start": 111,
"end": 245
}
|
class ____ {
@Inject
MyService service;
@GET
public String ping() {
return service.ping();
}
}
|
PingResource
|
java
|
elastic__elasticsearch
|
libs/core/src/test/java/org/elasticsearch/core/internal/provider/EmbeddedModulePathTests.java
|
{
"start": 1878,
"end": 3140
}
|
class ____ extends ESTestCase {
static final Class<IllegalArgumentException> IAE = IllegalArgumentException.class;
public void testVersion() {
Optional<Version> over;
over = EmbeddedModulePath.version("foo.jar");
assertThat(over, isEmpty());
over = EmbeddedModulePath.version("foo-1.2.jar");
assertThat(over, isPresentWith(Version.parse("1.2")));
over = EmbeddedModulePath.version("foo-bar-1.2.3-SNAPSHOT.jar");
assertThat(over, isPresentWith(Version.parse("1.2.3-SNAPSHOT")));
over = EmbeddedModulePath.version("elasticsearch-8.3.0-SNAPSHOT.jar");
assertThat(over, isPresentWith(Version.parse("8.3.0-SNAPSHOT")));
expectThrows(IAE, () -> EmbeddedModulePath.version(""));
expectThrows(IAE, () -> EmbeddedModulePath.version("foo"));
expectThrows(IAE, () -> EmbeddedModulePath.version("foo."));
expectThrows(IAE, () -> EmbeddedModulePath.version("foo.ja"));
}
public void testExplicitModuleDescriptorForEmbeddedJar() throws Exception {
Map<String, CharSequence> sources = new HashMap<>();
sources.put("module-info", "module m { exports p; opens q; }");
sources.put("p.Foo", "package p; public
|
EmbeddedModulePathTests
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
|
{
"start": 16371,
"end": 17765
}
|
class ____ implements WeightLoadable {
private final String id;
private final SlotSharingGroup slotSharingGroup;
private final Set<ExecutionVertexID> containedExecutionVertices;
public ExecutionSlotSharingGroup(
SlotSharingGroup slotSharingGroup,
Set<ExecutionVertexID> containedExecutionVertices) {
this(UUID.randomUUID().toString(), slotSharingGroup, containedExecutionVertices);
}
public ExecutionSlotSharingGroup(
String id,
SlotSharingGroup slotSharingGroup,
Set<ExecutionVertexID> containedExecutionVertices) {
this.id = id;
this.slotSharingGroup = Preconditions.checkNotNull(slotSharingGroup);
this.containedExecutionVertices = containedExecutionVertices;
}
@VisibleForTesting
public SlotSharingGroup getSlotSharingGroup() {
return slotSharingGroup;
}
public String getId() {
return id;
}
public Collection<ExecutionVertexID> getContainedExecutionVertices() {
return containedExecutionVertices;
}
@Nonnull
@Override
public LoadingWeight getLoading() {
return new DefaultLoadingWeight(containedExecutionVertices.size());
}
}
static
|
ExecutionSlotSharingGroup
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/http/FilterContainer.java
|
{
"start": 1054,
"end": 1327
}
|
class ____
* @param parameters a map from parameter names to initial values
*/
void addFilter(String name, String classname, Map<String, String> parameters);
/**
* Add a global filter to the container.
* @param name filter name
* @param classname filter
|
name
|
java
|
quarkusio__quarkus
|
extensions/infinispan-client/runtime/src/test/java/io/quarkus/infinispan/client/runtime/InfinispanServiceBindingConverterTest.java
|
{
"start": 797,
"end": 3239
}
|
class ____ {
private final static Path rootPath = Paths.get("src/test/resources/service-binding");
private final static String BINDING_DIRECTORY_ALL_PROPS = "all-props";
private final static String BINDING_DIRECTORY_NO_PROPS = "no-props";
private static final String EXPECTED_USERNAME = "someadmin";
private static final String EXPECTED_PASSWORD = "infiniforever";
private static final String EXPECTED_HOSTS = "infinispan.forever.com:11222";
private static final String EXPECTED_URI = "hotrod://admin:password@infinispan.forever.com:11222";
@Test
public void testBindingWithAllProperties() {
String bindingDirectory = BINDING_DIRECTORY_ALL_PROPS;
ServiceBinding serviceBinding = new ServiceBinding(rootPath.resolve(bindingDirectory));
assertThat(serviceBinding.getName()).isEqualTo(bindingDirectory);
assertThat(serviceBinding.getType()).isEqualTo("infinispan");
assertThat(serviceBinding.getProvider()).isEqualTo("coco");
assertThat(serviceBinding.getProperties().get(INFINISPAN_USE_AUTH)).isEqualTo("true");
assertThat(serviceBinding.getProperties().get(INFINISPAN_USERNAME)).isEqualTo(EXPECTED_USERNAME);
assertThat(serviceBinding.getProperties().get(INFINISPAN_PASSWORD)).isEqualTo(EXPECTED_PASSWORD);
assertThat(serviceBinding.getProperties().get(INFINISPAN_HOSTS)).isEqualTo(EXPECTED_HOSTS);
assertThat(serviceBinding.getProperties().get(INFINISPAN_URI)).isEqualTo(EXPECTED_URI);
}
@Test
public void testBindingWithMissingProperties() {
String bindingDirectory = BINDING_DIRECTORY_NO_PROPS;
ServiceBinding serviceBinding = new ServiceBinding(rootPath.resolve(bindingDirectory));
assertThat(serviceBinding.getName()).isEqualTo(bindingDirectory);
assertThat(serviceBinding.getType()).isEqualTo("infinispan");
assertThat(serviceBinding.getProvider()).isNull();
assertThat(serviceBinding.getProperties().containsKey(INFINISPAN_USE_AUTH)).isFalse();
assertThat(serviceBinding.getProperties().containsKey(INFINISPAN_USERNAME)).isFalse();
assertThat(serviceBinding.getProperties().containsKey(INFINISPAN_PASSWORD)).isFalse();
assertThat(serviceBinding.getProperties().containsKey(INFINISPAN_HOSTS)).isFalse();
assertThat(serviceBinding.getProperties().containsKey(INFINISPAN_URI)).isFalse();
}
}
|
InfinispanServiceBindingConverterTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/event/internal/EntityState.java
|
{
"start": 328,
"end": 2613
}
|
enum ____ {
PERSISTENT, TRANSIENT, DETACHED, DELETED;
/**
* Determine whether the entity is persistent, detached, or transient
*
* @param entity The entity to check
* @param entityName The name of the entity
* @param entry The entity's entry in the persistence context
* @param source The originating session.
*
* @return The state.
*/
public static EntityState getEntityState(
Object entity,
String entityName,
EntityEntry entry, //pass this as an argument only to avoid double looking
SessionImplementor source,
Boolean assumedUnsaved) {
if ( entry != null ) { // the object is persistent
//the entity is associated with the session, so check its status
if ( entry.getStatus() != Status.DELETED ) {
// do nothing for persistent instances
// if ( EVENT_LISTENER_LOGGER.isTraceEnabled() ) {
// EVENT_LISTENER_LOGGER.persistentInstance( getLoggableName( entityName, entity ) );
// }
return PERSISTENT;
}
else {
// must be deleted instance
// if ( EVENT_LISTENER_LOGGER.isTraceEnabled() ) {
// EVENT_LISTENER_LOGGER.deletedInstance( getLoggableName( entityName, entity ) );
// }
return DELETED;
}
}
// the object is transient or detached
// the entity is not associated with the session, so
// try interceptor and unsaved-value
else if ( ForeignKeys.isTransient( entityName, entity, assumedUnsaved, source ) ) {
// if ( EVENT_LISTENER_LOGGER.isTraceEnabled() ) {
// EVENT_LISTENER_LOGGER.transientInstance( getLoggableName( entityName, entity ) );
// }
return TRANSIENT;
}
else {
// if ( EVENT_LISTENER_LOGGER.isTraceEnabled() ) {
// EVENT_LISTENER_LOGGER.detachedInstance( getLoggableName( entityName, entity ) );
// }
final var persistenceContext = source.getPersistenceContextInternal();
if ( persistenceContext.containsDeletedUnloadedEntityKeys() ) {
final var entityPersister = source.getEntityPersister( entityName, entity );
final Object identifier = entityPersister.getIdentifier( entity, source );
final var entityKey = source.generateEntityKey( identifier, entityPersister );
if ( persistenceContext.containsDeletedUnloadedEntityKey( entityKey ) ) {
return EntityState.DELETED;
}
}
return DETACHED;
}
}
}
|
EntityState
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/search/sort/BucketedSort.java
|
{
"start": 15977,
"end": 17894
}
|
class ____ extends BucketedSort {
private DoubleArray values;
@SuppressWarnings("this-escape")
public ForDoubles(BigArrays bigArrays, SortOrder sortOrder, DocValueFormat format, int bucketSize, ExtraData extra) {
super(bigArrays, sortOrder, format, bucketSize, extra);
boolean success = false;
try {
values = bigArrays.newDoubleArray(getBucketSize(), false);
success = true;
} finally {
if (success == false) {
close();
}
}
initGatherOffsets();
}
@Override
public boolean needsScores() {
return false;
}
@Override
protected final BigArray values() {
return values;
}
@Override
protected final void growValues(long minSize) {
values = bigArrays.grow(values, minSize);
}
@Override
protected final int getNextGatherOffset(long rootIndex) {
// This cast is safe because all ints fit accurately into a double.
return (int) values.get(rootIndex);
}
@Override
protected final void setNextGatherOffset(long rootIndex, int offset) {
values.set(rootIndex, offset);
}
@Override
protected final SortValue getValue(long index) {
return SortValue.from(values.get(index));
}
@Override
protected final boolean betterThan(long lhs, long rhs) {
return getOrder().reverseMul() * Double.compare(values.get(lhs), values.get(rhs)) < 0;
}
@Override
protected final void swap(long lhs, long rhs) {
double tmp = values.get(lhs);
values.set(lhs, values.get(rhs));
values.set(rhs, tmp);
}
protected abstract
|
ForDoubles
|
java
|
elastic__elasticsearch
|
x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/saml/rest/action/RestSamlMetadataAction.java
|
{
"start": 967,
"end": 2299
}
|
class ____ extends IdpBaseRestHandler {
public RestSamlMetadataAction(XPackLicenseState licenseState) {
super(licenseState);
}
@Override
public String getName() {
return "saml_metadata_action";
}
@Override
public List<Route> routes() {
return List.of(new Route(GET, "/_idp/saml/metadata/{sp_entity_id}"));
}
@Override
protected RestChannelConsumer innerPrepareRequest(RestRequest request, NodeClient client) throws IOException {
final String spEntityId = request.param("sp_entity_id");
final String acs = request.param("acs");
final SamlMetadataRequest metadataRequest = new SamlMetadataRequest(spEntityId, acs);
return channel -> client.execute(
SamlMetadataAction.INSTANCE,
metadataRequest,
new RestBuilderListener<SamlMetadataResponse>(channel) {
@Override
public RestResponse buildResponse(SamlMetadataResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
builder.field("metadata", response.getXmlString());
builder.endObject();
return new RestResponse(RestStatus.OK, builder);
}
}
);
}
}
|
RestSamlMetadataAction
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/tofix/JsonIdentityInfoAndBackReferences3964Test.java
|
{
"start": 616,
"end": 911
}
|
class ____ extends DatabindTestUtil {
/**
* Fails : Original test
*/
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id",
scope = Tree.class
)
public static
|
JsonIdentityInfoAndBackReferences3964Test
|
java
|
apache__camel
|
components/camel-jms/src/main/java/org/apache/camel/component/jms/reply/SharedQueueMessageListenerContainer.java
|
{
"start": 1594,
"end": 3111
}
|
class ____ extends DefaultJmsMessageListenerContainer {
private String fixedMessageSelector;
private MessageSelectorCreator creator;
/**
* Use a fixed JMS message selector
*
* @param endpoint the endpoint
* @param fixedMessageSelector the fixed selector
*/
public SharedQueueMessageListenerContainer(JmsEndpoint endpoint, String fixedMessageSelector) {
super(endpoint, endpoint.isAllowReplyManagerQuickStop());
this.fixedMessageSelector = fixedMessageSelector;
// must use cache level consumer for fixed message selector
setCacheLevel(DefaultMessageListenerContainer.CACHE_CONSUMER);
}
/**
* Use a dynamic JMS message selector
*
* @param endpoint the endpoint
* @param creator the creator to create the dynamic selector
*/
public SharedQueueMessageListenerContainer(JmsEndpoint endpoint, MessageSelectorCreator creator) {
super(endpoint, endpoint.isAllowReplyManagerQuickStop());
this.creator = creator;
// must use cache level session for dynamic message selector,
// as otherwise the dynamic message selector will not be updated on-the-fly
setCacheLevel(DefaultMessageListenerContainer.CACHE_SESSION);
}
// override this method and return the appropriate selector
@Override
public String getMessageSelector() {
return JmsReplyHelper.getMessageSelector(fixedMessageSelector, creator);
}
}
|
SharedQueueMessageListenerContainer
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/cache/interceptor/CacheEvaluationContextFactory.java
|
{
"start": 1204,
"end": 2610
}
|
class ____ {
private final StandardEvaluationContext originalContext;
private @Nullable Supplier<ParameterNameDiscoverer> parameterNameDiscoverer;
CacheEvaluationContextFactory(StandardEvaluationContext originalContext) {
this.originalContext = originalContext;
}
public void setParameterNameDiscoverer(Supplier<ParameterNameDiscoverer> parameterNameDiscoverer) {
this.parameterNameDiscoverer = parameterNameDiscoverer;
}
public ParameterNameDiscoverer getParameterNameDiscoverer() {
if (this.parameterNameDiscoverer == null) {
this.parameterNameDiscoverer = SingletonSupplier.of(new DefaultParameterNameDiscoverer());
}
return this.parameterNameDiscoverer.get();
}
/**
* Creates a {@link CacheEvaluationContext} for the specified operation.
* @param rootObject the {@code root} object to use for the context
* @param targetMethod the target cache {@link Method}
* @param args the arguments of the method invocation
* @return a context suitable for this cache operation
*/
public CacheEvaluationContext forOperation(CacheExpressionRootObject rootObject,
Method targetMethod, @Nullable Object[] args) {
CacheEvaluationContext evaluationContext = new CacheEvaluationContext(
rootObject, targetMethod, args, getParameterNameDiscoverer());
this.originalContext.applyDelegatesTo(evaluationContext);
return evaluationContext;
}
}
|
CacheEvaluationContextFactory
|
java
|
FasterXML__jackson-core
|
src/test/java/tools/jackson/core/unittest/io/schubfach/FloatToDecimalTest.java
|
{
"start": 399,
"end": 3698
}
|
class ____ {
/*
MIN_NORMAL is incorrectly rendered by the JDK.
*/
@Test
void extremeValues() {
toDec(Float.NEGATIVE_INFINITY);
toDec(-Float.MAX_VALUE);
toDec(-Float.MIN_NORMAL);
toDec(-Float.MIN_VALUE);
toDec(-0.0f);
toDec(0.0f);
toDec(Float.MIN_VALUE);
toDec(Float.MIN_NORMAL);
toDec(Float.MAX_VALUE);
toDec(Float.POSITIVE_INFINITY);
toDec(Float.NaN);
/*
Quiet NaNs have the most significant bit of the mantissa as 1,
while signaling NaNs have it as 0.
Exercise 4 combinations of quiet/signaling NaNs and
"positive/negative" NaNs.
*/
toDec(intBitsToFloat(0x7FC0_0001));
toDec(intBitsToFloat(0x7F80_0001));
toDec(intBitsToFloat(0xFFC0_0001));
toDec(intBitsToFloat(0xFF80_0001));
/*
All values treated specially by Schubfach
*/
for (int c = 1; c < C_TINY; ++c) {
toDec(c * Float.MIN_VALUE);
}
}
/*
Some "powers of 10" are incorrectly rendered by the JDK.
The rendering is either too long or it is not the closest decimal.
*/
@Test
void powersOf10() {
for (int e = E_MIN; e <= E_MAX; ++e) {
toDec(Float.parseFloat("1e" + e));
}
}
/*
Many powers of 2 are incorrectly rendered by the JDK.
The rendering is either too long or it is not the closest decimal.
*/
@Test
void powersOf2() {
for (float v = Float.MIN_VALUE; v <= Float.MAX_VALUE; v *= 2) {
toDec(v);
}
}
@Test
void constants() {
assertEquals(FloatToDecimal.P, P, "P");
assertEquals(C_MIN, (long) (float) C_MIN, "C_MIN");
assertEquals(C_MAX, (long) (float) C_MAX, "C_MAX");
assertEquals(Float.MIN_VALUE, MIN_VALUE, "MIN_VALUE");
assertEquals(Float.MIN_NORMAL, MIN_NORMAL, "MIN_NORMAL");
assertEquals(Float.MAX_VALUE, MAX_VALUE, "MAX_VALUE");
assertEquals(FloatToDecimal.Q_MIN, Q_MIN, "Q_MIN");
assertEquals(FloatToDecimal.Q_MAX, Q_MAX, "Q_MAX");
assertEquals(FloatToDecimal.K_MIN, K_MIN, "K_MIN");
assertEquals(FloatToDecimal.K_MAX, K_MAX, "K_MAX");
assertEquals(FloatToDecimal.H, H, "H");
assertEquals(FloatToDecimal.E_MIN, E_MIN, "E_MIN");
assertEquals(FloatToDecimal.E_MAX, E_MAX, "E_MAX");
assertEquals(FloatToDecimal.C_TINY, C_TINY, "C_TINY");
}
@Test
void someAnomalies() {
for (String dec : Anomalies) {
toDec(Float.parseFloat(dec));
}
}
@Test
void paxson() {
for (int i = 0; i < PaxsonSignificands.length; ++i) {
toDec(scalb(PaxsonSignificands[i], PaxsonExponents[i]));
}
}
/*
Tests all positive integers below 2^23.
These are all exact floats and exercise the fast path.
*/
@Test
void ints() {
// 29-Nov-2022, tatu: Reduce from original due to slowness
// for (int i = 1; i < 1 << P - 1; ++i) {
for (int i = 1; i < 1 << P - 1; i += 3) {
toDec(i);
}
}
@Test
void randomNumberTests() {
FloatToDecimalChecker.randomNumberTests(1_000_000, new Random());
}
}
|
FloatToDecimalTest
|
java
|
netty__netty
|
codec-http/src/main/java/io/netty/handler/codec/http/multipart/DeleteFileOnExitHook.java
|
{
"start": 814,
"end": 2183
}
|
class ____ {
private static final Set<String> FILES = ConcurrentHashMap.newKeySet();
private DeleteFileOnExitHook() {
}
static {
// DeleteOnExitHook must be the last shutdown hook to be invoked.
// Application shutdown hooks may add the first file to the
// delete on exit list and cause the DeleteOnExitHook to be
// registered during shutdown in progress.
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
runHook();
}
});
}
/**
* Remove from the pool to reduce space footprint.
*
* @param file tmp file path
*/
public static void remove(String file) {
FILES.remove(file);
}
/**
* Add to the hook and clean up when the program exits.
*
* @param file tmp file path
*/
public static void add(String file) {
FILES.add(file);
}
/**
* Check in the hook files.
*
* @param file target file
* @return true or false
*/
public static boolean checkFileExist(String file) {
return FILES.contains(file);
}
/**
* Clean up all the files.
*/
static void runHook() {
for (String filename : FILES) {
new File(filename).delete();
}
}
}
|
DeleteFileOnExitHook
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/deser/DoubleDeserializerTest.java
|
{
"start": 363,
"end": 1201
}
|
class ____ extends TestCase {
public void test_bigdecimal() throws Exception {
Assert.assertEquals(0, JSON.parseObject("0", Double.class).intValue());
Assert.assertEquals(0, JSON.parseObject("0.0", Double.class).intValue());
Assert.assertEquals(0, JSON.parseObject("'0'", Double.class).intValue());
Assert.assertEquals(0, JSON.parseObject("'0'", double.class).intValue());
Assert.assertEquals(null, JSON.parseObject("null", Double.class));
DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE);
Assert.assertEquals(null, NumberDeserializer.instance.deserialze(parser, null, null));
Assert.assertEquals(JSONToken.LITERAL_INT, NumberDeserializer.instance.getFastMatchToken());
}
}
|
DoubleDeserializerTest
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/context/annotation/ParserStrategyUtilsTests.java
|
{
"start": 7763,
"end": 7979
}
|
class ____ {
MultipleConstructorsWithNoDefault(Environment environment, BeanFactory beanFactory) {
}
MultipleConstructorsWithNoDefault(Environment environment) {
}
}
static
|
MultipleConstructorsWithNoDefault
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHtmlQuoting.java
|
{
"start": 1205,
"end": 3690
}
|
class ____ {
@Test public void testNeedsQuoting() throws Exception {
assertTrue(HtmlQuoting.needsQuoting("abcde>"));
assertTrue(HtmlQuoting.needsQuoting("<abcde"));
assertTrue(HtmlQuoting.needsQuoting("abc'de"));
assertTrue(HtmlQuoting.needsQuoting("abcde\""));
assertTrue(HtmlQuoting.needsQuoting("&"));
assertFalse(HtmlQuoting.needsQuoting(""));
assertFalse(HtmlQuoting.needsQuoting("ab\ncdef"));
assertFalse(HtmlQuoting.needsQuoting(null));
}
@Test public void testQuoting() throws Exception {
assertEquals("ab<cd", HtmlQuoting.quoteHtmlChars("ab<cd"));
assertEquals("ab>", HtmlQuoting.quoteHtmlChars("ab>"));
assertEquals("&&&", HtmlQuoting.quoteHtmlChars("&&&"));
assertEquals(" '\n", HtmlQuoting.quoteHtmlChars(" '\n"));
assertEquals(""", HtmlQuoting.quoteHtmlChars("\""));
assertEquals(null, HtmlQuoting.quoteHtmlChars(null));
}
private void runRoundTrip(String str) throws Exception {
assertEquals(str,
HtmlQuoting.unquoteHtmlChars(HtmlQuoting.quoteHtmlChars(str)));
}
@Test public void testRoundtrip() throws Exception {
runRoundTrip("");
runRoundTrip("<>&'\"");
runRoundTrip("ab>cd<ef&ghi'\"");
runRoundTrip("A string\n with no quotable chars in it!");
runRoundTrip(null);
StringBuilder buffer = new StringBuilder();
for(char ch=0; ch < 127; ++ch) {
buffer.append(ch);
}
runRoundTrip(buffer.toString());
}
@Test
public void testRequestQuoting() throws Exception {
HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
HttpServer2.QuotingInputFilter.RequestQuoter quoter =
new HttpServer2.QuotingInputFilter.RequestQuoter(mockReq);
Mockito.doReturn("a<b").when(mockReq).getParameter("x");
assertEquals("a<b", quoter.getParameter("x"), "Test simple param quoting");
Mockito.doReturn(null).when(mockReq).getParameter("x");
assertEquals(null, quoter.getParameter("x"),
"Test that missing parameters dont cause NPE");
Mockito.doReturn(new String[]{"a<b", "b"}).when(mockReq).getParameterValues("x");
assertArrayEquals(new String[]{"a<b", "b"}, quoter.getParameterValues("x"),
"Test escaping of an array");
Mockito.doReturn(null).when(mockReq).getParameterValues("x");
assertArrayEquals(null, quoter.getParameterValues("x"),
"Test that missing parameters dont cause NPE for array");
}
}
|
TestHtmlQuoting
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.