language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__flink | flink-datastream-api/src/main/java/org/apache/flink/datastream/api/stream/KeyedPartitionStream.java | {
"start": 10173,
"end": 10394
} | interface ____<K, T>
extends KeyedPartitionStream<K, T>,
ProcessConfigurable<ProcessConfigurableAndKeyedPartitionStream<K, T>> {}
/**
* This | ProcessConfigurableAndKeyedPartitionStream |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ObjectsHashCodePrimitiveTest.java | {
"start": 2713,
"end": 3059
} | class ____ {
void f() {
short x = 3;
int y = Short.hashCode(x);
}
}
""")
.doTest();
}
@Test
public void hashCodeInt() {
helper
.addInputLines(
"Test.java",
"""
import java.util.Objects;
| Test |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/builditem/nativeimage/UnsafeAccessedFieldBuildItem.java | {
"start": 318,
"end": 760
} | class ____ extends MultiBuildItem {
final String declaringClass;
final String fieldName;
public UnsafeAccessedFieldBuildItem(String declaringClass, String fieldName) {
this.declaringClass = declaringClass;
this.fieldName = fieldName;
}
public String getDeclaringClass() {
return declaringClass;
}
public String getFieldName() {
return fieldName;
}
}
| UnsafeAccessedFieldBuildItem |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/type/temporal/AbstractParametersBuilder.java | {
"start": 466,
"end": 3452
} | class ____<V,D extends Data<V>,B extends AbstractParametersBuilder<V,D,B>> {
protected final Dialect dialect;
private final List<Parameter<V,D>> result = new ArrayList<>();
private final List<Class<? extends AbstractRemappingH2Dialect>> remappingDialectClasses = new ArrayList<>();
private ZoneId forcedJdbcTimeZone = null;
protected AbstractParametersBuilder(Dialect dialect) {
this.dialect = dialect;
// Always test without remapping
remappingDialectClasses.add( null );
}
public B skippedForDialects(List<Class<?>> dialectsToSkip, Consumer<B> ifNotSkipped) {
boolean skip = false;
for ( Class<?> dialectClass : dialectsToSkip ) {
if ( dialectClass.isInstance( dialect ) ) {
skip = true;
break;
}
}
if ( !skip ) {
ifNotSkipped.accept( thisAsB() );
}
return thisAsB();
}
public B skippedForDialects(Predicate<Dialect> skipPredicate, Consumer<B> ifNotSkipped) {
if ( !skipPredicate.test( dialect ) ) {
ifNotSkipped.accept( thisAsB() );
}
return thisAsB();
}
public B withForcedJdbcTimezone(String zoneIdString, Consumer<B> contributor) {
this.forcedJdbcTimeZone = ZoneId.of( zoneIdString );
try {
contributor.accept( thisAsB() );
}
finally {
this.forcedJdbcTimeZone = null;
}
return thisAsB();
}
@SafeVarargs
public final B alsoTestRemappingsWithH2(Class<? extends AbstractRemappingH2Dialect>... dialectClasses) {
if ( dialect instanceof H2Dialect && !( (H2Dialect) dialect ).hasOddDstBehavior() ) {
// Only test remappings with H2
Collections.addAll( remappingDialectClasses, dialectClasses );
}
return thisAsB();
}
protected final boolean isNanosecondPrecisionSupported() {
// This used to return true for H2Dialect, but as of 1.4.197 h2 does not use ns precision by default anymore.
// Bringing back ns precision would require timestamp(9) in the dialect class.
return false;
}
protected final B add(ZoneId defaultJvmTimeZone, D testData) {
for ( Class<? extends AbstractRemappingH2Dialect> remappingDialectClass : remappingDialectClasses ) {
addParam( defaultJvmTimeZone, forcedJdbcTimeZone, remappingDialectClass, testData );
}
if ( forcedJdbcTimeZone == null ) {
for ( ZoneId hibernateJdbcTimeZone : getHibernateJdbcTimeZonesToTest() ) {
addParam( defaultJvmTimeZone, hibernateJdbcTimeZone, null, testData );
}
}
return thisAsB();
}
private void addParam(
ZoneId defaultJvmTimeZone,
ZoneId forcedJdbcTimeZone,
Class<? extends AbstractRemappingH2Dialect> remappingDialectClass,
D testData) {
result.add( new Parameter<>(
new Environment( defaultJvmTimeZone, forcedJdbcTimeZone, remappingDialectClass ),
testData
) );
}
protected Iterable<? extends ZoneId> getHibernateJdbcTimeZonesToTest() {
return Arrays.asList( Timezones.ZONE_GMT, Timezones.ZONE_OSLO );
}
private B thisAsB() {
//noinspection unchecked
return (B) this;
}
public List<Parameter<V,D>> build() {
return result;
}
}
| AbstractParametersBuilder |
java | google__dagger | javatests/dagger/hilt/android/MultiTestRoot1Test.java | {
"start": 5213,
"end": 9064
} | interface ____ {
Qux getQux();
}
@Rule public HiltAndroidRule rule = new HiltAndroidRule(this);
@Inject Foo foo;
@Inject Qux qux;
@Inject Long longValue;
@Inject @MultiTestRootExternalModules.External String externalStrValue;
@BindValue
@Named(TEST_QUALIFIER)
String bindValueString = BIND_VALUE_STRING;
@Test
public void testInjectFromTestModule() throws Exception {
assertThat(foo).isNull();
setupComponent();
assertThat(foo).isNotNull();
assertThat(foo.value).isEqualTo(INT_VALUE);
}
@Test
public void testInjectFromNestedTestModule() throws Exception {
assertThat(longValue).isNull();
setupComponent();
assertThat(longValue).isNotNull();
assertThat(longValue).isEqualTo(LONG_VALUE);
}
@Test
public void testInjectFromExternalAppModule() throws Exception {
assertThat(externalStrValue).isNull();
setupComponent();
assertThat(externalStrValue).isNotNull();
assertThat(externalStrValue).isEqualTo(REPLACE_EXTERNAL_STR_VALUE);
assertThat(externalStrValue).isNotEqualTo(MultiTestRootExternalModules.EXTERNAL_STR_VALUE);
}
@Test
public void testInjectFromExternalActivityModule() throws Exception {
setupComponent();
ActivityController<TestActivity> ac = Robolectric.buildActivity(TestActivity.class);
assertThat(ac.get().externalLongValue).isNull();
ac.create();
assertThat(ac.get().externalLongValue).isNotNull();
assertThat(ac.get().externalLongValue).isEqualTo(REPLACE_EXTERNAL_LONG_VALUE);
assertThat(ac.get().externalLongValue)
.isNotEqualTo(MultiTestRootExternalModules.EXTERNAL_LONG_VALUE);
}
@Test
public void testInjectFromPkgPrivateTestModule() throws Exception {
assertThat(qux).isNull();
setupComponent();
assertThat(qux).isNotNull();
}
@Test
public void testLocalEntryPoint() throws Exception {
setupComponent();
Bar bar = EntryPoints.get(getApplicationContext(), BarEntryPoint.class).getBar();
assertThat(bar).isNotNull();
assertThat(bar.value).isEqualTo(STR_VALUE);
}
@Test
public void testLocalPkgPrivateEntryPoint() throws Exception {
setupComponent();
Qux qux = EntryPoints.get(getApplicationContext(), PkgPrivateQuxEntryPoint.class).getQux();
assertThat(qux).isNotNull();
}
@Test
public void testAndroidEntryPoint() throws Exception {
setupComponent();
ActivityController<TestActivity> ac = Robolectric.buildActivity(TestActivity.class);
assertThat(ac.get().baz).isNull();
ac.create();
assertThat(ac.get().baz).isNotNull();
assertThat(ac.get().baz.value).isEqualTo(LONG_VALUE);
}
@Test
public void testMissingMultiTestRoot2EntryPoint() throws Exception {
setupComponent();
ClassCastException exception =
assertThrows(
ClassCastException.class,
() -> EntryPoints.get(getApplicationContext(), MultiTestRoot2Test.BarEntryPoint.class));
assertThat(exception)
.hasMessageThat()
.isEqualTo(
"Cannot cast dagger.hilt.android.internal.testing.root."
+ "DaggerMultiTestRoot1Test_HiltComponents_SingletonC$SingletonCImpl"
+ " to dagger.hilt.android.MultiTestRoot2Test$BarEntryPoint");
}
@Test
public void testBindValueFieldIsProvided() throws Exception {
setupComponent();
assertThat(bindValueString).isEqualTo(BIND_VALUE_STRING);
assertThat(getBinding()).isEqualTo(BIND_VALUE_STRING);
}
@Test
public void testBindValueIsMutable() throws Exception {
setupComponent();
bindValueString = "newValue";
assertThat(getBinding()).isEqualTo("newValue");
}
void setupComponent() {
rule.inject();
}
private static String getBinding() {
return EntryPoints.get(getApplicationContext(), BindValueEntryPoint.class).bindValueString();
}
}
| PkgPrivateQuxEntryPoint |
java | apache__camel | components/camel-jandex/src/main/java/org/apache/camel/jandex/JandexPackageScanClassResolver.java | {
"start": 1745,
"end": 6171
} | class ____ extends DefaultPackageScanClassResolver {
private static final Logger LOG = LoggerFactory.getLogger(JandexPackageScanClassResolver.class);
private static final String INDEX = "classpath:META-INF/jandex.*";
private final List<Index> indexes = new ArrayList<>();
@Override
protected void doStart() throws Exception {
super.doStart();
PackageScanResourceResolver resolver = PluginHelper.getPackageScanResourceResolver(getCamelContext());
resolver.addClassLoader(getCamelContext().getApplicationContextClassLoader());
resolver.start();
var list = resolver.findResources(INDEX);
for (Resource res : list) {
if (res.getLocation().endsWith("jandex.idx")) {
try (InputStream is = res.getInputStream()) {
if (is != null) {
LOG.debug("Reading jandex.idx from: {}", res.getLocation());
Index index = new IndexReader(is).read();
indexes.add(index);
}
}
}
}
}
@Override
protected void doStop() throws Exception {
super.doStop();
indexes.clear();
}
@Override
protected void find(PackageScanFilter test, String packageName, ClassLoader loader, Set<Class<?>> classes) {
if (test instanceof AnnotatedWithPackageScanFilter ann) {
findByAnnotation(ann.getAnnotation(), classes);
}
if (test instanceof AnnotatedWithAnyPackageScanFilter ann) {
for (var c : ann.getAnnotations()) {
findByAnnotation(c, classes);
}
}
if (test instanceof AssignableToPackageScanFilter ann) {
for (var c : ann.getParents()) {
findBySubClass(c, classes);
}
}
}
private void findByAnnotation(Class<? extends Annotation> c, Set<Class<?>> classes) {
for (Index index : indexes) {
for (var ai : index.getAnnotations(c)) {
var at = ai.target();
if (at.kind() == AnnotationTarget.Kind.CLASS
&& at.asClass().nestingType() == ClassInfo.NestingType.TOP_LEVEL) {
if (!at.asClass().isAbstract()) {
String currentClass = at.asClass().name().toString();
for (ClassLoader cl : getClassLoaders()) {
try {
Class<?> clazz = cl.loadClass(currentClass);
classes.add(clazz);
break;
} catch (ClassNotFoundException e) {
// ignore
}
}
}
}
}
}
}
private void findBySubClass(Class<?> c, Set<Class<?>> classes) {
for (Index index : indexes) {
if (c.isInterface()) {
for (var ai : index.getAllKnownImplementations(c)) {
if (!ai.asClass().isAbstract()) {
String currentClass = ai.asClass().name().toString();
for (ClassLoader cl : getClassLoaders()) {
try {
Class<?> clazz = cl.loadClass(currentClass);
classes.add(clazz);
break;
} catch (ClassNotFoundException e) {
// ignore
}
}
}
}
} else {
for (var ai : index.getAllKnownSubclasses(c)) {
if (!ai.isAbstract()) {
String currentClass = ai.asClass().name().toString();
for (ClassLoader cl : getClassLoaders()) {
try {
Class<?> clazz = cl.loadClass(currentClass);
classes.add(clazz);
break;
} catch (ClassNotFoundException e) {
// ignore
}
}
}
}
}
}
}
}
| JandexPackageScanClassResolver |
java | elastic__elasticsearch | x-pack/plugin/migrate/src/main/java/org/elasticsearch/xpack/migrate/action/CopyLifecycleIndexMetadataAction.java | {
"start": 1014,
"end": 1393
} | class ____ extends ActionType<AcknowledgedResponse> {
public static final String NAME = "indices:admin/index/copy_lifecycle_index_metadata";
public static final ActionType<AcknowledgedResponse> INSTANCE = new CopyLifecycleIndexMetadataAction();
private CopyLifecycleIndexMetadataAction() {
super(NAME);
}
public static | CopyLifecycleIndexMetadataAction |
java | quarkusio__quarkus | extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/RandomPortTest.java | {
"start": 1406,
"end": 2157
} | class ____ {
@ConfigProperty(name = "quarkus.http.port")
String port;
public void route(@Observes Router router) {
router.route("/test").handler(new Handler<RoutingContext>() {
@Override
public void handle(RoutingContext event) {
event.response().end(System.getProperty("quarkus.http.test-port"));
}
});
router.route("/app").handler(new Handler<RoutingContext>() {
@Override
public void handle(RoutingContext event) {
event.response().end(ConfigProvider.getConfig().getValue("quarkus.http.port", String.class));
}
});
}
}
}
| AppClass |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java | {
"start": 1285,
"end": 9329
} | class ____ {
@Test
void findField() {
Field field = ReflectionUtils.findField(TestObjectSubclassWithPublicField.class, "publicField", String.class);
assertThat(field).isNotNull();
assertThat(field.getName()).isEqualTo("publicField");
assertThat(field.getType()).isEqualTo(String.class);
assertThat(Modifier.isPublic(field.getModifiers())).as("Field should be public.").isTrue();
field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "prot", String.class);
assertThat(field).isNotNull();
assertThat(field.getName()).isEqualTo("prot");
assertThat(field.getType()).isEqualTo(String.class);
assertThat(Modifier.isProtected(field.getModifiers())).as("Field should be protected.").isTrue();
field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class);
assertThat(field).isNotNull();
assertThat(field.getName()).isEqualTo("name");
assertThat(field.getType()).isEqualTo(String.class);
assertThat(Modifier.isPrivate(field.getModifiers())).as("Field should be private.").isTrue();
}
@Test
void setField() {
TestObjectSubclassWithNewField testBean = new TestObjectSubclassWithNewField();
Field field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class);
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, testBean, "FooBar");
assertThat(testBean.getName()).isNotNull();
assertThat(testBean.getName()).isEqualTo("FooBar");
ReflectionUtils.setField(field, testBean, null);
assertThat(testBean.getName()).isNull();
}
@Test
void invokeMethod() throws Exception {
String rob = "Rob Harrop";
TestObject bean = new TestObject();
bean.setName(rob);
Method getName = TestObject.class.getMethod("getName");
Method setName = TestObject.class.getMethod("setName", String.class);
Object name = ReflectionUtils.invokeMethod(getName, bean);
assertThat(name).as("Incorrect name returned").isEqualTo(rob);
String juergen = "Juergen Hoeller";
ReflectionUtils.invokeMethod(setName, bean, juergen);
assertThat(bean.getName()).as("Incorrect name set").isEqualTo(juergen);
}
@Test
void declaresException() throws Exception {
Method remoteExMethod = A.class.getDeclaredMethod("foo", Integer.class);
assertThat(ReflectionUtils.declaresException(remoteExMethod, RemoteException.class)).isTrue();
assertThat(ReflectionUtils.declaresException(remoteExMethod, ConnectException.class)).isTrue();
assertThat(ReflectionUtils.declaresException(remoteExMethod, NoSuchMethodException.class)).isFalse();
assertThat(ReflectionUtils.declaresException(remoteExMethod, Exception.class)).isFalse();
Method illegalExMethod = B.class.getDeclaredMethod("bar", String.class);
assertThat(ReflectionUtils.declaresException(illegalExMethod, IllegalArgumentException.class)).isTrue();
assertThat(ReflectionUtils.declaresException(illegalExMethod, NumberFormatException.class)).isTrue();
assertThat(ReflectionUtils.declaresException(illegalExMethod, IllegalStateException.class)).isFalse();
assertThat(ReflectionUtils.declaresException(illegalExMethod, Exception.class)).isFalse();
}
@Test
void copySrcToDestinationOfIncorrectClass() {
TestObject src = new TestObject();
String dest = new String();
assertThatIllegalArgumentException().isThrownBy(() ->
ReflectionUtils.shallowCopyFieldState(src, dest));
}
@Test
void rejectsNullSrc() {
TestObject src = null;
String dest = new String();
assertThatIllegalArgumentException().isThrownBy(() ->
ReflectionUtils.shallowCopyFieldState(src, dest));
}
@Test
void rejectsNullDest() {
TestObject src = new TestObject();
String dest = null;
assertThatIllegalArgumentException().isThrownBy(() ->
ReflectionUtils.shallowCopyFieldState(src, dest));
}
@Test
void validCopy() {
TestObject src = new TestObject();
TestObject dest = new TestObject();
testValidCopy(src, dest);
}
@Test
void validCopyOnSubTypeWithNewField() {
TestObjectSubclassWithNewField src = new TestObjectSubclassWithNewField();
TestObjectSubclassWithNewField dest = new TestObjectSubclassWithNewField();
src.magic = 11;
// Will check inherited fields are copied
testValidCopy(src, dest);
// Check subclass fields were copied
assertThat(dest.magic).isEqualTo(src.magic);
assertThat(dest.prot).isEqualTo(src.prot);
}
@Test
void validCopyToSubType() {
TestObject src = new TestObject();
TestObjectSubclassWithNewField dest = new TestObjectSubclassWithNewField();
dest.magic = 11;
testValidCopy(src, dest);
// Should have left this one alone
assertThat(dest.magic).isEqualTo(11);
}
@Test
void validCopyToSubTypeWithFinalField() {
TestObjectSubclassWithFinalField src = new TestObjectSubclassWithFinalField();
TestObjectSubclassWithFinalField dest = new TestObjectSubclassWithFinalField();
// Check that this doesn't fail due to attempt to assign final
testValidCopy(src, dest);
}
private void testValidCopy(TestObject src, TestObject dest) {
src.setName("freddie");
src.setAge(15);
src.setSpouse(new TestObject());
assertThat(src.getAge()).isNotEqualTo(dest.getAge());
ReflectionUtils.shallowCopyFieldState(src, dest);
assertThat(dest.getAge()).isEqualTo(src.getAge());
assertThat(dest.getSpouse()).isEqualTo(src.getSpouse());
}
@Test
void doWithMethodsUsingProtectedFilter() {
ListSavingMethodCallback mc = new ListSavingMethodCallback();
ReflectionUtils.doWithMethods(TestObject.class, mc, method -> Modifier.isProtected(method.getModifiers()));
assertThat(mc.getMethodNames())
.hasSizeGreaterThanOrEqualTo(2)
.as("Must find protected methods on Object").contains("clone", "finalize")
.as("Public, not protected").doesNotContain("hashCode", "absquatulate");
}
@Test
void doWithMethodsUsingUserDeclaredMethodsFilterStartingWithObject() {
ListSavingMethodCallback mc = new ListSavingMethodCallback();
ReflectionUtils.doWithMethods(Object.class, mc, ReflectionUtils.USER_DECLARED_METHODS);
assertThat(mc.getMethodNames()).isEmpty();
}
@Test
void doWithMethodsUsingUserDeclaredMethodsFilterStartingWithTestObject() {
ListSavingMethodCallback mc = new ListSavingMethodCallback();
ReflectionUtils.doWithMethods(TestObject.class, mc, ReflectionUtils.USER_DECLARED_METHODS);
assertThat(mc.getMethodNames())
.as("user declared methods").contains("absquatulate", "compareTo", "getName", "setName", "getAge", "setAge", "getSpouse", "setSpouse")
.as("methods on Object").doesNotContain("equals", "hashCode", "toString", "clone", "finalize", "getClass", "notify", "notifyAll", "wait");
}
@Test
void doWithMethodsUsingUserDeclaredMethodsComposedFilter() {
ListSavingMethodCallback mc = new ListSavingMethodCallback();
// "q" because both absquatulate() and equals() contain "q"
MethodFilter isSetterMethodOrNameContainsQ = m -> m.getName().startsWith("set") || m.getName().contains("q");
MethodFilter methodFilter = ReflectionUtils.USER_DECLARED_METHODS.and(isSetterMethodOrNameContainsQ);
ReflectionUtils.doWithMethods(TestObject.class, mc, methodFilter);
assertThat(mc.getMethodNames()).containsExactlyInAnyOrder("setName", "setAge", "setSpouse", "absquatulate");
}
@Test
void doWithMethodsFindsDuplicatesInClassHierarchy() {
ListSavingMethodCallback mc = new ListSavingMethodCallback();
ReflectionUtils.doWithMethods(TestObjectSubclass.class, mc);
assertThat(mc.getMethodNames().stream()).filteredOn("absquatulate"::equals).as("Found 2 absquatulates").hasSize(2);
}
@Test
void findMethod() {
assertThat(ReflectionUtils.findMethod(B.class, "bar", String.class)).isNotNull();
assertThat(ReflectionUtils.findMethod(B.class, "foo", Integer.class)).isNotNull();
assertThat(ReflectionUtils.findMethod(B.class, "getClass")).isNotNull();
}
@Test
void findMethodWithVarArgs() {
assertThat(ReflectionUtils.findMethod(B.class, "add", int[].class)).isNotNull();
}
@Test
void isCglibRenamedMethod() throws SecurityException, NoSuchMethodException {
@SuppressWarnings("unused")
| ReflectionUtilsTests |
java | spring-projects__spring-framework | spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/ConvertingEncoderDecoderSupportTests.java | {
"start": 7713,
"end": 7903
} | class ____ implements Converter<String, MyType> {
@Override
public MyType convert(String source) {
return new MyType(source.substring(1));
}
}
private static | StringToMyTypeConverter |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/ManyToManyAbstractTablePerClassTest.java | {
"start": 4148,
"end": 4302
} | class ____ extends TablePerClassBase {
public TablePerClassSub2() {
}
public TablePerClassSub2(Integer id) {
super( id );
}
}
}
| TablePerClassSub2 |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/ElectionType.java | {
"start": 1042,
"end": 1593
} | enum ____ {
PREFERRED((byte) 0), UNCLEAN((byte) 1);
public final byte value;
ElectionType(byte value) {
this.value = value;
}
public static ElectionType valueOf(byte value) {
if (value == PREFERRED.value) {
return PREFERRED;
} else if (value == UNCLEAN.value) {
return UNCLEAN;
} else {
throw new IllegalArgumentException(
String.format("Value %s must be one of %s", value, Arrays.asList(ElectionType.values())));
}
}
}
| ElectionType |
java | apache__flink | flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/nfa/compiler/NFACompiler.java | {
"start": 48239,
"end": 48366
} | interface ____ {@link NFA}.
*
* @param <T> Type of the input events which are processed by the NFA
*/
public | for |
java | spring-projects__spring-framework | spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectiveIndexAccessorTests.java | {
"start": 2910,
"end": 4283
} | class ____ read-method: %s", readMethod);
}
@Test
void publicReadAndWriteMethods() {
FruitMap fruitMap = new FruitMap();
EvaluationContext context = mock();
ReflectiveIndexAccessor accessor =
new ReflectiveIndexAccessor(FruitMap.class, Color.class, "getFruit", "setFruit");
assertThat(accessor.getSpecificTargetClasses()).containsOnly(FruitMap.class);
assertThat(accessor.canRead(context, this, Color.RED)).isFalse();
assertThat(accessor.canRead(context, fruitMap, this)).isFalse();
assertThat(accessor.canRead(context, fruitMap, Color.RED)).isTrue();
assertThat(accessor.read(context, fruitMap, Color.RED)).extracting(TypedValue::getValue).isEqualTo("cherry");
assertThat(accessor.canWrite(context, this, Color.RED)).isFalse();
assertThat(accessor.canWrite(context, fruitMap, this)).isFalse();
assertThat(accessor.canWrite(context, fruitMap, Color.RED)).isTrue();
accessor.write(context, fruitMap, Color.RED, "strawberry");
assertThat(fruitMap.getFruit(Color.RED)).isEqualTo("strawberry");
assertThat(accessor.read(context, fruitMap, Color.RED)).extracting(TypedValue::getValue).isEqualTo("strawberry");
assertThat(accessor.isCompilable()).isTrue();
assertThat(accessor.getIndexedValueType()).isEqualTo(String.class);
assertThatNoException().isThrownBy(() -> accessor.generateCode(mock(), mock(), mock()));
}
public static | for |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/aot/AotDetector.java | {
"start": 1067,
"end": 1894
} | class ____ {
/**
* System property that indicates the application should run with AOT
* generated artifacts. If such optimizations are not available, it is
* recommended to throw an exception rather than fall back to the regular
* runtime behavior.
*/
public static final String AOT_ENABLED = "spring.aot.enabled";
private static final boolean inNativeImage = NativeDetector.inNativeImage(Context.RUN, Context.BUILD);
/**
* Determine whether AOT optimizations must be considered at runtime. This
* is mandatory in a native image but can be triggered on the JVM using
* the {@value #AOT_ENABLED} Spring property.
* @return whether AOT optimizations must be considered
*/
public static boolean useGeneratedArtifacts() {
return (inNativeImage || SpringProperties.getFlag(AOT_ENABLED));
}
}
| AotDetector |
java | apache__logging-log4j2 | log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/util/TruncatingBufferedWriterTest.java | {
"start": 976,
"end": 11859
} | class ____ {
@Test
void test_ctor_invalid_args() {
Assertions.assertThatThrownBy(() -> new TruncatingBufferedWriter(-1))
.isInstanceOf(NegativeArraySizeException.class);
}
@Test
void test_okay_payloads() {
// Fill in the writer.
final int capacity = 1_000;
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(capacity);
writer.write(Character.MAX_VALUE);
writer.write(new char[] {Character.MIN_VALUE, Character.MAX_VALUE});
writer.write("foo");
writer.write("foobar", 3, 3);
writer.write("empty", 3, 0);
writer.write(new char[] {'f', 'o', 'o', 'b', 'a', 'r', 'b', 'u', 'z', 'z'}, 6, 4);
writer.write(new char[] {'a', 'b', 'c'}, 0, 0);
writer.write(new char[] {}, 0, 0);
writer.write(new char[] {});
writer.write("", 0, 0);
writer.write("");
writer.append('!');
writer.append("yo");
writer.append(null);
writer.append("yo dog", 3, 6);
writer.append(null, -1, -1);
writer.append("", -1, -1);
writer.append("");
// Verify accessors.
final char[] expectedBuffer = new char[capacity];
int expectedPosition = 0;
expectedBuffer[expectedPosition++] = Character.MAX_VALUE;
expectedBuffer[expectedPosition++] = Character.MIN_VALUE;
expectedBuffer[expectedPosition++] = Character.MAX_VALUE;
expectedBuffer[expectedPosition++] = 'f';
expectedBuffer[expectedPosition++] = 'o';
expectedBuffer[expectedPosition++] = 'o';
expectedBuffer[expectedPosition++] = 'b';
expectedBuffer[expectedPosition++] = 'a';
expectedBuffer[expectedPosition++] = 'r';
expectedBuffer[expectedPosition++] = 'b';
expectedBuffer[expectedPosition++] = 'u';
expectedBuffer[expectedPosition++] = 'z';
expectedBuffer[expectedPosition++] = 'z';
expectedBuffer[expectedPosition++] = '!';
expectedBuffer[expectedPosition++] = 'y';
expectedBuffer[expectedPosition++] = 'o';
expectedBuffer[expectedPosition++] = 'n';
expectedBuffer[expectedPosition++] = 'u';
expectedBuffer[expectedPosition++] = 'l';
expectedBuffer[expectedPosition++] = 'l';
expectedBuffer[expectedPosition++] = 'd';
expectedBuffer[expectedPosition++] = 'o';
expectedBuffer[expectedPosition++] = 'g';
expectedBuffer[expectedPosition++] = 'n';
expectedBuffer[expectedPosition++] = 'u';
expectedBuffer[expectedPosition++] = 'l';
expectedBuffer[expectedPosition++] = 'l';
Assertions.assertThat(writer.buffer()).isEqualTo(expectedBuffer);
Assertions.assertThat(writer.position()).isEqualTo(expectedPosition);
Assertions.assertThat(writer.capacity()).isEqualTo(capacity);
Assertions.assertThat(writer.truncated()).isFalse();
verifyClose(writer);
}
@Test
void test_write_int_truncation() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
writer.write('a');
writer.write('b');
verifyTruncation(writer, 'a');
}
@Test
void test_write_char_array_truncation() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
writer.write(new char[] {'a', 'b'});
verifyTruncation(writer, 'a');
}
@Test
void test_write_String_truncation() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
writer.write("ab");
verifyTruncation(writer, 'a');
}
@Test
void test_write_String_slice_invalid_args() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
final String string = "a";
Assertions.assertThatThrownBy(() -> writer.write(string, -1, 1))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid offset");
Assertions.assertThatThrownBy(() -> writer.write(string, 1, 1))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid offset");
Assertions.assertThatThrownBy(() -> writer.write(string, 0, -1))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid length");
Assertions.assertThatThrownBy(() -> writer.write(string, 0, 2))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid length");
}
@Test
void test_write_String_slice_truncation() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
writer.write("ab", 0, 2);
verifyTruncation(writer, 'a');
}
@Test
void test_write_char_array_slice_invalid_args() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
final char[] buffer = new char[] {'a'};
Assertions.assertThatThrownBy(() -> writer.write(buffer, -1, 1))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid offset");
Assertions.assertThatThrownBy(() -> writer.write(buffer, 1, 1))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid offset");
Assertions.assertThatThrownBy(() -> writer.write(buffer, 0, -1))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid length");
Assertions.assertThatThrownBy(() -> writer.write(buffer, 0, 2))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid length");
}
@Test
void test_write_char_array_slice_truncation() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
writer.write(new char[] {'a', 'b'}, 0, 2);
verifyTruncation(writer, 'a');
}
@Test
void test_append_char_truncation() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
writer.append('a');
writer.append('b');
verifyTruncation(writer, 'a');
}
@Test
void test_append_seq_truncation() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
writer.append("ab");
verifyTruncation(writer, 'a');
}
@Test
void test_append_seq_null_truncation() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
writer.append(null);
verifyTruncation(writer, 'n');
}
@Test
void test_append_seq_slice_invalid_args() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
final CharSequence seq = "ab";
Assertions.assertThatThrownBy(() -> writer.append(seq, -1, 2))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid start");
Assertions.assertThatThrownBy(() -> writer.append(seq, 2, 2))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid start");
Assertions.assertThatThrownBy(() -> writer.append(seq, 0, -1))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid end");
Assertions.assertThatThrownBy(() -> writer.append(seq, 1, 0))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid end");
Assertions.assertThatThrownBy(() -> writer.append(seq, 0, 3))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("invalid end");
}
@Test
void test_append_seq_slice_truncation() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
writer.append("ab", 0, 1);
verifyTruncation(writer, 'a');
}
@Test
void test_append_seq_slice_null_truncation() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(1);
writer.append(null, -1, -1);
verifyTruncation(writer, 'n');
}
private static void verifyTruncation(final TruncatingBufferedWriter writer, final char c) {
Assertions.assertThat(writer.buffer()).isEqualTo(new char[] {c});
Assertions.assertThat(writer.position()).isEqualTo(1);
Assertions.assertThat(writer.capacity()).isEqualTo(1);
Assertions.assertThat(writer.truncated()).isTrue();
verifyClose(writer);
}
private static void verifyClose(final TruncatingBufferedWriter writer) {
writer.close();
Assertions.assertThat(writer.position()).isEqualTo(0);
Assertions.assertThat(writer.truncated()).isFalse();
}
@Test
void test_length_and_position() {
// Create the writer and the verifier.
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(2);
final Consumer<Integer> positionAndLengthVerifier =
(final Integer expected) -> Assertions.assertThat(writer.position())
.isEqualTo(writer.length())
.isEqualTo(expected);
// Check the initial condition.
positionAndLengthVerifier.accept(0);
// Append the 1st character and verify.
writer.write("a");
positionAndLengthVerifier.accept(1);
// Append the 2nd character and verify.
writer.write("b");
positionAndLengthVerifier.accept(2);
// Append the 3rd to-be-truncated character and verify.
writer.write("c");
positionAndLengthVerifier.accept(2);
// Reposition the writer and verify.
writer.position(1);
positionAndLengthVerifier.accept(1);
}
@Test
void subSequence_should_not_be_supported() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(2);
assertUnsupportedOperation(() -> writer.subSequence(0, 0));
}
@Test
void chars_should_not_be_supported() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(2);
assertUnsupportedOperation(() -> writer.subSequence(0, 0));
}
@Test
void codePoints_should_not_be_supported() {
final TruncatingBufferedWriter writer = new TruncatingBufferedWriter(2);
assertUnsupportedOperation(() -> writer.subSequence(0, 0));
}
private static void assertUnsupportedOperation(final Runnable runnable) {
Assertions.assertThatThrownBy(runnable::run)
.isInstanceOf(UnsupportedOperationException.class)
.hasMessage("operation requires allocation, contradicting with the purpose of the class");
}
}
| TruncatingBufferedWriterTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhance/internal/bytebuddy/DirtyCheckingWithEmbeddableAndNonVisibleGenericMappedSuperclassWithDifferentGenericParameterNameTest.java | {
"start": 3685,
"end": 4033
} | class ____ extends MyLevel2GenericMappedSuperclass<MyEmbeddable> {
@Id
private Integer id;
public MyEntity() {
}
private MyEntity(Integer id, String text) {
this.id = id;
setEmbedded( new MyEmbeddable( text ) );
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
}
| MyEntity |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/handler/predicate/VersionRoutePredicateFactoryPathSegmentIntegrationTests.java | {
"start": 1956,
"end": 2400
} | class ____ {
@Value("${test.uri}")
String uri;
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("version14_dsl",
r -> r.path("/version14/sub/{pathVersion}")
.and()
.version("1.4")
.filters(f -> f.setPath("/httpbin/anything/{pathVersion}")
.setResponseHeader("X-Matched-Version", "1.4"))
.uri(uri))
.build();
}
}
}
| TestConfig |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/array/HSQLArrayPositionFunction.java | {
"start": 572,
"end": 1648
} | class ____ extends AbstractArrayPositionFunction {
public HSQLArrayPositionFunction(TypeConfiguration typeConfiguration) {
super( typeConfiguration );
}
@Override
public void render(
SqlAppender sqlAppender,
List<? extends SqlAstNode> sqlAstArguments,
ReturnableType<?> returnType,
SqlAstTranslator<?> walker) {
final Expression arrayExpression = (Expression) sqlAstArguments.get( 0 );
final Expression elementExpression = (Expression) sqlAstArguments.get( 1 );
sqlAppender.append( "case when " );
arrayExpression.accept( walker );
sqlAppender.append( " is not null then coalesce((select t.idx from unnest(");
arrayExpression.accept( walker );
sqlAppender.append(") with ordinality t(val,idx) where t.val is not distinct from " );
walker.render( elementExpression, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER );
if ( sqlAstArguments.size() > 2 ) {
sqlAppender.append( " and t.idx>=" );
sqlAstArguments.get( 2 ).accept( walker );
}
sqlAppender.append( " order by t.idx fetch first 1 row only),0) end" );
}
}
| HSQLArrayPositionFunction |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/support/search/WatcherSearchTemplateService.java | {
"start": 1392,
"end": 4120
} | class ____ {
private final ScriptService scriptService;
private final NamedXContentRegistry xContentRegistry;
private final Predicate<NodeFeature> clusterSupportsFeature;
public WatcherSearchTemplateService(
ScriptService scriptService,
NamedXContentRegistry xContentRegistry,
Predicate<NodeFeature> clusterSupportsFeature
) {
this.scriptService = scriptService;
this.xContentRegistry = xContentRegistry;
this.clusterSupportsFeature = clusterSupportsFeature;
}
public String renderTemplate(Script source, WatchExecutionContext ctx, Payload payload) {
// Due the inconsistency with templates in ES 1.x, we maintain our own template format.
// This template format we use now, will become the template structure in ES 2.0
Map<String, Object> watcherContextParams = Variables.createCtxParamsMap(ctx, payload);
// Here we convert watcher template into a ES core templates. Due to the different format we use, we
// convert to the template format used in ES core
if (source.getParams() != null) {
watcherContextParams.putAll(source.getParams());
}
// Templates are always of lang mustache:
Script template = new Script(
source.getType(),
source.getType() == ScriptType.STORED ? null : "mustache",
source.getIdOrCode(),
source.getOptions(),
watcherContextParams
);
TemplateScript.Factory compiledTemplate = scriptService.compile(template, Watcher.SCRIPT_TEMPLATE_CONTEXT);
return compiledTemplate.newInstance(template.getParams()).execute();
}
public SearchRequest toSearchRequest(WatcherSearchTemplateRequest request) throws IOException {
SearchRequest searchRequest = new SearchRequest(request.getIndices());
searchRequest.searchType(request.getSearchType());
searchRequest.indicesOptions(request.getIndicesOptions());
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BytesReference source = request.getSearchSource();
if (source != null && source.length() > 0) {
try (
XContentParser parser = XContentHelper.createParserNotCompressed(
LoggingDeprecationHandler.XCONTENT_PARSER_CONFIG.withRegistry(xContentRegistry),
source,
XContentHelper.xContentType(source)
)
) {
sourceBuilder.parseXContent(parser, true, clusterSupportsFeature);
searchRequest.source(sourceBuilder);
}
}
return searchRequest;
}
}
| WatcherSearchTemplateService |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/JobContext.java | {
"start": 4071,
"end": 4235
} | class ____ the job.
*/
public Class<? extends Reducer<?,?,?,?>> getReducerClass()
throws ClassNotFoundException;
/**
* Get the {@link OutputFormat} | for |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/TestInstanceLifecycleUtilsTests.java | {
"start": 1899,
"end": 4208
} | class ____ {
private static final String KEY = DEFAULT_TEST_INSTANCE_LIFECYCLE_PROPERTY_NAME;
@SuppressWarnings("DataFlowIssue")
@Test
void getTestInstanceLifecyclePreconditions() {
assertPreconditionViolationNotNullFor("testClass", () -> getTestInstanceLifecycle(null,
new DefaultJupiterConfiguration(mock(), dummyOutputDirectoryCreator(), mock())));
assertPreconditionViolationNotNullFor("configuration", () -> getTestInstanceLifecycle(getClass(), null));
}
@Test
void getTestInstanceLifecycleWithNoConfigParamSet() {
Lifecycle lifecycle = getTestInstanceLifecycle(getClass(),
new DefaultJupiterConfiguration(mock(), dummyOutputDirectoryCreator(), mock()));
assertThat(lifecycle).isEqualTo(PER_METHOD);
}
@Test
void getTestInstanceLifecycleWithConfigParamSet() {
ConfigurationParameters configParams = mock();
when(configParams.get(KEY)).thenReturn(Optional.of(PER_CLASS.name().toLowerCase()));
Lifecycle lifecycle = getTestInstanceLifecycle(getClass(),
new DefaultJupiterConfiguration(configParams, dummyOutputDirectoryCreator(), mock()));
assertThat(lifecycle).isEqualTo(PER_CLASS);
}
@Test
void getTestInstanceLifecycleWithLocalConfigThatOverridesCustomDefaultSetViaConfigParam() {
ConfigurationParameters configParams = mock();
when(configParams.get(KEY)).thenReturn(Optional.of(PER_CLASS.name().toLowerCase()));
Lifecycle lifecycle = getTestInstanceLifecycle(TestCase.class,
new DefaultJupiterConfiguration(configParams, dummyOutputDirectoryCreator(), mock()));
assertThat(lifecycle).isEqualTo(PER_METHOD);
}
@Test
void getTestInstanceLifecycleFromMetaAnnotationWithNoConfigParamSet() {
Class<?> testClass = BaseMetaAnnotatedTestCase.class;
Lifecycle lifecycle = getTestInstanceLifecycle(testClass,
new DefaultJupiterConfiguration(mock(), dummyOutputDirectoryCreator(), mock()));
assertThat(lifecycle).isEqualTo(PER_CLASS);
}
@Test
void getTestInstanceLifecycleFromSpecializedClassWithNoConfigParamSet() {
Class<?> testClass = SpecializedTestCase.class;
Lifecycle lifecycle = getTestInstanceLifecycle(testClass,
new DefaultJupiterConfiguration(mock(), dummyOutputDirectoryCreator(), mock()));
assertThat(lifecycle).isEqualTo(PER_CLASS);
}
@TestInstance(Lifecycle.PER_METHOD)
private static | TestInstanceLifecycleUtilsTests |
java | apache__thrift | lib/javame/src/org/apache/thrift/transport/TTransportException.java | {
"start": 924,
"end": 2006
} | class ____ extends TException {
private static final long serialVersionUID = 1L;
public static final int UNKNOWN = 0;
public static final int NOT_OPEN = 1;
public static final int ALREADY_OPEN = 2;
public static final int TIMED_OUT = 3;
public static final int END_OF_FILE = 4;
protected int type_ = UNKNOWN;
public TTransportException() {
super();
}
public TTransportException(int type) {
super();
type_ = type;
}
public TTransportException(int type, String message) {
super(message);
type_ = type;
}
public TTransportException(String message) {
super(message);
}
public TTransportException(int type, Throwable cause) {
super(cause);
type_ = type;
}
public TTransportException(Throwable cause) {
super(cause);
}
public TTransportException(String message, Throwable cause) {
super(message, cause);
}
public TTransportException(int type, String message, Throwable cause) {
super(message, cause);
type_ = type;
}
public int getType() {
return type_;
}
}
| TTransportException |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/ai/model/mcp/SecurityScheme.java | {
"start": 153,
"end": 1978
} | class ____ {
/**
* ID of the security scheme. Will be used and reference by tools.
*/
private String id;
/**
* Type of the security scheme. Possible values are: 'http', 'apiKey', 'localEnv' or other custom extension.
*/
private String type;
/**
* Scheme of the security scheme. Used when {@link #type} is `http`. Possible values are: `basic` 或 `bearer`.
*/
private String scheme;
/**
* Location of the security scheme. Possible values are: `query`, `header`.
*/
private String in;
/**
* Name of the security scheme. Used when {@link #type} is `apiKey` or `localEnv`.
* e.g. the key name for `apiKey` or environment name for `localEnv`.
*/
private String name;
/**
* The default credential when leak input identity by properties. Optional.
*/
private String defaultCredential;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getScheme() {
return scheme;
}
public void setScheme(String scheme) {
this.scheme = scheme;
}
public String getIn() {
return in;
}
public void setIn(String in) {
this.in = in;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDefaultCredential() {
return defaultCredential;
}
public void setDefaultCredential(String defaultCredential) {
this.defaultCredential = defaultCredential;
}
}
| SecurityScheme |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ReferenceEqualityTest.java | {
"start": 9470,
"end": 9794
} | class ____ {
boolean f(String s) {
return s.getClass() == String.class;
}
}
""")
.doTest();
}
@Test
public void transitiveEquals() {
compilationHelper
.addSourceLines(
"Super.java",
"""
public | Test |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java | {
"start": 2713,
"end": 2791
} | class ____ a non-void returning setter method
@SuppressWarnings("unused")
| with |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/lazyonetoone/LazyOneToOneTest.java | {
"start": 1095,
"end": 2639
} | class ____ {
@Test
public void testLazy(SessionFactoryScope scope) {
Person person = new Person( "Gavin" );
Employee e = new Employee( person );
Employment old = new Employment( e, "IFA" );
scope.inTransaction(
session -> {
Person p2 = new Person( "Emmanuel" );
new Employment( e, "JBoss" );
old.setEndDate( new Date() );
session.persist( person );
session.persist( p2 );
}
);
scope.inTransaction(
session -> {
Person p = (Person) session.createQuery( "from Person where name='Gavin'" ).uniqueResult();
//assertFalse( Hibernate.isPropertyInitialized(p, "employee") );
assertSame( p ,p.getEmployee().getPerson() );
assertTrue( Hibernate.isInitialized( p.getEmployee().getEmployments() ) );
assertEquals( 1, p.getEmployee().getEmployments().size() );
Person p2 = (Person) session.createQuery( "from Person where name='Emmanuel'" ).uniqueResult();
assertNull( p2.getEmployee() );
}
);
scope.inTransaction(
session -> {
Person p = session.get( Person.class, "Gavin" );
//assertFalse( Hibernate.isPropertyInitialized(p, "employee") );
assertSame( p.getEmployee().getPerson(), p );
assertTrue( Hibernate.isInitialized( p.getEmployee().getEmployments() ) );
assertEquals( p.getEmployee().getEmployments().size(), 1 );
Person p2 = session.get( Person.class, "Emmanuel" );
assertNull( p2.getEmployee() );
session.remove( p2 );
session.remove( old );
session.remove( p );
}
);
}
}
| LazyOneToOneTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/basicType/DoubleNullTest_primitive.java | {
"start": 953,
"end": 1027
} | class ____ {
public double v1;
public double v2;
}
}
| Model |
java | apache__spark | examples/src/main/java/org/apache/spark/examples/sql/JavaSparkSQLExample.java | {
"start": 6549,
"end": 10904
} | class ____
Encoder<Long> longEncoder = Encoders.LONG();
Dataset<Long> primitiveDS = spark.createDataset(Arrays.asList(1L, 2L, 3L), longEncoder);
Dataset<Long> transformedDS = primitiveDS.map(
(MapFunction<Long, Long>) value -> value + 1L,
longEncoder);
transformedDS.collect(); // Returns [2, 3, 4]
// DataFrames can be converted to a Dataset by providing a class. Mapping based on name
String path = "examples/src/main/resources/people.json";
Dataset<Person> peopleDS = spark.read().json(path).as(personEncoder);
peopleDS.show();
// +----+-------+
// | age| name|
// +----+-------+
// |null|Michael|
// | 30| Andy|
// | 19| Justin|
// +----+-------+
// $example off:create_ds$
}
private static void runInferSchemaExample(SparkSession spark) {
// $example on:schema_inferring$
// Create an RDD of Person objects from a text file
JavaRDD<Person> peopleRDD = spark.read()
.textFile("examples/src/main/resources/people.txt")
.javaRDD()
.map(line -> {
String[] parts = line.split(",");
Person person = new Person();
person.setName(parts[0]);
person.setAge(Integer.parseInt(parts[1].trim()));
return person;
});
// Apply a schema to an RDD of JavaBeans to get a DataFrame
Dataset<Row> peopleDF = spark.createDataFrame(peopleRDD, Person.class);
// Register the DataFrame as a temporary view
peopleDF.createOrReplaceTempView("people");
// SQL statements can be run by using the sql methods provided by spark
Dataset<Row> teenagersDF = spark.sql("SELECT name FROM people WHERE age BETWEEN 13 AND 19");
// The columns of a row in the result can be accessed by field index
Encoder<String> stringEncoder = Encoders.STRING();
Dataset<String> teenagerNamesByIndexDF = teenagersDF.map(
(MapFunction<Row, String>) row -> "Name: " + row.getString(0),
stringEncoder);
teenagerNamesByIndexDF.show();
// +------------+
// | value|
// +------------+
// |Name: Justin|
// +------------+
// or by field name
Dataset<String> teenagerNamesByFieldDF = teenagersDF.map(
(MapFunction<Row, String>) row -> "Name: " + row.<String>getAs("name"),
stringEncoder);
teenagerNamesByFieldDF.show();
// +------------+
// | value|
// +------------+
// |Name: Justin|
// +------------+
// $example off:schema_inferring$
}
private static void runProgrammaticSchemaExample(SparkSession spark) {
// $example on:programmatic_schema$
// Create an RDD
JavaRDD<String> peopleRDD = spark.sparkContext()
.textFile("examples/src/main/resources/people.txt", 1)
.toJavaRDD();
// The schema is encoded in a string
String schemaString = "name age";
// Generate the schema based on the string of schema
List<StructField> fields = new ArrayList<>();
for (String fieldName : schemaString.split(" ")) {
StructField field = DataTypes.createStructField(fieldName, DataTypes.StringType, true);
fields.add(field);
}
StructType schema = DataTypes.createStructType(fields);
// Convert records of the RDD (people) to Rows
JavaRDD<Row> rowRDD = peopleRDD.map((Function<String, Row>) record -> {
String[] attributes = record.split(",");
return RowFactory.create(attributes[0], attributes[1].trim());
});
// Apply the schema to the RDD
Dataset<Row> peopleDataFrame = spark.createDataFrame(rowRDD, schema);
// Creates a temporary view using the DataFrame
peopleDataFrame.createOrReplaceTempView("people");
// SQL can be run over a temporary view created using DataFrames
Dataset<Row> results = spark.sql("SELECT name FROM people");
// The results of SQL queries are DataFrames and support all the normal RDD operations
// The columns of a row in the result can be accessed by field index or by field name
Dataset<String> namesDS = results.map(
(MapFunction<Row, String>) row -> "Name: " + row.getString(0),
Encoders.STRING());
namesDS.show();
// +-------------+
// | value|
// +-------------+
// |Name: Michael|
// | Name: Andy|
// | Name: Justin|
// +-------------+
// $example off:programmatic_schema$
}
}
| Encoders |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/Address.java | {
"start": 179,
"end": 907
} | class ____ {
private String street;
private String city;
private String state;
private String zip;
public Address() {
}
public Address(String street, String city, String state, String zip) {
this.street = street;
this.city = city;
this.state = state;
this.zip = zip;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}
| Address |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/function/ByteSupplier.java | {
"start": 909,
"end": 1011
} | interface ____ {@link IntSupplier}, but for a byte.
*
* @since 3.19
*/
@FunctionalInterface
public | like |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/retention/UnusedStatsRemover.java | {
"start": 1815,
"end": 6116
} | class ____ implements MlDataRemover {
private static final Logger LOGGER = LogManager.getLogger(UnusedStatsRemover.class);
private final OriginSettingClient client;
private final TaskId parentTaskId;
public UnusedStatsRemover(OriginSettingClient client, TaskId parentTaskId) {
this.client = Objects.requireNonNull(client);
this.parentTaskId = Objects.requireNonNull(parentTaskId);
}
@Override
public void remove(float requestsPerSec, ActionListener<Boolean> listener, BooleanSupplier isTimedOutSupplier) {
try {
if (isTimedOutSupplier.getAsBoolean()) {
listener.onResponse(false);
return;
}
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
.mustNot(QueryBuilders.termsQuery(Fields.JOB_ID.getPreferredName(), getDataFrameAnalyticsJobIds()))
.mustNot(QueryBuilders.termsQuery(TrainedModelConfig.MODEL_ID.getPreferredName(), getTrainedModelIds()));
if (isTimedOutSupplier.getAsBoolean()) {
listener.onResponse(false);
return;
}
executeDeleteUnusedStatsDocs(queryBuilder, requestsPerSec, listener);
} catch (Exception e) {
listener.onFailure(e);
}
}
private Set<String> getDataFrameAnalyticsJobIds() {
Set<String> jobIds = new HashSet<>();
DocIdBatchedDocumentIterator iterator = new DocIdBatchedDocumentIterator(
client,
MlConfigIndex.indexName(),
QueryBuilders.termQuery(DataFrameAnalyticsConfig.CONFIG_TYPE.getPreferredName(), DataFrameAnalyticsConfig.TYPE)
);
while (iterator.hasNext()) {
Deque<String> docIds = iterator.next();
docIds.stream().map(DataFrameAnalyticsConfig::extractJobIdFromDocId).filter(Objects::nonNull).forEach(jobIds::add);
}
return jobIds;
}
private Set<String> getTrainedModelIds() {
Set<String> modelIds = new HashSet<>(TrainedModelProvider.MODELS_STORED_AS_RESOURCE);
DocIdBatchedDocumentIterator iterator = new DocIdBatchedDocumentIterator(
client,
InferenceIndexConstants.INDEX_PATTERN,
QueryBuilders.termQuery(InferenceIndexConstants.DOC_TYPE.getPreferredName(), TrainedModelConfig.NAME)
);
while (iterator.hasNext()) {
Deque<String> docIds = iterator.next();
docIds.stream().filter(Objects::nonNull).forEach(modelIds::add);
}
return modelIds;
}
private void executeDeleteUnusedStatsDocs(QueryBuilder dbq, float requestsPerSec, ActionListener<Boolean> listener) {
var indicesToQuery = WritableIndexExpander.getInstance().getWritableIndices(MlStatsIndex.indexPattern());
if (indicesToQuery.isEmpty()) {
LOGGER.info("No writable indices found for unused stats documents");
listener.onResponse(true);
return;
}
DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(indicesToQuery.toArray(new String[0])).setIndicesOptions(
IndicesOptions.lenientExpandOpen()
).setAbortOnVersionConflict(false).setRequestsPerSecond(requestsPerSec).setTimeout(DEFAULT_MAX_DURATION).setQuery(dbq);
deleteByQueryRequest.setParentTask(parentTaskId);
client.execute(DeleteByQueryAction.INSTANCE, deleteByQueryRequest, ActionListener.wrap(response -> {
if (response.getBulkFailures().isEmpty() == false || response.getSearchFailures().isEmpty() == false) {
LOGGER.error(
"Some unused stats documents could not be deleted due to failures: {}",
Strings.collectionToCommaDelimitedString(response.getBulkFailures())
+ ","
+ Strings.collectionToCommaDelimitedString(response.getSearchFailures())
);
} else {
LOGGER.info("Successfully deleted [{}] unused stats documents", response.getDeleted());
}
listener.onResponse(true);
}, e -> {
LOGGER.error("Error deleting unused model stats documents: ", e);
listener.onFailure(e);
}));
}
}
| UnusedStatsRemover |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/process/AbstractProcessTableOperator.java | {
"start": 9285,
"end": 11301
} | class ____ TimeContext: "
+ conversionClass.getName());
}
internalTimeContext.setTime(
processTableRunner.getCurrentWatermark(), processTableRunner.getTime());
return (TimeContext<TimeType>)
new ExternalTimeContext<>(internalTimeContext, timeConverter);
}
@Override
public TableSemantics tableSemanticsFor(String argName) {
final RuntimeTableSemantics tableSemantics = tableSemanticsMap.get(argName);
if (tableSemantics == null) {
throw new TableRuntimeException("Unknown table argument: " + argName);
}
return tableSemantics;
}
@Override
public void clearState(String stateName) {
final Integer statePos = stateNameToPosMap.get(stateName);
if (statePos == null) {
throw new TableRuntimeException("Unknown state entry: " + stateName);
}
processTableRunner.clearState(statePos);
}
@Override
public void clearAllState() {
processTableRunner.clearAllState();
}
@Override
public void clearAllTimers() {
internalTimeContext.clearAllTimers();
}
@Override
public void clearAll() {
clearAllState();
clearAllTimers();
}
@Override
public ChangelogMode getChangelogMode() {
return changelogMode;
}
@VisibleForTesting
public StateDescriptor<?, ?> getStateDescriptor(String stateName) {
final Integer statePos = stateNameToPosMap.get(stateName);
if (statePos == null) {
throw new TableRuntimeException("Unknown state entry: " + stateName);
}
return stateDescriptors[statePos];
}
}
/** Implementation of {@link ProcessTableFunction.OnTimerContext}. */
@Internal
public | for |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/EnumUtils.java | {
"start": 15031,
"end": 15208
} | enum ____ and performs case insensitive matching of
* the name.
* </p>
*
* @param <E> the type of the enumeration.
* @param enumClass the | name |
java | spring-projects__spring-boot | module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/export/jmx/JmxMetricsExportAutoConfigurationTests.java | {
"start": 3906,
"end": 4076
} | class ____ {
@Bean
JmxMeterRegistry customRegistry(JmxConfig config, Clock clock) {
return new JmxMeterRegistry(config, clock);
}
}
}
| CustomRegistryConfiguration |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/load/resource/transcode/UnitTranscoder.java | {
"start": 388,
"end": 827
} | class ____<Z> implements ResourceTranscoder<Z, Z> {
private static final UnitTranscoder<?> UNIT_TRANSCODER = new UnitTranscoder<>();
@SuppressWarnings("unchecked")
public static <Z> ResourceTranscoder<Z, Z> get() {
return (ResourceTranscoder<Z, Z>) UNIT_TRANSCODER;
}
@Nullable
@Override
public Resource<Z> transcode(@NonNull Resource<Z> toTranscode, @NonNull Options options) {
return toTranscode;
}
}
| UnitTranscoder |
java | apache__flink | flink-table/flink-table-common/src/test/java/org/apache/flink/table/sources/TableSourceTestBase.java | {
"start": 1321,
"end": 3627
} | class ____ {
/**
* Constructs a table source to be tested.
*
* @param requestedSchema A requested schema for the table source. Some tests require particular
* behavior depending on the schema of a source.
* @return table source to be tested
*/
protected abstract TableSource<?> createTableSource(TableSchema requestedSchema);
/**
* Checks that {@link ProjectableTableSource#projectFields(int[])} returns a table source with a
* different {@link TableSource#explainSource()} even when filtering out all fields.
*
* <p>Required by {@code PushProjectIntoTableSourceScanRule}.
*/
@Test
void testEmptyProjection() {
TableSource<?> source =
createTableSource(TableSchema.builder().field("f0", DataTypes.INT()).build());
assumeThat(source).isInstanceOf(ProjectableTableSource.class);
ProjectableTableSource<?> projectableTableSource = (ProjectableTableSource<?>) source;
TableSource<?> newTableSource = projectableTableSource.projectFields(new int[0]);
assertThat(newTableSource.explainSource()).isNotEqualTo(source.explainSource());
}
/**
* Checks that {@link ProjectableTableSource#projectFields(int[])} returns a table source with a
* different {@link TableSource#explainSource()}, but same schema.
*
* <p>Required by {@code PushProjectIntoTableSourceScanRule}.
*/
@Test
void testProjectionReturnsDifferentSource() {
TableSource<?> source =
createTableSource(
TableSchema.builder()
.field("f0", DataTypes.INT())
.field("f1", DataTypes.STRING())
.field("f2", DataTypes.BIGINT())
.build());
assumeThat(source).isInstanceOf(ProjectableTableSource.class);
ProjectableTableSource<?> projectableTableSource = (ProjectableTableSource<?>) source;
TableSource<?> newTableSource = projectableTableSource.projectFields(new int[] {0, 2});
assertThat(newTableSource.explainSource()).isNotEqualTo(source.explainSource());
assertThat(newTableSource.getTableSchema()).isEqualTo(source.getTableSchema());
}
}
| TableSourceTestBase |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/JobClientHeartbeatHeaders.java | {
"start": 1149,
"end": 2548
} | class ____
implements RuntimeMessageHeaders<
JobClientHeartbeatRequestBody, EmptyResponseBody, JobClientHeartbeatParameters> {
public static final String URL = "/jobs/:jobid/clientHeartbeat";
private static final JobClientHeartbeatHeaders INSTANCE = new JobClientHeartbeatHeaders();
private JobClientHeartbeatHeaders() {}
@Override
public Class<JobClientHeartbeatRequestBody> getRequestClass() {
return JobClientHeartbeatRequestBody.class;
}
@Override
public Class<EmptyResponseBody> getResponseClass() {
return EmptyResponseBody.class;
}
@Override
public HttpResponseStatus getResponseStatusCode() {
return HttpResponseStatus.ACCEPTED;
}
@Override
public JobClientHeartbeatParameters getUnresolvedMessageParameters() {
return new JobClientHeartbeatParameters();
}
@Override
public HttpMethodWrapper getHttpMethod() {
return HttpMethodWrapper.PATCH;
}
@Override
public String getTargetRestEndpointURL() {
return URL;
}
public static JobClientHeartbeatHeaders getInstance() {
return INSTANCE;
}
@Override
public String getDescription() {
return "Report the jobClient's aliveness.";
}
@Override
public String operationId() {
return "triggerHeartbeat";
}
}
| JobClientHeartbeatHeaders |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/data/ArrayData.java | {
"start": 1861,
"end": 8460
} | interface ____ {
/** Returns the number of elements in this array. */
int size();
// ------------------------------------------------------------------------------------------
// Read-only accessor methods
// ------------------------------------------------------------------------------------------
/** Returns true if the element is null at the given position. */
boolean isNullAt(int pos);
/** Returns the boolean value at the given position. */
boolean getBoolean(int pos);
/** Returns the byte value at the given position. */
byte getByte(int pos);
/** Returns the short value at the given position. */
short getShort(int pos);
/** Returns the integer value at the given position. */
int getInt(int pos);
/** Returns the long value at the given position. */
long getLong(int pos);
/** Returns the float value at the given position. */
float getFloat(int pos);
/** Returns the double value at the given position. */
double getDouble(int pos);
/** Returns the string value at the given position. */
StringData getString(int pos);
/**
* Returns the decimal value at the given position.
*
* <p>The precision and scale are required to determine whether the decimal value was stored in
* a compact representation (see {@link DecimalData}).
*/
DecimalData getDecimal(int pos, int precision, int scale);
/**
* Returns the timestamp value at the given position.
*
* <p>The precision is required to determine whether the timestamp value was stored in a compact
* representation (see {@link TimestampData}).
*/
TimestampData getTimestamp(int pos, int precision);
/** Returns the raw value at the given position. */
<T> RawValueData<T> getRawValue(int pos);
/** Returns the Variant value at the given position. */
Variant getVariant(int i);
/** Returns the binary value at the given position. */
byte[] getBinary(int pos);
/** Returns the array value at the given position. */
ArrayData getArray(int pos);
/** Returns the map value at the given position. */
MapData getMap(int pos);
/**
* Returns the row value at the given position.
*
* <p>The number of fields is required to correctly extract the row.
*/
RowData getRow(int pos, int numFields);
// ------------------------------------------------------------------------------------------
// Conversion Utilities
// ------------------------------------------------------------------------------------------
boolean[] toBooleanArray();
byte[] toByteArray();
short[] toShortArray();
int[] toIntArray();
long[] toLongArray();
float[] toFloatArray();
double[] toDoubleArray();
// ------------------------------------------------------------------------------------------
// Access Utilities
// ------------------------------------------------------------------------------------------
/**
* Creates an accessor for getting elements in an internal array data structure at the given
* position.
*
* @param elementType the element type of the array
*/
static ElementGetter createElementGetter(LogicalType elementType) {
final ElementGetter elementGetter;
// ordered by type root definition
switch (elementType.getTypeRoot()) {
case CHAR:
case VARCHAR:
elementGetter = ArrayData::getString;
break;
case BOOLEAN:
elementGetter = ArrayData::getBoolean;
break;
case BINARY:
case VARBINARY:
elementGetter = ArrayData::getBinary;
break;
case DECIMAL:
final int decimalPrecision = getPrecision(elementType);
final int decimalScale = getScale(elementType);
elementGetter =
(array, pos) -> array.getDecimal(pos, decimalPrecision, decimalScale);
break;
case TINYINT:
elementGetter = ArrayData::getByte;
break;
case SMALLINT:
elementGetter = ArrayData::getShort;
break;
case INTEGER:
case DATE:
case TIME_WITHOUT_TIME_ZONE:
case INTERVAL_YEAR_MONTH:
elementGetter = ArrayData::getInt;
break;
case BIGINT:
case INTERVAL_DAY_TIME:
elementGetter = ArrayData::getLong;
break;
case FLOAT:
elementGetter = ArrayData::getFloat;
break;
case DOUBLE:
elementGetter = ArrayData::getDouble;
break;
case TIMESTAMP_WITHOUT_TIME_ZONE:
case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
final int timestampPrecision = getPrecision(elementType);
elementGetter = (array, pos) -> array.getTimestamp(pos, timestampPrecision);
break;
case TIMESTAMP_WITH_TIME_ZONE:
throw new UnsupportedOperationException();
case ARRAY:
elementGetter = ArrayData::getArray;
break;
case MULTISET:
case MAP:
elementGetter = ArrayData::getMap;
break;
case ROW:
case STRUCTURED_TYPE:
final int rowFieldCount = getFieldCount(elementType);
elementGetter = (array, pos) -> array.getRow(pos, rowFieldCount);
break;
case DISTINCT_TYPE:
elementGetter = createElementGetter(((DistinctType) elementType).getSourceType());
break;
case RAW:
elementGetter = ArrayData::getRawValue;
break;
case VARIANT:
elementGetter = ArrayData::getVariant;
break;
case NULL:
case SYMBOL:
case UNRESOLVED:
case DESCRIPTOR:
default:
throw new IllegalArgumentException();
}
return (array, pos) -> {
if (array.isNullAt(pos)) {
return null;
}
return elementGetter.getElementOrNull(array, pos);
};
}
/**
* Accessor for getting the elements of an array during runtime.
*
* @see #createElementGetter(LogicalType)
*/
@PublicEvolving
| ArrayData |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/search/aggregations/MultiBucketCollectorTests.java | {
"start": 1400,
"end": 1564
} | class ____ extends Scorable {
float score;
@Override
public float score() {
return score;
}
}
private static | Score |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ObjectEqualsForPrimitivesTest.java | {
"start": 2105,
"end": 2504
} | class ____ {
private static boolean doTest(int a, Integer b) {
return Objects.equals(a, b);
}
}
""")
.expectUnchanged()
.doTest();
}
@Test
public void objects() {
refactoringHelper
.addInputLines(
"Test.java",
"""
import java.util.Objects;
public | Test |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSPermission.java | {
"start": 36714,
"end": 37552
} | class ____ extends PermissionVerifier {
@Override
void setOpPermission() {
this.opParentPermission = SEARCH_MASK;
this.opPermission = WRITE_MASK;
}
@Override
void call() throws IOException {
fs.setTimes(path, 100, 100);
fs.setTimes(path, -1, 100);
fs.setTimes(path, 100, -1);
}
}
private final SetTimesPermissionVerifier timesVerifier =
new SetTimesPermissionVerifier();
/* test if the permission checking of setReplication is correct */
private void testSetTimes(UserGroupInformation ugi, Path path,
short ancestorPermission, short parentPermission, short filePermission)
throws Exception {
timesVerifier.set(path, ancestorPermission, parentPermission,
filePermission);
timesVerifier.verifyPermission(ugi);
}
/* A | SetTimesPermissionVerifier |
java | quarkusio__quarkus | tcks/microprofile-graphql/src/main/java/io/quarkus/tck/graphql/TestInterceptor.java | {
"start": 1121,
"end": 18311
} | class ____ extends TestListenerAdapter {
private static final Logger LOG = Logger.getLogger(TestInterceptor.class.getName());
private static final String EXECUTION_TEST = ExecutionDynamicTest.class.getName();
private static final String SCHEMA_TEST = SchemaDynamicValidityTest.class.getName();
private static final String TEST_SPECIFICATION = "testSpecification";
private static final String OVERRIDES = "src/main/resources/overrides";
private static final String PIPE = "|";
private static final String FILE_TYPE = ".csv";
private static final String DELIMITER = "\\" + PIPE;
private static final String COMMENT = "#";
private static final String OR = "'OR'";
private Map<String, org.eclipse.microprofile.graphql.tck.dynamic.execution.TestData> executionTestDataMap = new HashMap<>();
private Map<Integer, org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData> schemaTestDataMap = new HashMap<>();
public TestInterceptor() {
loadExecutionOverride();
loadSchemaOverride();
}
private void loadSchemaOverride() {
Path folderPath = Paths.get(OVERRIDES);
if (!Files.isDirectory(folderPath)) {
return;
}
// Get all csv files
try (DirectoryStream<Path> overrides = Files.newDirectoryStream(folderPath)) {
List<Path> overrideFiles = toListOfPathsForSchema(overrides);
List<org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData> testDataList = toListOfTestDataForSchema(
overrideFiles);
for (org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData td : testDataList) {
schemaTestDataMap.put(generateKey(td), td);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void loadExecutionOverride() {
Path folderPath = Paths.get(OVERRIDES);
if (!Files.isDirectory(folderPath)) {
return;
}
try (DirectoryStream<Path> overrides = Files.newDirectoryStream(folderPath)) {
Set<Path> overrideFolders = toListOfPathsForExecution(overrides);
executionTestDataMap.putAll(toMapOfTestDataForExecution(overrideFolders));
} catch (IOException ex) {
ex.printStackTrace();
}
}
private Set<Path> toListOfPathsForExecution(DirectoryStream<Path> directoryStream) {
Set<Path> directories = new HashSet<>();
for (Path p : directoryStream) {
try (Stream<Path> paths = Files.walk(p)) {
Set<Path> tree = paths.filter(Files::isDirectory)
.collect(Collectors.toSet());
directories.addAll(tree);
} catch (IOException ex) {
LOG.errorf("Ignoring directory [{0}] - {1}", new Object[] { p.getFileName().toString(), ex.getMessage() });
}
}
return directories;
}
private static List<Path> toListOfPathsForSchema(DirectoryStream<Path> directoryStream) {
List<Path> files = new ArrayList<>();
for (Path p : directoryStream) {
if (!Files.isDirectory(p) && p.getFileName().toString().endsWith(FILE_TYPE)) {
files.add(p);
}
}
return files;
}
private Map<String, org.eclipse.microprofile.graphql.tck.dynamic.execution.TestData> toMapOfTestDataForExecution(
Set<Path> testFolders) {
Map<String, org.eclipse.microprofile.graphql.tck.dynamic.execution.TestData> testDataMap = new HashMap<>();
for (Path testFolder : testFolders) {
if (!testFolder.getFileName().toString().startsWith("META-INF")) {// Ignore META-INF
try {
org.eclipse.microprofile.graphql.tck.dynamic.execution.TestData testData = toTestDataForExecution(
testFolder);
if (!testData.shouldIgnore()) {
testDataMap.put(testData.getName(), testData);
}
} catch (IOException ioe) {
LOG.errorf("Could not add test case {0} - {1}",
new Object[] { testFolder.getFileName().toString(), ioe.getMessage() });
}
}
}
return testDataMap;
}
private List<org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData> toListOfTestDataForSchema(
List<Path> testFolders) {
List<org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData> testDataList = new LinkedList<>();
for (Path testFile : testFolders) {
try {
testDataList.addAll(toTestDataForSchema(testFile));
} catch (IOException ioe) {
LOG.logf(Logger.Level.ERROR, "Could not add test case {0} - {1}",
new Object[] { testFile.getFileName().toString(), ioe.getMessage() });
}
}
return testDataList;
}
private org.eclipse.microprofile.graphql.tck.dynamic.execution.TestData toTestDataForExecution(Path folder)
throws IOException {
org.eclipse.microprofile.graphql.tck.dynamic.execution.TestData testData = new org.eclipse.microprofile.graphql.tck.dynamic.execution.TestData(
folder.getFileName().toString().replace("/", ""));
Files.walkFileTree(folder, new HashSet<>(), 1, new FileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (!Files.isDirectory(file)) {
String filename = file.getFileName().toString();
if (filename.matches("output.*\\.json")) {
// Special case to cater for multiple output*.json files where the
// test will pass on the first file content that matches.
// If no content matches, then the test will fail.
String content = getFileContent(file);
testData.addOutput(content);
} else if (filename.matches("input.*\\.graphql")) {
// Special case to cater for multiple input*.graphql files where the
// test will pass on the first file input content which is successful.
// If no content matches, then the test will fail.
String content = getFileContent(file);
testData.addInput(content);
} else {
switch (filename) {
case "httpHeader.properties": {
Properties properties = new Properties();
properties.load(Files.newInputStream(file));
testData.setHttpHeaders(properties);
break;
}
case "variables.json": {
String content = getFileContent(file);
testData.setVariables(toJsonObject(content));
break;
}
case "test.properties": {
Properties properties = new Properties();
properties.load(Files.newInputStream(file));
testData.setProperties(properties);
break;
}
case "cleanup.graphql": {
String content = getFileContent(file);
testData.setCleanup(content);
break;
}
case "prepare.graphql": {
String content = getFileContent(file);
testData.setPrepare(content);
break;
}
default:
LOG.warnf("Ignoring unknown file {0}", filename);
break;
}
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
LOG.errorf("Could not load file {0}[{1}]", new Object[] { file, exc.getMessage() });
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
return testData;
}
private static List<org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData> toTestDataForSchema(Path testFile)
throws IOException {
List<org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData> testDataList = new LinkedList<>();
List<String> content = Files.readAllLines(testFile);
String currentHeader = "";
for (String line : content) {
if (validLine(line)) {
String[] parts = line.split(DELIMITER);
if (parts.length == 4) {
org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData testData = createTestDataForSchema(
currentHeader, testFile.getFileName().toString(), parts);
testDataList.add(testData);
} else {
LOG.logf(Logger.Level.ERROR, "Could not add test case {0} - {1}",
new Object[] { testFile.getFileName().toString(),
"Does not contain 3 parts [" + parts.length + "]" });
}
} else if (isHeader(line)) {
currentHeader = line.substring(line.indexOf(COMMENT) + 1).trim();
}
}
return testDataList;
}
private static org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData createTestDataForSchema(String header,
String filename, String[] parts) {
org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData testData = new org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData();
testData.setCount(Integer.valueOf(parts[0]));
testData.setHeader(header);
testData.setName(filename);
String count = parts[0].trim();
String snippet = parts[1].trim();
if (snippet == null || snippet.isEmpty()) {
snippet = null;
}
testData.setSnippetSearchTerm(snippet);
String containsString = parts[2].trim();
if (containsString.contains(OR)) {
String[] containsStrings = containsString.split(OR);
for (String oneOf : containsStrings) {
testData.addContainsString(oneOf.trim());
}
} else {
testData.addContainsString(containsString);
}
testData.setErrorMessage("(" + count + ") - " + parts[3].trim());
return testData;
}
private static boolean validLine(String line) {
return !line.isEmpty() && line.trim().contains(PIPE) && !isHeader(line);
}
private static boolean isHeader(String line) {
return line.trim().startsWith(COMMENT);
}
private JsonObject toJsonObject(String jsonString) {
if (jsonString == null || jsonString.isEmpty()) {
return null;
}
try (JsonReader jsonReader = Json.createReader(new StringReader(jsonString))) {
return jsonReader.readObject();
}
}
private String getFileContent(Path file) throws IOException {
return new String(Files.readAllBytes(file));
}
@Override
public void onTestStart(ITestResult itr) {
if (itr.getTestClass().getName().equals(EXECUTION_TEST)) {
onExecutionTestStart(itr);
} else if (itr.getTestClass().getName().equals(SCHEMA_TEST)) {
onSchemaTestStart(itr);
}
super.onTestStart(itr);
}
private void onSchemaTestStart(ITestResult itr) {
if (itr.getName().equals("testPartsOfSchema")) { // We only override the input data
org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData testData = getSchemaTestData(itr.getParameters());
int key = generateKey(testData);
if (!schemaTestDataMap.isEmpty() && schemaTestDataMap.containsKey(key)) {
LOG.info("\n\t =================================================="
+ "\n\t Schema: Testing Override [" + testData.getCount() + "] " + testData.getHeader() + " in "
+ testData.getName()
+ "\n\t =================================================="
+ "\n");
org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData overrideTestData = schemaTestDataMap.get(key);
testData.setContainsAnyOfString(overrideTestData.getContainsAnyOfString());
testData.setErrorMessage(overrideTestData.getErrorMessage());
testData.setSnippetSearchTerm(overrideTestData.getSnippetSearchTerm());
}
}
}
private void onExecutionTestStart(ITestResult itr) {
org.eclipse.microprofile.graphql.tck.dynamic.execution.TestData testData = getExecutionTestData(itr.getParameters());
LOG.info("\n\t =================================================="
+ "\n\t Execution: Testing [" + testData.getName() + "]"
+ "\n\t =================================================="
+ "\n");
if (itr.getName().startsWith(TEST_SPECIFICATION) && !executionTestDataMap.isEmpty()
&& executionTestDataMap.containsKey(testData.getName())) {
org.eclipse.microprofile.graphql.tck.dynamic.execution.TestData override = executionTestDataMap
.get(testData.getName());
if (override.getCleanup() != null && !override.getCleanup().isEmpty()) {
testData.setCleanup(override.getCleanup());
LOG.warn("\n\t NOTE: Overriding Cleanup");
}
if (override.getHttpHeaders() != null && !override.getHttpHeaders().isEmpty()) {
testData.setHttpHeaders(override.getHttpHeaders());
LOG.warn("\n\t NOTE: Overriding HTTP Headers");
}
if (override.getInput() != null && !override.getInput().isEmpty()) {
testData.setInput(override.getInput());
LOG.warn("\n\t NOTE: Overriding Input");
}
if (override.getOutput() != null && !override.getOutput().isEmpty()) {
testData.setOutput(override.getOutput());
LOG.warn("\n\t NOTE: Overriding Output");
}
if (override.getPrepare() != null && !override.getPrepare().isEmpty()) {
testData.setPrepare(override.getPrepare());
LOG.warn("\n\t NOTE: Overriding Prepare");
}
if (override.getProperties() != null && !override.getProperties().isEmpty()) {
testData.setProperties(override.getProperties());
LOG.warn("\n\t NOTE: Overriding Properties");
}
if (override.getVariables() != null && !override.getVariables().isEmpty()) {
testData.setVariables(override.getVariables());
LOG.warn("\n\t NOTE: Overriding Variables");
}
}
}
private org.eclipse.microprofile.graphql.tck.dynamic.execution.TestData getExecutionTestData(Object[] parameters) {
for (Object param : parameters) {
if (org.eclipse.microprofile.graphql.tck.dynamic.execution.TestData.class.isInstance(param)) {
return org.eclipse.microprofile.graphql.tck.dynamic.execution.TestData.class.cast(param);
}
}
return null;
}
private org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData getSchemaTestData(Object[] parameters) {
for (Object param : parameters) {
if (org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData.class.isInstance(param)) {
return org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData.class.cast(param);
}
}
throw new RuntimeException("Could not find TestData for SchemaTest");
}
private int generateKey(org.eclipse.microprofile.graphql.tck.dynamic.schema.TestData data) {
String concat = data.getName() + data.getHeader() + data.getCount();
return concat.hashCode();
}
}
| TestInterceptor |
java | quarkusio__quarkus | integration-tests/kafka-devservices/src/test/java/io/quarkus/it/kafka/DevServicesKafkaCustomPortITest.java | {
"start": 486,
"end": 961
} | class ____ {
@Test
@DisplayName("should start kafka container with the given custom port")
public void shouldStartKafkaContainer() {
Assertions.assertTrue(SocketKit.isPortAlreadyUsed(5050));
RestAssured.when().get("/kafka/port").then().body(Matchers.is("5050"));
}
@Test
public void shouldBeCorrectImage() {
RestAssured.when().get("/kafka/image").then().body(Matchers.is("kafka-native"));
}
}
| DevServicesKafkaCustomPortITest |
java | apache__spark | common/unsafe/src/main/java/org/apache/spark/sql/catalyst/util/CollationFactory.java | {
"start": 14123,
"end": 14460
} | enum ____ from collation ID.
*/
private static DefinitionOrigin getDefinitionOrigin(int collationId) {
return DefinitionOrigin.values()[SpecifierUtils.getSpecValue(collationId,
DEFINITION_ORIGIN_OFFSET, DEFINITION_ORIGIN_MASK)];
}
/**
* Utility function to retrieve `SpaceTrimming` | instance |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnsynchronizedOverridesSynchronizedTest.java | {
"start": 1446,
"end": 1915
} | class ____ extends Super {
int counter;
// BUG: Diagnostic contains: f overrides synchronized method in Super
// synchronized void f()
void f() {
counter++;
}
}
""")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"test/Super.java",
"""
package test;
| Test |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/CustomNonBlockingReturnTypeTest.java | {
"start": 4578,
"end": 5717
} | class ____<T extends HasMessage> implements ServerMessageBodyWriter<T> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, ResteasyReactiveResourceInfo target,
MediaType mediaType) {
return HasMessage.class.isAssignableFrom(type);
}
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return HasMessage.class.isAssignableFrom(type);
}
@Override
public void writeResponse(T o, Type genericType, ServerRequestContext context)
throws WebApplicationException {
context.serverResponse().end(o.getMessage());
}
@Override
public void writeTo(T o, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
entityStream.write(o.getMessage().getBytes(StandardCharsets.UTF_8));
}
}
}
| HasMessageMessageBodyWriter |
java | quarkusio__quarkus | extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/CurrentVertxRequest.java | {
"start": 196,
"end": 998
} | class ____ {
private RoutingContext current;
private Object otherHttpContextObject;
@Produces
@RequestScoped
public RoutingContext getCurrent() {
return current;
}
public CurrentVertxRequest setCurrent(RoutingContext current) {
this.current = current;
return this;
}
public CurrentVertxRequest setCurrent(RoutingContext current, Object otherHttpContextObject) {
this.current = current;
this.otherHttpContextObject = otherHttpContextObject;
return this;
}
public Object getOtherHttpContextObject() {
return otherHttpContextObject;
}
public void setOtherHttpContextObject(Object otherHttpContextObject) {
this.otherHttpContextObject = otherHttpContextObject;
}
}
| CurrentVertxRequest |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/calcite/rel/logical/LogicalTableScan.java | {
"start": 1500,
"end": 2367
} | class ____ copied from Calcite because the {@link #explainTerms} should consider hints.
*
* <p>If the table is a <code>net.sf.saffron.ext.JdbcTable</code>, then this is literally possible.
* But for other kinds of tables, there may be many ways to read the data from the table. For some
* kinds of table, it may not even be possible to read all of the rows unless some narrowing
* constraint is applied.
*
* <p>In the example of the <code>net.sf.saffron.ext.ReflectSchema</code> schema,
*
* <blockquote>
*
* <pre>select from fields</pre>
*
* </blockquote>
*
* <p>cannot be implemented, but
*
* <blockquote>
*
* <pre>select from fields as f
* where f.getClass().getName().equals("java.lang.String")</pre>
*
* </blockquote>
*
* <p>can. It is the optimizer's responsibility to find these ways, by applying transformation
* rules.
*/
public final | is |
java | apache__rocketmq | common/src/main/java/org/apache/rocketmq/common/compression/Lz4Compressor.java | {
"start": 1220,
"end": 3327
} | class ____ implements Compressor {
private static final Logger log = LoggerFactory.getLogger(LoggerName.COMMON_LOGGER_NAME);
@Override
public byte[] compress(byte[] src, int level) throws IOException {
byte[] result = src;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(src.length);
LZ4FrameOutputStream outputStream = new LZ4FrameOutputStream(byteArrayOutputStream);
try {
outputStream.write(src);
outputStream.flush();
outputStream.close();
result = byteArrayOutputStream.toByteArray();
} catch (IOException e) {
log.error("Failed to compress data by lz4", e);
throw e;
} finally {
try {
byteArrayOutputStream.close();
} catch (IOException ignored) {
}
}
return result;
}
@Override
public byte[] decompress(byte[] src) throws IOException {
byte[] result = src;
byte[] uncompressData = new byte[src.length];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(src);
LZ4FrameInputStream lz4InputStream = new LZ4FrameInputStream(byteArrayInputStream);
ByteArrayOutputStream resultOutputStream = new ByteArrayOutputStream(src.length);
try {
while (true) {
int len = lz4InputStream.read(uncompressData, 0, uncompressData.length);
if (len <= 0) {
break;
}
resultOutputStream.write(uncompressData, 0, len);
}
resultOutputStream.flush();
resultOutputStream.close();
result = resultOutputStream.toByteArray();
} catch (IOException e) {
throw e;
} finally {
try {
lz4InputStream.close();
byteArrayInputStream.close();
} catch (IOException e) {
log.warn("Failed to close the lz4 compress stream ", e);
}
}
return result;
}
}
| Lz4Compressor |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Owner.java | {
"start": 484,
"end": 854
} | class ____ {
private Integer id;
private Set<String> elements = new HashSet<String>();
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@ElementCollection
public Set<String> getElements() {
return elements;
}
public void setElements(Set<String> elements) {
this.elements = elements;
}
}
| Owner |
java | quarkusio__quarkus | extensions/flyway/deployment/src/test/java/io/quarkus/flyway/test/FlywayExtensionCallback.java | {
"start": 287,
"end": 1410
} | class ____ implements Callback {
public static List<Event> DEFAULT_EVENTS = Arrays.asList(
Event.BEFORE_BASELINE,
Event.AFTER_BASELINE,
Event.BEFORE_MIGRATE,
Event.BEFORE_EACH_MIGRATE,
Event.AFTER_EACH_MIGRATE,
Event.AFTER_VERSIONED,
Event.AFTER_MIGRATE,
Event.AFTER_MIGRATE_OPERATION_FINISH);
@Override
public boolean supports(Event event, Context context) {
return DEFAULT_EVENTS.contains(event);
}
@Override
public boolean canHandleInTransaction(Event event, Context context) {
return true;
}
@Override
public void handle(Event event, Context context) {
try (Statement stmt = context.getConnection().createStatement()) {
stmt.executeUpdate("INSERT INTO quarked_callback(name) VALUES('" + event.getId() + "')");
} catch (SQLException exception) {
throw new IllegalStateException(exception);
}
}
@Override
public String getCallbackName() {
return "Quarked Flyway Callback";
}
}
| FlywayExtensionCallback |
java | square__retrofit | retrofit/java-test/src/test/java/retrofit2/RequestFactoryTest.java | {
"start": 96315,
"end": 96753
} | class ____ {
@GET("ftp://example.org")
Call<ResponseBody> get() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessageThat()
.isEqualTo("Malformed URL. Base: http://example.com/, Relative: ftp://example.org");
}
}
@Test
public void malformedParameterRelativeUrlThrows() {
| Example |
java | quarkusio__quarkus | extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/i18n/PrioritizedLocalizedFilesMergeTest.java | {
"start": 479,
"end": 1439
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClass(Messages.class)
.addAsResource(new StringAsset("hello=Hi!\ngoodbye=Bye"), "messages/msg_en.properties"))
.withAdditionalDependency(
d -> d.addAsResource(new StringAsset("""
hello=Hey!
goodbye=Byebye
foo=Alpha
"""), "messages/msg.properties"))
.overrideConfigKey("quarkus.default-locale", "en");
@Localized("en")
Messages messages;
@Test
public void testMerge() {
assertEquals("Hello", messages.hello());
assertEquals("Bye", messages.goodbye());
assertEquals("Alpha", messages.foo());
}
@MessageBundle(DEFAULT_NAME)
public | PrioritizedLocalizedFilesMergeTest |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationPredicatesTests.java | {
"start": 1136,
"end": 4700
} | class ____ {
@Test
void typeInStringArrayWhenNameMatchesAccepts() {
MergedAnnotation<TestAnnotation> annotation = MergedAnnotations.from(
WithTestAnnotation.class).get(TestAnnotation.class);
assertThat(MergedAnnotationPredicates.typeIn(
TestAnnotation.class.getName())).accepts(annotation);
}
@Test
void typeInStringArrayWhenNameDoesNotMatchRejects() {
MergedAnnotation<TestAnnotation> annotation = MergedAnnotations.from(
WithTestAnnotation.class).get(TestAnnotation.class);
assertThat(MergedAnnotationPredicates.typeIn(
MissingAnnotation.class.getName())).rejects(annotation);
}
@Test
void typeInClassArrayWhenNameMatchesAccepts() {
MergedAnnotation<TestAnnotation> annotation =
MergedAnnotations.from(WithTestAnnotation.class).get(TestAnnotation.class);
assertThat(MergedAnnotationPredicates.typeIn(TestAnnotation.class)).accepts(annotation);
}
@Test
void typeInClassArrayWhenNameDoesNotMatchRejects() {
MergedAnnotation<TestAnnotation> annotation =
MergedAnnotations.from(WithTestAnnotation.class).get(TestAnnotation.class);
assertThat(MergedAnnotationPredicates.typeIn(MissingAnnotation.class)).rejects(annotation);
}
@Test
void typeInCollectionWhenMatchesStringInCollectionAccepts() {
MergedAnnotation<TestAnnotation> annotation = MergedAnnotations.from(
WithTestAnnotation.class).get(TestAnnotation.class);
assertThat(MergedAnnotationPredicates.typeIn(
Collections.singleton(TestAnnotation.class.getName()))).accepts(annotation);
}
@Test
void typeInCollectionWhenMatchesClassInCollectionAccepts() {
MergedAnnotation<TestAnnotation> annotation = MergedAnnotations.from(
WithTestAnnotation.class).get(TestAnnotation.class);
assertThat(MergedAnnotationPredicates.typeIn(
Collections.singleton(TestAnnotation.class))).accepts(annotation);
}
@Test
void typeInCollectionWhenDoesNotMatchAnyRejects() {
MergedAnnotation<TestAnnotation> annotation = MergedAnnotations.from(
WithTestAnnotation.class).get(TestAnnotation.class);
assertThat(MergedAnnotationPredicates.typeIn(Arrays.asList(
MissingAnnotation.class.getName(), MissingAnnotation.class))).rejects(annotation);
}
@Test
void firstRunOfAcceptsOnlyFirstRun() {
List<MergedAnnotation<TestAnnotation>> filtered = MergedAnnotations.from(
WithMultipleTestAnnotation.class).stream(TestAnnotation.class).filter(
MergedAnnotationPredicates.firstRunOf(
this::firstCharOfValue)).toList();
assertThat(filtered.stream().map(
annotation -> annotation.getString("value"))).containsExactly("a1", "a2", "a3");
}
@Test
void firstRunOfWhenValueExtractorIsNullThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() ->
MergedAnnotationPredicates.firstRunOf(null));
}
@Test
void uniqueAcceptsUniquely() {
List<MergedAnnotation<TestAnnotation>> filtered = MergedAnnotations.from(
WithMultipleTestAnnotation.class).stream(TestAnnotation.class).filter(
MergedAnnotationPredicates.unique(
this::firstCharOfValue)).toList();
assertThat(filtered.stream().map(
annotation -> annotation.getString("value"))).containsExactly("a1", "b1", "c1");
}
@Test
void uniqueWhenKeyExtractorIsNullThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() ->
MergedAnnotationPredicates.unique(null));
}
private char firstCharOfValue(MergedAnnotation<TestAnnotation> annotation) {
return annotation.getString("value").charAt(0);
}
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(TestAnnotations.class)
@ | MergedAnnotationPredicatesTests |
java | apache__hadoop | hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-workload/src/main/java/org/apache/hadoop/tools/dynamometer/workloadgenerator/audit/UserCommandKey.java | {
"start": 1356,
"end": 3060
} | class ____ implements WritableComparable {
private Text user;
private Text command;
private Text type;
public UserCommandKey() {
user = new Text();
command = new Text();
type = new Text();
}
public UserCommandKey(Text user, Text command, Text type) {
this.user = user;
this.command = command;
this.type = type;
}
public UserCommandKey(String user, String command, String type) {
this.user = new Text(user);
this.command = new Text(command);
this.type = new Text(type);
}
public String getUser() {
return user.toString();
}
public String getCommand() {
return command.toString();
}
public String getType() {
return type.toString();
}
@Override
public void write(DataOutput out) throws IOException {
user.write(out);
command.write(out);
type.write(out);
}
@Override
public void readFields(DataInput in) throws IOException {
user.readFields(in);
command.readFields(in);
type.readFields(in);
}
@Override
public int compareTo(@Nonnull Object o) {
return toString().compareTo(o.toString());
}
@Override
public String toString() {
return getUser() + "," + getType() + "," + getCommand();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UserCommandKey that = (UserCommandKey) o;
return getUser().equals(that.getUser()) &&
getCommand().equals(that.getCommand()) &&
getType().equals(that.getType());
}
@Override
public int hashCode() {
return Objects.hash(getUser(), getCommand(), getType());
}
}
| UserCommandKey |
java | quarkusio__quarkus | extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/client/TlsClientEndpointMissingTlsConfigurationTest.java | {
"start": 1995,
"end": 2141
} | class ____ {
@OnOpen
void open() {
}
}
@WebSocketClient(path = "/endpoint/{name}")
public static | ServerEndpoint |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/state/WindowBytesStoreSupplier.java | {
"start": 1357,
"end": 2446
} | interface ____ extends StoreSupplier<WindowStore<Bytes, byte[]>> {
/**
* The size of the segments (in milliseconds) the store has.
* If your store is segmented then this should be the size of segments in the underlying store.
* It is also used to reduce the amount of data that is scanned when caching is enabled.
*
* @return size of the segments (in milliseconds)
*/
long segmentIntervalMs();
/**
* The size of the windows (in milliseconds) any store created from this supplier is creating.
*
* @return window size
*/
long windowSize();
/**
* Whether or not this store is retaining duplicate keys.
* Usually only true if the store is being used for joins.
* Note this should return false if caching is enabled.
*
* @return true if duplicates should be retained
*/
boolean retainDuplicates();
/**
* The time period for which the {@link WindowStore} will retain historic data.
*
* @return retentionPeriod
*/
long retentionPeriod();
}
| WindowBytesStoreSupplier |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java | {
"start": 2912,
"end": 37627
} | class ____ implements EventProcessor<ApplicationEvent> {
private final Logger log;
private final Metadata metadata;
private final SubscriptionState subscriptions;
private final RequestManagers requestManagers;
private int metadataVersionSnapshot;
public ApplicationEventProcessor(final LogContext logContext,
final RequestManagers requestManagers,
final Metadata metadata,
final SubscriptionState subscriptions) {
this.log = logContext.logger(ApplicationEventProcessor.class);
this.requestManagers = requestManagers;
this.metadata = metadata;
this.subscriptions = subscriptions;
this.metadataVersionSnapshot = metadata.updateVersion();
}
@SuppressWarnings({"CyclomaticComplexity", "JavaNCSSCheck"})
@Override
public void process(ApplicationEvent event) {
switch (event.type()) {
case ASYNC_POLL:
process((AsyncPollEvent) event);
return;
case SHARE_POLL:
process((SharePollEvent) event);
return;
case COMMIT_ASYNC:
process((AsyncCommitEvent) event);
return;
case COMMIT_SYNC:
process((SyncCommitEvent) event);
return;
case FETCH_COMMITTED_OFFSETS:
process((FetchCommittedOffsetsEvent) event);
return;
case ASSIGNMENT_CHANGE:
process((AssignmentChangeEvent) event);
return;
case TOPIC_METADATA:
process((TopicMetadataEvent) event);
return;
case ALL_TOPICS_METADATA:
process((AllTopicsMetadataEvent) event);
return;
case LIST_OFFSETS:
process((ListOffsetsEvent) event);
return;
case RESET_OFFSET:
process((ResetOffsetEvent) event);
return;
case CHECK_AND_UPDATE_POSITIONS:
process((CheckAndUpdatePositionsEvent) event);
return;
case TOPIC_SUBSCRIPTION_CHANGE:
process((TopicSubscriptionChangeEvent) event);
return;
case TOPIC_PATTERN_SUBSCRIPTION_CHANGE:
process((TopicPatternSubscriptionChangeEvent) event);
return;
case TOPIC_RE2J_PATTERN_SUBSCRIPTION_CHANGE:
process((TopicRe2JPatternSubscriptionChangeEvent) event);
return;
case UPDATE_SUBSCRIPTION_METADATA:
process((UpdatePatternSubscriptionEvent) event);
return;
case UNSUBSCRIBE:
process((UnsubscribeEvent) event);
return;
case CONSUMER_REBALANCE_LISTENER_CALLBACK_COMPLETED:
process((ConsumerRebalanceListenerCallbackCompletedEvent) event);
return;
case COMMIT_ON_CLOSE:
process((CommitOnCloseEvent) event);
return;
case LEAVE_GROUP_ON_CLOSE:
process((LeaveGroupOnCloseEvent) event);
return;
case STOP_FIND_COORDINATOR_ON_CLOSE:
process((StopFindCoordinatorOnCloseEvent) event);
return;
case CREATE_FETCH_REQUESTS:
process((CreateFetchRequestsEvent) event);
return;
case SHARE_FETCH:
process((ShareFetchEvent) event);
return;
case SHARE_ACKNOWLEDGE_SYNC:
process((ShareAcknowledgeSyncEvent) event);
return;
case SHARE_ACKNOWLEDGE_ASYNC:
process((ShareAcknowledgeAsyncEvent) event);
return;
case SHARE_SUBSCRIPTION_CHANGE:
process((ShareSubscriptionChangeEvent) event);
return;
case SHARE_UNSUBSCRIBE:
process((ShareUnsubscribeEvent) event);
return;
case SHARE_ACKNOWLEDGE_ON_CLOSE:
process((ShareAcknowledgeOnCloseEvent) event);
return;
case SHARE_ACKNOWLEDGEMENT_COMMIT_CALLBACK_REGISTRATION:
process((ShareAcknowledgementCommitCallbackRegistrationEvent) event);
return;
case SEEK_UNVALIDATED:
process((SeekUnvalidatedEvent) event);
return;
case PAUSE_PARTITIONS:
process((PausePartitionsEvent) event);
return;
case RESUME_PARTITIONS:
process((ResumePartitionsEvent) event);
return;
case CURRENT_LAG:
process((CurrentLagEvent) event);
return;
case STREAMS_ON_TASKS_REVOKED_CALLBACK_COMPLETED:
process((StreamsOnTasksRevokedCallbackCompletedEvent) event);
return;
case STREAMS_ON_TASKS_ASSIGNED_CALLBACK_COMPLETED:
process((StreamsOnTasksAssignedCallbackCompletedEvent) event);
return;
case STREAMS_ON_ALL_TASKS_LOST_CALLBACK_COMPLETED:
process((StreamsOnAllTasksLostCallbackCompletedEvent) event);
return;
default:
log.warn("Application event type {} was not expected", event.type());
}
}
private void process(final SharePollEvent event) {
requestManagers.consumerMembershipManager.ifPresent(consumerMembershipManager ->
consumerMembershipManager.maybeReconcile(true));
requestManagers.shareHeartbeatRequestManager.ifPresent(hrm -> {
hrm.membershipManager().onConsumerPoll();
hrm.resetPollTimer(event.pollTimeMs());
});
}
private void process(final CreateFetchRequestsEvent event) {
CompletableFuture<Void> future = requestManagers.fetchRequestManager.createFetchRequests();
future.whenComplete(complete(event.future()));
}
private void process(final AsyncCommitEvent event) {
if (requestManagers.commitRequestManager.isEmpty()) {
event.future().completeExceptionally(new KafkaException("Unable to async commit " +
"offset because the CommitRequestManager is not available. Check if group.id was set correctly"));
return;
}
try {
CommitRequestManager manager = requestManagers.commitRequestManager.get();
Map<TopicPartition, OffsetAndMetadata> offsets = event.offsets().orElseGet(subscriptions::allConsumed);
event.markOffsetsReady();
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> future = manager.commitAsync(offsets);
future.whenComplete(complete(event.future()));
} catch (Exception e) {
event.future().completeExceptionally(e);
}
}
private void process(final SyncCommitEvent event) {
if (requestManagers.commitRequestManager.isEmpty()) {
event.future().completeExceptionally(new KafkaException("Unable to sync commit " +
"offset because the CommitRequestManager is not available. Check if group.id was set correctly"));
return;
}
try {
CommitRequestManager manager = requestManagers.commitRequestManager.get();
Map<TopicPartition, OffsetAndMetadata> offsets = event.offsets().orElseGet(subscriptions::allConsumed);
event.markOffsetsReady();
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> future = manager.commitSync(offsets, event.deadlineMs());
future.whenComplete(complete(event.future()));
} catch (Exception e) {
event.future().completeExceptionally(e);
}
}
private void process(final FetchCommittedOffsetsEvent event) {
if (requestManagers.commitRequestManager.isEmpty()) {
event.future().completeExceptionally(new KafkaException("Unable to fetch committed " +
"offset because the CommitRequestManager is not available. Check if group.id was set correctly"));
return;
}
CommitRequestManager manager = requestManagers.commitRequestManager.get();
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> future = manager.fetchOffsets(event.partitions(), event.deadlineMs());
future.whenComplete(complete(event.future()));
}
/**
* Commit all consumed if auto-commit is enabled. Note this will trigger an async commit,
* that will not be retried if the commit request fails.
*/
private void process(final AssignmentChangeEvent event) {
if (requestManagers.commitRequestManager.isPresent()) {
CommitRequestManager manager = requestManagers.commitRequestManager.get();
manager.updateTimerAndMaybeCommit(event.currentTimeMs());
}
log.info("Assigned to partition(s): {}", event.partitions());
try {
if (subscriptions.assignFromUser(new HashSet<>(event.partitions())))
metadata.requestUpdateForNewTopics();
event.future().complete(null);
} catch (Exception e) {
event.future().completeExceptionally(e);
}
}
/**
* Handles ListOffsetsEvent by fetching the offsets for the given partitions and timestamps.
*/
private void process(final ListOffsetsEvent event) {
final CompletableFuture<Map<TopicPartition, OffsetAndTimestampInternal>> future =
requestManagers.offsetsRequestManager.fetchOffsets(event.timestampsToSearch(), event.requireTimestamps());
future.whenComplete(complete(event.future()));
}
/**
* Process event that indicates that the subscription topics changed. This will make the
* consumer join the group if it is not part of it yet, or send the updated subscription if
* it is already a member on the next poll.
*/
private void process(final TopicSubscriptionChangeEvent event) {
if (requestManagers.consumerHeartbeatRequestManager.isPresent()) {
try {
if (subscriptions.subscribe(event.topics(), event.listener())) {
this.metadataVersionSnapshot = metadata.requestUpdateForNewTopics();
}
// Join the group if not already part of it, or just send the new subscription to the broker on the next poll.
requestManagers.consumerHeartbeatRequestManager.get().membershipManager().onSubscriptionUpdated();
event.future().complete(null);
} catch (Exception e) {
event.future().completeExceptionally(e);
}
} else if (requestManagers.streamsGroupHeartbeatRequestManager.isPresent()) {
try {
if (subscriptions.subscribe(event.topics(), event.listener())) {
this.metadataVersionSnapshot = metadata.requestUpdateForNewTopics();
}
requestManagers.streamsGroupHeartbeatRequestManager.get().membershipManager().onSubscriptionUpdated();
event.future().complete(null);
} catch (Exception e) {
event.future().completeExceptionally(e);
}
} else {
log.warn("Group membership manager not present when processing a subscribe event");
event.future().complete(null);
}
}
/**
* Process event that indicates that the subscription java pattern changed.
* This will update the subscription state in the client to persist the new pattern.
* It will also evaluate the pattern against the latest metadata to find the matching topics,
* and send an updated subscription to the broker on the next poll
* (joining the group if it's not already part of it).
*/
private void process(final TopicPatternSubscriptionChangeEvent event) {
try {
subscriptions.subscribe(event.pattern(), event.listener());
metadata.requestUpdateForNewTopics();
requestManagers.consumerHeartbeatRequestManager.ifPresent(hrm -> {
ConsumerMembershipManager membershipManager = hrm.membershipManager();
updatePatternSubscription(membershipManager::onSubscriptionUpdated, metadata.fetch());
});
event.future().complete(null);
} catch (Exception e) {
event.future().completeExceptionally(e);
}
}
/**
* Process event that indicates that the subscription RE2J pattern changed.
* This will update the subscription state in the client to persist the new pattern.
* It will also make the consumer send the updated pattern on the next poll,
* joining the group if it's not already part of it.
* Note that this does not evaluate the pattern, it just passes it to the broker.
*/
private void process(final TopicRe2JPatternSubscriptionChangeEvent event) {
if (requestManagers.consumerMembershipManager.isEmpty()) {
event.future().completeExceptionally(
new KafkaException("MembershipManager is not available when processing a subscribe event"));
return;
}
try {
subscriptions.subscribe(event.pattern(), event.listener());
requestManagers.consumerMembershipManager.get().onSubscriptionUpdated();
event.future().complete(null);
} catch (Exception e) {
event.future().completeExceptionally(e);
}
}
/**
* Process event that re-evaluates the subscribed regular expression using the latest topics from metadata, only if metadata changed.
* This will make the consumer send the updated subscription on the next poll.
*/
private void process(final UpdatePatternSubscriptionEvent event) {
requestManagers.consumerMembershipManager.ifPresent(mm -> maybeUpdatePatternSubscription(mm::onSubscriptionUpdated));
event.future().complete(null);
}
/**
* Process event indicating that the consumer unsubscribed from all topics. This will make
* the consumer release its assignment and send a request to leave the group.
*
* @param event Unsubscribe event containing a future that will complete when the callback
* execution for releasing the assignment completes, and the request to leave
* the group is sent out.
*/
private void process(final UnsubscribeEvent event) {
if (requestManagers.consumerHeartbeatRequestManager.isPresent()) {
CompletableFuture<Void> future = requestManagers.consumerHeartbeatRequestManager.get().membershipManager().leaveGroup();
future.whenComplete(complete(event.future()));
} else if (requestManagers.streamsGroupHeartbeatRequestManager.isPresent()) {
CompletableFuture<Void> future = requestManagers.streamsGroupHeartbeatRequestManager.get().membershipManager().leaveGroup();
future.whenComplete(complete(event.future()));
} else {
// If the consumer is not using the group management capabilities, we still need to clear all assignments it may have.
subscriptions.unsubscribe();
event.future().complete(null);
}
}
private void process(final ResetOffsetEvent event) {
try {
Collection<TopicPartition> parts = event.topicPartitions().isEmpty() ?
subscriptions.assignedPartitions() : event.topicPartitions();
subscriptions.requestOffsetReset(parts, event.offsetResetStrategy());
event.future().complete(null);
} catch (Exception e) {
event.future().completeExceptionally(e);
}
}
/**
* Check if all assigned partitions have fetch positions. If there are missing positions, fetch offsets and use
* them to update positions in the subscription state.
*/
private void process(final CheckAndUpdatePositionsEvent event) {
CompletableFuture<Void> future = requestManagers.offsetsRequestManager.updateFetchPositions(event.deadlineMs());
future.whenComplete(complete(event.future()));
}
private void process(final TopicMetadataEvent event) {
final CompletableFuture<Map<String, List<PartitionInfo>>> future =
requestManagers.topicMetadataRequestManager.requestTopicMetadata(event.topic(), event.deadlineMs());
future.whenComplete(complete(event.future()));
}
private void process(final AllTopicsMetadataEvent event) {
final CompletableFuture<Map<String, List<PartitionInfo>>> future =
requestManagers.topicMetadataRequestManager.requestAllTopicsMetadata(event.deadlineMs());
future.whenComplete(complete(event.future()));
}
private void process(final ConsumerRebalanceListenerCallbackCompletedEvent event) {
if (requestManagers.consumerHeartbeatRequestManager.isEmpty()) {
log.warn(
"An internal error occurred; the group membership manager was not present, so the notification of the {} callback execution could not be sent",
event.methodName()
);
return;
}
requestManagers.consumerHeartbeatRequestManager.get().membershipManager().consumerRebalanceListenerCallbackCompleted(event);
}
private void process(@SuppressWarnings("unused") final CommitOnCloseEvent event) {
if (requestManagers.commitRequestManager.isEmpty())
return;
log.debug("Signal CommitRequestManager closing");
requestManagers.commitRequestManager.get().signalClose();
}
private void process(final LeaveGroupOnCloseEvent event) {
if (requestManagers.consumerMembershipManager.isPresent()) {
log.debug("Signal the ConsumerMembershipManager to leave the consumer group since the consumer is closing");
CompletableFuture<Void> future = requestManagers.consumerMembershipManager.get().leaveGroupOnClose(event.membershipOperation());
future.whenComplete(complete(event.future()));
} else if (requestManagers.streamsMembershipManager.isPresent()) {
log.debug("Signal the StreamsMembershipManager to leave the streams group since the member is closing");
CompletableFuture<Void> future = requestManagers.streamsMembershipManager.get().leaveGroupOnClose();
future.whenComplete(complete(event.future()));
}
}
private void process(@SuppressWarnings("unused") final StopFindCoordinatorOnCloseEvent event) {
requestManagers.coordinatorRequestManager.ifPresent(manager -> {
log.debug("Signal CoordinatorRequestManager closing");
manager.signalClose();
});
}
/**
* Process event that tells the share consume request manager to fetch more records.
*/
private void process(final ShareFetchEvent event) {
requestManagers.shareConsumeRequestManager.ifPresent(scrm -> scrm.fetch(event.acknowledgementsMap()));
}
/**
* Process event that indicates the consumer acknowledged delivery of records synchronously.
*/
private void process(final ShareAcknowledgeSyncEvent event) {
if (requestManagers.shareConsumeRequestManager.isEmpty()) {
return;
}
ShareConsumeRequestManager manager = requestManagers.shareConsumeRequestManager.get();
CompletableFuture<Map<TopicIdPartition, Acknowledgements>> future =
manager.commitSync(event.acknowledgementsMap(), event.deadlineMs());
future.whenComplete(complete(event.future()));
}
/**
* Process event that indicates the consumer acknowledged delivery of records asynchronously.
*/
private void process(final ShareAcknowledgeAsyncEvent event) {
if (requestManagers.shareConsumeRequestManager.isEmpty()) {
return;
}
ShareConsumeRequestManager manager = requestManagers.shareConsumeRequestManager.get();
manager.commitAsync(event.acknowledgementsMap(), event.deadlineMs());
}
/**
* Process event that indicates that the subscription changed for a share group. This will make the
* consumer join the share group if it is not part of it yet, or send the updated subscription if
* it is already a member.
*/
private void process(final ShareSubscriptionChangeEvent event) {
if (requestManagers.shareHeartbeatRequestManager.isEmpty()) {
KafkaException error = new KafkaException("Group membership manager not present when processing a subscribe event");
event.future().completeExceptionally(error);
return;
}
if (subscriptions.subscribeToShareGroup(event.topics()))
metadata.requestUpdateForNewTopics();
requestManagers.shareHeartbeatRequestManager.get().membershipManager().onSubscriptionUpdated();
event.future().complete(null);
}
/**
* Process event indicating that the consumer unsubscribed from all topics. This will make
* the consumer release its assignment and send a request to leave the share group.
*
* @param event Unsubscribe event containing a future that will complete when the callback
* execution for releasing the assignment completes, and the request to leave
* the group is sent out.
*/
private void process(final ShareUnsubscribeEvent event) {
if (requestManagers.shareHeartbeatRequestManager.isEmpty()) {
KafkaException error = new KafkaException("Group membership manager not present when processing an unsubscribe event");
event.future().completeExceptionally(error);
return;
}
subscriptions.unsubscribe();
CompletableFuture<Void> future = requestManagers.shareHeartbeatRequestManager.get().membershipManager().leaveGroup();
// The future will be completed on heartbeat sent
future.whenComplete(complete(event.future()));
}
/**
* Process event indicating that the consumer is closing. This will make the consumer
* complete pending acknowledgements.
*
* @param event Acknowledge-on-close event containing a future that will complete when
* the acknowledgements have responses.
*/
private void process(final ShareAcknowledgeOnCloseEvent event) {
if (requestManagers.shareConsumeRequestManager.isEmpty()) {
KafkaException error = new KafkaException("Group membership manager not present when processing an acknowledge-on-close event");
event.future().completeExceptionally(error);
return;
}
ShareConsumeRequestManager manager = requestManagers.shareConsumeRequestManager.get();
CompletableFuture<Void> future = manager.acknowledgeOnClose(event.acknowledgementsMap(), event.deadlineMs());
future.whenComplete(complete(event.future()));
}
/**
* Process event indicating whether the AcknowledgeCommitCallbackHandler is configured by the user.
*
* @param event Event containing a boolean to indicate if the callback handler is configured or not.
*/
private void process(final ShareAcknowledgementCommitCallbackRegistrationEvent event) {
if (requestManagers.shareConsumeRequestManager.isEmpty()) {
return;
}
ShareConsumeRequestManager manager = requestManagers.shareConsumeRequestManager.get();
manager.setAcknowledgementCommitCallbackRegistered(event.isCallbackRegistered());
}
private void process(final SeekUnvalidatedEvent event) {
try {
event.offsetEpoch().ifPresent(epoch -> metadata.updateLastSeenEpochIfNewer(event.partition(), epoch));
SubscriptionState.FetchPosition newPosition = new SubscriptionState.FetchPosition(
event.offset(),
event.offsetEpoch(),
metadata.currentLeader(event.partition())
);
subscriptions.seekUnvalidated(event.partition(), newPosition);
event.future().complete(null);
} catch (Exception e) {
event.future().completeExceptionally(e);
}
}
private void process(final PausePartitionsEvent event) {
try {
Collection<TopicPartition> partitions = event.partitions();
log.debug("Pausing partitions {}", partitions);
for (TopicPartition partition : partitions) {
subscriptions.pause(partition);
}
event.future().complete(null);
} catch (Exception e) {
event.future().completeExceptionally(e);
}
}
private void process(final ResumePartitionsEvent event) {
try {
Collection<TopicPartition> partitions = event.partitions();
log.debug("Resuming partitions {}", partitions);
for (TopicPartition partition : partitions) {
subscriptions.resume(partition);
}
event.future().complete(null);
} catch (Exception e) {
event.future().completeExceptionally(e);
}
}
private void process(final CurrentLagEvent event) {
try {
final TopicPartition topicPartition = event.partition();
final IsolationLevel isolationLevel = event.isolationLevel();
final Long lag = subscriptions.partitionLag(topicPartition, isolationLevel);
final OptionalLong lagOpt;
if (lag == null) {
if (subscriptions.partitionEndOffset(topicPartition, isolationLevel) == null &&
!subscriptions.partitionEndOffsetRequested(topicPartition)) {
// If the log end offset is unknown and there isn't already an in-flight list offset
// request, issue one with the goal that the lag will be available the next time the
// user calls currentLag().
log.info("Requesting the log end offset for {} in order to compute lag", topicPartition);
subscriptions.requestPartitionEndOffset(topicPartition);
// Emulates the Consumer.endOffsets() logic...
Map<TopicPartition, Long> timestampToSearch = Collections.singletonMap(
topicPartition,
ListOffsetsRequest.LATEST_TIMESTAMP
);
requestManagers.offsetsRequestManager.fetchOffsets(timestampToSearch, false);
}
lagOpt = OptionalLong.empty();
} else {
lagOpt = OptionalLong.of(lag);
}
event.future().complete(lagOpt);
} catch (Exception e) {
event.future().completeExceptionally(e);
}
}
private void process(final StreamsOnTasksRevokedCallbackCompletedEvent event) {
if (requestManagers.streamsMembershipManager.isEmpty()) {
log.warn("An internal error occurred; the Streams membership manager was not present, so the notification " +
"of the onTasksRevoked callback execution could not be sent");
return;
}
requestManagers.streamsMembershipManager.get().onTasksRevokedCallbackCompleted(event);
}
private void process(final StreamsOnTasksAssignedCallbackCompletedEvent event) {
if (requestManagers.streamsMembershipManager.isEmpty()) {
log.warn("An internal error occurred; the Streams membership manager was not present, so the notification " +
"of the onTasksAssigned callback execution could not be sent");
return;
}
requestManagers.streamsMembershipManager.get().onTasksAssignedCallbackCompleted(event);
}
private void process(final StreamsOnAllTasksLostCallbackCompletedEvent event) {
if (requestManagers.streamsMembershipManager.isEmpty()) {
log.warn("An internal error occurred; the Streams membership manager was not present, so the notification " +
"of the onAllTasksLost callback execution could not be sent");
return;
}
requestManagers.streamsMembershipManager.get().onAllTasksLostCallbackCompleted(event);
}
private void process(final AsyncPollEvent event) {
// Trigger a reconciliation that can safely commit offsets if needed to rebalance,
// as we're processing before any new fetching starts
requestManagers.consumerMembershipManager.ifPresent(consumerMembershipManager ->
consumerMembershipManager.maybeReconcile(true));
if (requestManagers.commitRequestManager.isPresent()) {
CommitRequestManager commitRequestManager = requestManagers.commitRequestManager.get();
commitRequestManager.updateTimerAndMaybeCommit(event.pollTimeMs());
requestManagers.consumerHeartbeatRequestManager.ifPresent(hrm -> {
ConsumerMembershipManager membershipManager = hrm.membershipManager();
maybeUpdatePatternSubscription(membershipManager::onSubscriptionUpdated);
membershipManager.onConsumerPoll();
hrm.resetPollTimer(event.pollTimeMs());
});
requestManagers.streamsGroupHeartbeatRequestManager.ifPresent(hrm -> {
StreamsMembershipManager membershipManager = hrm.membershipManager();
maybeUpdatePatternSubscription(membershipManager::onSubscriptionUpdated);
membershipManager.onConsumerPoll();
hrm.resetPollTimer(event.pollTimeMs());
});
}
CompletableFuture<Void> updatePositionsFuture = requestManagers.offsetsRequestManager.updateFetchPositions(event.deadlineMs());
event.markValidatePositionsComplete();
updatePositionsFuture.whenComplete((__, updatePositionsError) -> {
if (maybeCompleteAsyncPollEventExceptionally(event, updatePositionsError))
return;
requestManagers.fetchRequestManager.createFetchRequests().whenComplete((___, fetchError) -> {
if (maybeCompleteAsyncPollEventExceptionally(event, fetchError))
return;
event.completeSuccessfully();
});
});
}
/**
* If there's an error to report to the user, the current event will be completed and this method will
* return {@code true}. Otherwise, it will return {@code false}.
*/
private boolean maybeCompleteAsyncPollEventExceptionally(AsyncPollEvent event, Throwable t) {
if (t == null)
return false;
if (t instanceof org.apache.kafka.common.errors.TimeoutException || t instanceof java.util.concurrent.TimeoutException) {
log.trace("Ignoring timeout for {}: {}", event, t.getMessage());
return false;
}
if (t instanceof CompletionException) {
t = t.getCause();
}
KafkaException e = ConsumerUtils.maybeWrapAsKafkaException(t);
event.completeExceptionally(e);
log.trace("Failing event processing for {}", event, e);
return true;
}
private <T> BiConsumer<? super T, ? super Throwable> complete(final CompletableFuture<T> b) {
return (value, exception) -> {
if (exception != null)
b.completeExceptionally(exception);
else
b.complete(value);
};
}
/**
* Creates a {@link Supplier} for deferred creation during invocation by
* {@link ConsumerNetworkThread}.
*/
public static Supplier<ApplicationEventProcessor> supplier(final LogContext logContext,
final Metadata metadata,
final SubscriptionState subscriptions,
final Supplier<RequestManagers> requestManagersSupplier) {
return new CachedSupplier<>() {
@Override
protected ApplicationEventProcessor create() {
RequestManagers requestManagers = requestManagersSupplier.get();
return new ApplicationEventProcessor(
logContext,
requestManagers,
metadata,
subscriptions
);
}
};
}
private void maybeUpdatePatternSubscription(MembershipManagerShim membershipManager) {
if (!subscriptions.hasPatternSubscription()) {
return;
}
if (this.metadataVersionSnapshot < metadata.updateVersion()) {
this.metadataVersionSnapshot = metadata.updateVersion();
updatePatternSubscription(membershipManager, metadata.fetch());
}
}
/**
* This function evaluates the regex that the consumer subscribed to
* against the list of topic names from metadata, and updates
* the list of topics in subscription state accordingly
*
* @param cluster Cluster from which we get the topics
*/
private void updatePatternSubscription(MembershipManagerShim membershipManager, Cluster cluster) {
final Set<String> topicsToSubscribe = cluster.topics().stream()
.filter(subscriptions::matchesSubscribedPattern)
.collect(Collectors.toSet());
if (subscriptions.subscribeFromPattern(topicsToSubscribe)) {
this.metadataVersionSnapshot = metadata.requestUpdateForNewTopics();
}
// Join the group if not already part of it, or just send the updated subscription
// to the broker on the next poll. Note that this is done even if no topics matched
// the regex, to ensure the member joins the group if needed (with empty subscription).
membershipManager.onSubscriptionUpdated();
}
// Visible for testing
int metadataVersionSnapshot() {
return metadataVersionSnapshot;
}
/**
* Ideally the {@link AbstractMembershipManager#onSubscriptionUpdated()} API could be invoked directly, but
* unfortunately {@link StreamsMembershipManager} doesn't extend from {@link AbstractMembershipManager}, so
* that method is not directly available. This functional | ApplicationEventProcessor |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/env/MergedPropertiesFilesTestPropertySourceTests.java | {
"start": 1258,
"end": 1524
} | class ____ extends
ExplicitPropertiesFileInClasspathTestPropertySourceTests {
@Test
void verifyExtendedPropertiesAreAvailableInEnvironment() {
assertThat(env.getProperty("extended", Integer.class)).isEqualTo(42);
}
}
| MergedPropertiesFilesTestPropertySourceTests |
java | elastic__elasticsearch | x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/action/AbstractEnrichBasedCrossClusterTestCase.java | {
"start": 11994,
"end": 13974
} | class ____ extends TransportXPackInfoAction {
@Inject
public EnrichTransportXPackInfoAction(
TransportService transportService,
ActionFilters actionFilters,
LicenseService licenseService,
NodeClient client
) {
super(transportService, actionFilters, licenseService, client);
}
@Override
protected List<ActionType<XPackInfoFeatureResponse>> infoActions() {
return Collections.singletonList(XPackInfoFeatureAction.ENRICH);
}
}
@Override
protected Class<? extends TransportAction<XPackInfoRequest, XPackInfoResponse>> getInfoAction() {
return CrossClusterQueriesWithInvalidLicenseIT.LocalStateEnrich.EnrichTransportXPackInfoAction.class;
}
}
protected void assertClusterInfoSuccess(EsqlExecutionInfo.Cluster cluster, int numShards) {
assertThat(cluster.getTook().millis(), greaterThanOrEqualTo(0L));
assertThat(cluster.getStatus(), equalTo(EsqlExecutionInfo.Cluster.Status.SUCCESSFUL));
assertThat(cluster.getTotalShards(), equalTo(numShards));
assertThat(cluster.getSuccessfulShards(), equalTo(numShards));
assertThat(cluster.getSkippedShards(), equalTo(0));
assertThat(cluster.getFailedShards(), equalTo(0));
assertThat(cluster.getFailures().size(), equalTo(0));
}
protected void assertClusterInfoSkipped(EsqlExecutionInfo.Cluster cluster) {
assertThat(cluster.getTook().millis(), greaterThanOrEqualTo(0L));
assertThat(cluster.getStatus(), equalTo(EsqlExecutionInfo.Cluster.Status.SKIPPED));
assertThat(cluster.getTotalShards(), equalTo(0));
assertThat(cluster.getSuccessfulShards(), equalTo(0));
assertThat(cluster.getSkippedShards(), equalTo(0));
assertThat(cluster.getFailedShards(), equalTo(0));
}
}
| EnrichTransportXPackInfoAction |
java | apache__camel | components/camel-aws/camel-aws2-iam/src/main/java/org/apache/camel/component/aws2/iam/client/IAM2ClientFactory.java | {
"start": 1332,
"end": 2213
} | class ____ {
private IAM2ClientFactory() {
}
/**
* Return the correct AWS IAM client (based on remote vs local).
*
* @param configuration configuration
* @return IamClient
*/
public static IAM2InternalClient getIamClient(IAM2Configuration configuration) {
if (Boolean.TRUE.equals(configuration.isUseDefaultCredentialsProvider())) {
return new IAM2ClientOptimizedImpl(configuration);
} else if (Boolean.TRUE.equals(configuration.isUseProfileCredentialsProvider())) {
return new IAM2ClientProfileOptimizedImpl(configuration);
} else if (Boolean.TRUE.equals(configuration.isUseSessionCredentials())) {
return new IAM2ClientSessionTokenImpl(configuration);
} else {
return new IAM2ClientStandardImpl(configuration);
}
}
}
| IAM2ClientFactory |
java | quarkusio__quarkus | extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/devmode/CompileErrorEndpoint.java | {
"start": 123,
"end": 343
} | class ____ {
void addConfigRoute(@Observes Router router) {
router.route("/error")
.produces("text/plain")
.handler(rc -> rc.response().end("error"));
}
}
| CompileErrorEndpoint |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLTruncateStatement.java | {
"start": 954,
"end": 4940
} | class ____ extends SQLStatementImpl {
protected List<SQLExprTableSource> tableSources = new ArrayList<SQLExprTableSource>(2);
private boolean purgeSnapshotLog;
private boolean only;
private Boolean restartIdentity;
private Boolean cascade;
// db2
private boolean dropStorage;
private boolean reuseStorage;
private boolean immediate;
private boolean ignoreDeleteTriggers;
private boolean restrictWhenDeleteTriggers;
private boolean continueIdentity;
protected boolean ifExists;
protected List<SQLAssignItem> partitions = new ArrayList<SQLAssignItem>();
// adb
protected boolean partitionAll;
protected List<SQLIntegerExpr> partitionsForADB = new ArrayList<SQLIntegerExpr>();
public SQLTruncateStatement() {
}
public SQLTruncateStatement(DbType dbType) {
super(dbType);
}
public List<SQLExprTableSource> getTableSources() {
return tableSources;
}
public void setTableSources(List<SQLExprTableSource> tableSources) {
this.tableSources = tableSources;
}
public void addTableSource(SQLName name) {
SQLExprTableSource tableSource = new SQLExprTableSource(name);
tableSource.setParent(this);
this.tableSources.add(tableSource);
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, tableSources);
}
visitor.endVisit(this);
}
public boolean isPurgeSnapshotLog() {
return purgeSnapshotLog;
}
public void setPurgeSnapshotLog(boolean purgeSnapshotLog) {
this.purgeSnapshotLog = purgeSnapshotLog;
}
public boolean isOnly() {
return only;
}
public void setOnly(boolean only) {
this.only = only;
}
public Boolean getRestartIdentity() {
return restartIdentity;
}
public void setRestartIdentity(Boolean restartIdentity) {
this.restartIdentity = restartIdentity;
}
public Boolean getCascade() {
return cascade;
}
public void setCascade(Boolean cascade) {
this.cascade = cascade;
}
public boolean isDropStorage() {
return dropStorage;
}
public void setDropStorage(boolean dropStorage) {
this.dropStorage = dropStorage;
}
public boolean isReuseStorage() {
return reuseStorage;
}
public void setReuseStorage(boolean reuseStorage) {
this.reuseStorage = reuseStorage;
}
public boolean isImmediate() {
return immediate;
}
public void setImmediate(boolean immediate) {
this.immediate = immediate;
}
public boolean isIgnoreDeleteTriggers() {
return ignoreDeleteTriggers;
}
public void setIgnoreDeleteTriggers(boolean ignoreDeleteTriggers) {
this.ignoreDeleteTriggers = ignoreDeleteTriggers;
}
public boolean isRestrictWhenDeleteTriggers() {
return restrictWhenDeleteTriggers;
}
public void setRestrictWhenDeleteTriggers(boolean restrictWhenDeleteTriggers) {
this.restrictWhenDeleteTriggers = restrictWhenDeleteTriggers;
}
public boolean isContinueIdentity() {
return continueIdentity;
}
public void setContinueIdentity(boolean continueIdentity) {
this.continueIdentity = continueIdentity;
}
@Override
public List getChildren() {
return tableSources;
}
public boolean isIfExists() {
return ifExists;
}
public void setIfExists(boolean ifExists) {
this.ifExists = ifExists;
}
public List<SQLAssignItem> getPartitions() {
return partitions;
}
public boolean isPartitionAll() {
return partitionAll;
}
public void setPartitionAll(boolean partitionAll) {
this.partitionAll = partitionAll;
}
public List<SQLIntegerExpr> getPartitionsForADB() {
return partitionsForADB;
}
}
| SQLTruncateStatement |
java | apache__avro | lang/java/ipc/src/main/java/org/apache/avro/ipc/SaslSocketTransceiver.java | {
"start": 12077,
"end": 12963
} | class ____ implements SaslClient {
@Override
public String getMechanismName() {
return "ANONYMOUS";
}
@Override
public boolean hasInitialResponse() {
return true;
}
@Override
public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
return System.getProperty("user.name").getBytes(StandardCharsets.UTF_8);
}
@Override
public boolean isComplete() {
return true;
}
@Override
public byte[] unwrap(byte[] incoming, int offset, int len) {
throw new UnsupportedOperationException();
}
@Override
public byte[] wrap(byte[] outgoing, int offset, int len) {
throw new UnsupportedOperationException();
}
@Override
public Object getNegotiatedProperty(String propName) {
return null;
}
@Override
public void dispose() {
}
}
}
| AnonymousClient |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/util/ConcurrencyThrottleSupport.java | {
"start": 1370,
"end": 1489
} | class ____
* {@link #UNBOUNDED_CONCURRENCY}. Subclasses may override this default;
* check the javadoc of the concrete | is |
java | alibaba__nacos | common/src/main/java/com/alibaba/nacos/common/packagescan/classreading/ClassReader.java | {
"start": 21399,
"end": 21924
} | class ____ or adapters.</i>
*
* @param offset the start index of the value to be read in this {@link ClassReader}.
* @return the read value.
*/
public int readUnsignedShort(final int offset) {
byte[] classBuffer = classFileBuffer;
return ((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF);
}
/**
* Reads a signed short value in this {@link ClassReader}. <i>This method is intended for
* Attribute sub classes, and is normally not needed by | generators |
java | dropwizard__dropwizard | dropwizard-benchmarks/src/main/java/io/dropwizard/benchmarks/util/DataSizeBenchmark.java | {
"start": 582,
"end": 1165
} | class ____ {
/**
* Don't trust the IDE, it's advisedly non-final to avoid constant folding
*/
private String size = "256KiB";
@Benchmark
public DataSize parseSize() {
return DataSize.parse(size);
}
public static void main(String[] args) throws Exception {
new Runner(new OptionsBuilder()
.include(DataSizeBenchmark.class.getSimpleName())
.forks(1)
.warmupIterations(5)
.measurementIterations(5)
.build())
.run();
}
}
| DataSizeBenchmark |
java | apache__maven | impl/maven-di/src/test/java/org/apache/maven/di/impl/InjectorImplTest.java | {
"start": 4537,
"end": 4606
} | interface ____ {}
@Named
@Typed
static | MyService |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/inheritance/MemberLevelInheritanceTest.java | {
"start": 1148,
"end": 2106
} | class ____ {
@RegisterExtension
ArcTestContainer testContainer = new ArcTestContainer(Foo.class, FooExtended.class, DummyBean.class,
MyBinding.class, MyInterceptor.class);
@Test
public void testMemberLevelInheritance() {
ArcContainer container = Arc.container();
// IP inheritance
FooExtended fooExtended = container.instance(FooExtended.class).get();
assertNotNull(fooExtended);
assertNotNull(fooExtended.getBar());
// producer inheritance is tested simply by not getting ambiguous dependency while running the test
// initializer inheritance
assertNotNull(fooExtended.getBeanFromInitMethod());
// interceptor binding on a method inheritance
assertEquals(0, MyInterceptor.timesInvoked);
fooExtended.interceptedMethod();
assertEquals(1, MyInterceptor.timesInvoked);
}
@ApplicationScoped
static | MemberLevelInheritanceTest |
java | alibaba__fastjson | src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectF1.java | {
"start": 143,
"end": 2354
} | class ____ {
long a = -1;
int b = 0;
long c = 0;
int d = 0;
int e = 0;
@JSONField(serialize = false)
String f = "";
transient boolean g;
long h;
long i;
int j;
int k;
int l;
int m;
int n;
List<Long> o;
int p;
int q;
public long getA() {
return a;
}
public void setA(long a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public long getC() {
return c;
}
public void setC(long c) {
this.c = c;
}
public int getD() {
return d;
}
public void setD(int d) {
this.d = d;
}
public int getE() {
return e;
}
public void setE(int e) {
this.e = e;
}
public String getF() {
return f;
}
public void setF(String f) {
this.f = f;
}
public boolean isG() {
return g;
}
public void setG(boolean g) {
this.g = g;
}
public long getH() {
return h;
}
public void setH(long h) {
this.h = h;
}
public long getI() {
return i;
}
public void setI(long i) {
this.i = i;
}
public int getJ() {
return j;
}
public void setJ(int j) {
this.j = j;
}
public int getK() {
return k;
}
public void setK(int k) {
this.k = k;
}
public int getL() {
return l;
}
public void setL(int l) {
this.l = l;
}
public int getM() {
return m;
}
public void setM(int m) {
this.m = m;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public List<Long> getO() {
return o;
}
public void setO(List<Long> o) {
this.o = o;
}
public int getP() {
return p;
}
public void setP(int p) {
this.p = p;
}
public int getQ() {
return q;
}
public void setQ(int q) {
this.q = q;
}
}
| ObjectF1 |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsNotCloseToPercentage_Test.java | {
"start": 1674,
"end": 4592
} | class ____ extends BytesBaseTest {
private static final Byte ZERO = 0;
private static final Byte ONE = 1;
private static final Byte TEN = 10;
private static final Byte ONE_HUNDRED = 100;
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytes.assertIsNotCloseToPercentage(someInfo(), null, ONE,
withPercentage(ONE)))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_expected_value_is_null() {
assertThatNullPointerException().isThrownBy(() -> bytes.assertIsNotCloseToPercentage(someInfo(), ONE, null,
withPercentage(ONE)));
}
@Test
void should_fail_if_percentage_is_null() {
assertThatNullPointerException().isThrownBy(() -> bytes.assertIsNotCloseToPercentage(someInfo(), ONE, ZERO, null));
}
@Test
void should_fail_if_percentage_is_negative() {
assertThatIllegalArgumentException().isThrownBy(() -> bytes.assertIsNotCloseToPercentage(someInfo(), ONE, ZERO,
withPercentage(-1)));
}
@ParameterizedTest
@CsvSource({
"1, 2, 1",
"1, 11, 90",
"-1, -2, 1",
"-1, -11, 90",
"0, -1, 99"
})
void should_pass_if_difference_is_less_than_given_percentage(Byte actual, Byte other, Byte percentage) {
bytes.assertIsNotCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
@ParameterizedTest
@CsvSource({
"1, 1, 0",
"2, 1, 100",
"1, 2, 50",
"-1, -1, 0",
"-2, -1, 100",
"-1, -2, 50"
})
void should_fail_if_difference_is_equal_to_given_percentage(Byte actual, Byte other, Byte percentage) {
AssertionInfo info = someInfo();
Throwable error = catchThrowable(() -> bytes.assertIsNotCloseToPercentage(someInfo(), actual, other,
withPercentage(percentage)));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldNotBeEqualWithinPercentage(actual, other, withPercentage(percentage),
abs(actual - other)));
}
@Test
void should_fail_if_actual_is_too_close_to_expected_value() {
AssertionInfo info = someInfo();
Throwable error = catchThrowable(() -> bytes.assertIsNotCloseToPercentage(someInfo(), ONE, TEN, withPercentage(ONE_HUNDRED)));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldNotBeEqualWithinPercentage(ONE, TEN, withinPercentage(100), (TEN - ONE)));
}
}
| Bytes_assertIsNotCloseToPercentage_Test |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedEmbeddedObjectWithASecondaryTableTest.java | {
"start": 1175,
"end": 1621
} | class ____ {
@Test
void testNestedEmbeddedAndSecondaryTables(ServiceRegistryScope registryScope) {
final MetadataSources metadataSources = new MetadataSources( registryScope.getRegistry() )
.addAnnotatedClasses( Book.class, Author.class, House.class );
metadataSources.buildMetadata();
}
@Entity(name = "book")
@Table(name = "TBOOK")
@SecondaryTable(name = "TSECONDARYTABLE")
public static | NestedEmbeddedObjectWithASecondaryTableTest |
java | google__guava | android/guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java | {
"start": 6151,
"end": 6568
} | class ____ {}
TesterRequirements requirements = buildTesterRequirements(Tester.class);
assertThat(requirements.getPresentFeatures()).isEmpty();
assertThat(requirements.getAbsentFeatures()).containsExactly(IMPLIES_IMPLIES_FOO, IMPLIES_BAR);
}
public void testBuildTesterRequirements_class_present_and_absent() throws Exception {
@Require(value = IMPLIES_FOO, absent = IMPLIES_IMPLIES_FOO)
| Tester |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/creators/NoParamsCreator5318Test.java | {
"start": 1499,
"end": 3433
} | class ____ {
protected Pojo5318Ignore() { }
@JsonIgnore
public Pojo5318Ignore(int productId, String name) {
throw new IllegalStateException("Should not be called");
}
}
private final ObjectMapper MAPPER = jsonMapperBuilder()
.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.build();
// For [databind#5318]: intended usage
@Test
void creatorDetectionWithNoParamsCtor() throws Exception {
Pojo5318Working pojo = MAPPER.readValue("{\"productId\":1,\"name\":\"foo\"}", Pojo5318Working.class);
assertEquals(1, pojo.productId);
assertEquals("foo", pojo.name);
}
// For [databind#5318]: avoid detection with explicit annotation on 0-params ctor
@Test
void noCreatorDetectionDueToCreatorAnnotation() throws Exception {
assertNotNull(MAPPER.readValue("{}", Pojo5318Annotated.class));
}
// For [databind#5318]: avoid detection with explicit ignoral of parameterized ctor
@Test
void noCreatorDetectionDueToIgnore() throws Exception {
assertNotNull(MAPPER.readValue("{}", Pojo5318Ignore.class));
}
// For [databind#5318]: avoid detection when configured to do so (not allow
// implicit with default ctor)
@Test
void noCreatorDetectionDueToFeatureDisabled() throws Exception {
final ObjectMapper mapper = jsonMapperBuilder()
.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.constructorDetector(ConstructorDetector.DEFAULT
.withAllowImplicitWithDefaultConstructor(false))
.build();
try {
mapper.readValue("{\"productId\": 1}", Pojo5318Working.class);
fail("Should not pass");
} catch (MismatchedInputException e) {
verifyException(e, "Unrecognized property \"productId\"");
}
}
}
| Pojo5318Ignore |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java | {
"start": 34868,
"end": 34990
} | class ____ {}
""")
.addSourceLines(
"threadsafety/Test.java",
"""
package threadsafety;
| Super |
java | apache__camel | test-infra/camel-test-infra-solr/src/main/java/org/apache/camel/test/infra/solr/services/SolrInfraService.java | {
"start": 938,
"end": 1161
} | interface ____ extends InfrastructureService {
int getPort();
String getSolrHost();
default String getHttpHostAddress() {
return String.format("%s:%d", getSolrHost(), getPort());
}
}
| SolrInfraService |
java | apache__thrift | lib/java/src/main/java/org/apache/thrift/TBaseHelper.java | {
"start": 1192,
"end": 4928
} | class ____ {
private TBaseHelper() {}
private static final Comparator comparator = new NestedStructureComparator();
public static int compareTo(Object o1, Object o2) {
if (o1 instanceof Comparable) {
return compareTo((Comparable) o1, (Comparable) o2);
} else if (o1 instanceof List) {
return compareTo((List) o1, (List) o2);
} else if (o1 instanceof Set) {
return compareTo((Set) o1, (Set) o2);
} else if (o1 instanceof Map) {
return compareTo((Map) o1, (Map) o2);
} else if (o1 instanceof byte[]) {
return compareTo((byte[]) o1, (byte[]) o2);
} else {
throw new IllegalArgumentException("Cannot compare objects of type " + o1.getClass());
}
}
public static int compareTo(boolean a, boolean b) {
return Boolean.compare(a, b);
}
public static int compareTo(byte a, byte b) {
return Byte.compare(a, b);
}
public static int compareTo(short a, short b) {
return Short.compare(a, b);
}
public static int compareTo(int a, int b) {
return Integer.compare(a, b);
}
public static int compareTo(long a, long b) {
return Long.compare(a, b);
}
public static int compareTo(double a, double b) {
return Double.compare(a, b);
}
public static int compareTo(String a, String b) {
return a.compareTo(b);
}
public static int compareTo(byte[] a, byte[] b) {
int compare = compareTo(a.length, b.length);
if (compare == 0) {
for (int i = 0; i < a.length; i++) {
compare = compareTo(a[i], b[i]);
if (compare != 0) {
break;
}
}
}
return compare;
}
public static int compareTo(Comparable a, Comparable b) {
return a.compareTo(b);
}
public static int compareTo(List a, List b) {
int compare = compareTo(a.size(), b.size());
if (compare == 0) {
for (int i = 0; i < a.size(); i++) {
compare = comparator.compare(a.get(i), b.get(i));
if (compare != 0) {
break;
}
}
}
return compare;
}
public static int compareTo(Set a, Set b) {
int compare = compareTo(a.size(), b.size());
if (compare == 0) {
ArrayList sortedA = new ArrayList(a);
ArrayList sortedB = new ArrayList(b);
Collections.sort(sortedA, comparator);
Collections.sort(sortedB, comparator);
Iterator iterA = sortedA.iterator();
Iterator iterB = sortedB.iterator();
// Compare each item.
while (iterA.hasNext() && iterB.hasNext()) {
compare = comparator.compare(iterA.next(), iterB.next());
if (compare != 0) {
break;
}
}
}
return compare;
}
public static int compareTo(Map a, Map b) {
int lastComparison = compareTo(a.size(), b.size());
if (lastComparison != 0) {
return lastComparison;
}
// Sort a and b so we can compare them.
SortedMap sortedA = new TreeMap(comparator);
sortedA.putAll(a);
Iterator<Map.Entry> iterA = sortedA.entrySet().iterator();
SortedMap sortedB = new TreeMap(comparator);
sortedB.putAll(b);
Iterator<Map.Entry> iterB = sortedB.entrySet().iterator();
// Compare each item.
while (iterA.hasNext() && iterB.hasNext()) {
Map.Entry entryA = iterA.next();
Map.Entry entryB = iterB.next();
lastComparison = comparator.compare(entryA.getKey(), entryB.getKey());
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = comparator.compare(entryA.getValue(), entryB.getValue());
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
/** Comparator to compare items inside a structure (e.g. a list, set, or map). */
private static | TBaseHelper |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestTokenClientRMService.java | {
"start": 2208,
"end": 12116
} | class ____ {
private final static String kerberosRule =
"RULE:[1:$1@$0](.*@EXAMPLE.COM)s/@.*//\nDEFAULT";
private static RMDelegationTokenSecretManager dtsm;
static {
KerberosName.setRules(kerberosRule);
}
private static final UserGroupInformation owner = UserGroupInformation
.createRemoteUser("owner", AuthMethod.KERBEROS);
private static final UserGroupInformation other = UserGroupInformation
.createRemoteUser("other", AuthMethod.KERBEROS);
private static final UserGroupInformation tester = UserGroupInformation
.createRemoteUser("tester", AuthMethod.KERBEROS);
private static final String testerPrincipal = "tester@EXAMPLE.COM";
private static final String ownerPrincipal = "owner@EXAMPLE.COM";
private static final String otherPrincipal = "other@EXAMPLE.COM";
private static final UserGroupInformation testerKerb = UserGroupInformation
.createRemoteUser(testerPrincipal, AuthMethod.KERBEROS);
private static final UserGroupInformation ownerKerb = UserGroupInformation
.createRemoteUser(ownerPrincipal, AuthMethod.KERBEROS);
private static final UserGroupInformation otherKerb = UserGroupInformation
.createRemoteUser(otherPrincipal, AuthMethod.KERBEROS);
@BeforeAll
public static void setupSecretManager() throws IOException {
ResourceManager rm = mock(ResourceManager.class);
RMContext rmContext = mock(RMContext.class);
when(rmContext.getStateStore()).thenReturn(new NullRMStateStore());
when(rm.getRMContext()).thenReturn(rmContext);
when(rmContext.getResourceManager()).thenReturn(rm);
dtsm =
new RMDelegationTokenSecretManager(60000, 60000, 60000, 60000,
rmContext);
dtsm.startThreads();
Configuration conf = new Configuration();
conf.set("hadoop.security.authentication", "kerberos");
conf.set("hadoop.security.auth_to_local", kerberosRule);
UserGroupInformation.setConfiguration(conf);
UserGroupInformation.getLoginUser()
.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
}
@AfterAll
public static void teardownSecretManager() {
if (dtsm != null) {
dtsm.stopThreads();
}
}
@Test
public void testTokenCancellationByOwner() throws Exception {
// two tests required - one with a kerberos name
// and with a short name
RMContext rmContext = mock(RMContext.class);
final ClientRMService rmService =
new ClientRMService(rmContext, null, null, null, null, dtsm);
testerKerb.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
checkTokenCancellation(rmService, testerKerb, other);
return null;
}
});
owner.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
checkTokenCancellation(owner, other);
return null;
}
});
}
@Test
public void testTokenRenewalWrongUser() throws Exception {
try {
owner.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
try {
checkTokenRenewal(owner, other);
return null;
} catch (YarnException ex) {
assertTrue(ex.getMessage().contains(
owner.getUserName() + " tries to renew a token"));
assertTrue(ex.getMessage().contains(
"with non-matching renewer " + other.getUserName()));
throw ex;
}
}
});
} catch (Exception e) {
return;
}
fail("renew should have failed");
}
@Test
public void testTokenRenewalByLoginUser() throws Exception {
UserGroupInformation.getLoginUser().doAs(
new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
checkTokenRenewal(owner, owner);
checkTokenRenewal(owner, other);
return null;
}
});
}
private void checkTokenRenewal(UserGroupInformation owner,
UserGroupInformation renewer) throws IOException, YarnException {
RMDelegationTokenIdentifier tokenIdentifier =
new RMDelegationTokenIdentifier(new Text(owner.getUserName()),
new Text(renewer.getUserName()), null);
Token<?> token =
new Token<RMDelegationTokenIdentifier>(tokenIdentifier, dtsm);
org.apache.hadoop.yarn.api.records.Token dToken =
BuilderUtils.newDelegationToken(token.getIdentifier(), token.getKind()
.toString(), token.getPassword(), token.getService().toString());
RenewDelegationTokenRequest request =
Records.newRecord(RenewDelegationTokenRequest.class);
request.setDelegationToken(dToken);
RMContext rmContext = mock(RMContext.class);
ClientRMService rmService =
new ClientRMService(rmContext, null, null, null, null, dtsm);
rmService.renewDelegationToken(request);
}
@Test
public void testTokenCancellationByRenewer() throws Exception {
// two tests required - one with a kerberos name
// and with a short name
RMContext rmContext = mock(RMContext.class);
final ClientRMService rmService =
new ClientRMService(rmContext, null, null, null, null, dtsm);
testerKerb.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
checkTokenCancellation(rmService, owner, testerKerb);
return null;
}
});
other.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
checkTokenCancellation(owner, other);
return null;
}
});
}
@Test
public void testTokenCancellationByWrongUser() {
// two sets to test -
// 1. try to cancel tokens of short and kerberos users as a kerberos UGI
// 2. try to cancel tokens of short and kerberos users as a simple auth UGI
RMContext rmContext = mock(RMContext.class);
final ClientRMService rmService =
new ClientRMService(rmContext, null, null, null, null, dtsm);
UserGroupInformation[] kerbTestOwners =
{ owner, other, tester, ownerKerb, otherKerb };
UserGroupInformation[] kerbTestRenewers =
{ owner, other, ownerKerb, otherKerb };
for (final UserGroupInformation tokOwner : kerbTestOwners) {
for (final UserGroupInformation tokRenewer : kerbTestRenewers) {
try {
testerKerb.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
try {
checkTokenCancellation(rmService, tokOwner, tokRenewer);
fail("We should not reach here; token owner = "
+ tokOwner.getUserName() + ", renewer = "
+ tokRenewer.getUserName());
return null;
} catch (YarnException e) {
assertTrue(e.getMessage().contains(
testerKerb.getUserName()
+ " is not authorized to cancel the token"));
return null;
}
}
});
} catch (Exception e) {
fail("Unexpected exception; " + e.getMessage());
}
}
}
UserGroupInformation[] simpleTestOwners =
{ owner, other, ownerKerb, otherKerb, testerKerb };
UserGroupInformation[] simpleTestRenewers =
{ owner, other, ownerKerb, otherKerb };
for (final UserGroupInformation tokOwner : simpleTestOwners) {
for (final UserGroupInformation tokRenewer : simpleTestRenewers) {
try {
tester.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
try {
checkTokenCancellation(tokOwner, tokRenewer);
fail("We should not reach here; token owner = "
+ tokOwner.getUserName() + ", renewer = "
+ tokRenewer.getUserName());
return null;
} catch (YarnException ex) {
assertTrue(ex.getMessage().contains(
tester.getUserName()
+ " is not authorized to cancel the token"));
return null;
}
}
});
} catch (Exception e) {
fail("Unexpected exception; " + e.getMessage());
}
}
}
}
private void checkTokenCancellation(UserGroupInformation owner,
UserGroupInformation renewer) throws IOException, YarnException {
RMContext rmContext = mock(RMContext.class);
final ClientRMService rmService =
new ClientRMService(rmContext, null, null, null, null, dtsm);
checkTokenCancellation(rmService, owner, renewer);
}
private void checkTokenCancellation(ClientRMService rmService,
UserGroupInformation owner, UserGroupInformation renewer)
throws IOException, YarnException {
RMDelegationTokenIdentifier tokenIdentifier =
new RMDelegationTokenIdentifier(new Text(owner.getUserName()),
new Text(renewer.getUserName()), null);
Token<?> token =
new Token<RMDelegationTokenIdentifier>(tokenIdentifier, dtsm);
org.apache.hadoop.yarn.api.records.Token dToken =
BuilderUtils.newDelegationToken(token.getIdentifier(), token.getKind()
.toString(), token.getPassword(), token.getService().toString());
CancelDelegationTokenRequest request =
Records.newRecord(CancelDelegationTokenRequest.class);
request.setDelegationToken(dToken);
rmService.cancelDelegationToken(request);
}
@Test
public void testTokenRenewalByOwner() throws Exception {
owner.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
checkTokenRenewal(owner, owner);
return null;
}
});
}
}
| TestTokenClientRMService |
java | apache__camel | components/camel-ai/camel-langchain4j-tokenizer/src/main/java/org/apache/camel/component/langchain4j/tokenizer/AbstractLangChain4JTokenizer.java | {
"start": 1235,
"end": 1270
} | class ____ LangChain4j
*/
abstract | for |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/commons/util/AnnotationUtilsTests.java | {
"start": 24523,
"end": 24654
} | interface ____ {
}
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@ | FastAndSmoky |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/spi/metrics/NetworkMetrics.java | {
"start": 700,
"end": 1805
} | interface ____<S> extends Metrics {
/**
* Called when bytes have been read
*
* @param socketMetric the socket metric, null for UDP
* @param remoteAddress the remote address which this socket received bytes from
* @param numberOfBytes the number of bytes read
*/
default void bytesRead(S socketMetric, SocketAddress remoteAddress, long numberOfBytes) {
}
/**
* Called when bytes have been written
*
* @param socketMetric the socket metric, null for UDP
* @param remoteAddress the remote address which bytes are being written to
* @param numberOfBytes the number of bytes written
*/
default void bytesWritten(S socketMetric, SocketAddress remoteAddress, long numberOfBytes) {
}
/**
* Called when exceptions occur for a specific connection.
*
* @param socketMetric the socket metric, null for UDP
* @param remoteAddress the remote address of the connection or null if it's datagram/udp
* @param t the exception that occurred
*/
default void exceptionOccurred(S socketMetric, SocketAddress remoteAddress, Throwable t) {
}
}
| NetworkMetrics |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/odps/OdpsFormatCommentTest14.java | {
"start": 121,
"end": 1054
} | class ____ extends TestCase {
public void test_column_comment() throws Exception {
String sql = "select * from ("
+ "select 1 from t1"
+ "\n --c_0"
+ "\n union all "
+ "\n --c_1"
+ "\nselect 2 from t2"
+ "\n --c_2"
+ "\n union all "
+ "\n --c_3"
+ "\nselect 3 from t3"
+ ") xx";
assertEquals("SELECT *"
+ "\nFROM ("
+ "\n\tSELECT 1"
+ "\n\tFROM t1 -- c_0"
+ "\n\tUNION ALL"
+ "\n\t-- c_1"
+ "\n\tSELECT 2"
+ "\n\tFROM t2 -- c_2"
+ "\n\tUNION ALL"
+ "\n\t-- c_3"
+ "\n\tSELECT 3"
+ "\n\tFROM t3"
+ "\n) xx", SQLUtils.formatOdps(sql));
}
}
| OdpsFormatCommentTest14 |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java | {
"start": 3535,
"end": 4125
} | class ____ {
*
* private final ReadWriteLockVisitor<PrintStream> lock;
* private final PrintStream ps;
*
* public SimpleLogger(OutputStream out) {
* ps = new PrintStream(out);
* lock = LockingVisitors.readWriteLockVisitor(ps);
* }
*
* public void log(String message) {
* lock.acceptWriteLocked(ps -> ps.println(message));
* }
*
* public void log(byte[] buffer) {
* lock.acceptWriteLocked(ps -> { ps.write(buffer); ps.println(); });
* }
* }
* }
* </pre>
*
* <p>
* Example 3: A thread safe logger | SimpleLogger2 |
java | apache__camel | components/camel-servicenow/camel-servicenow-component/src/main/java/org/apache/camel/component/servicenow/model/Reference.java | {
"start": 972,
"end": 1844
} | class ____ {
private final String link;
private final String value;
private final String displayValue;
@JsonCreator
public Reference(String value) {
this.link = null;
this.value = value;
this.displayValue = null;
}
@JsonCreator
public Reference(
@JsonProperty(value = "link", required = false) String link,
@JsonProperty(value = "value", required = true) String value,
@JsonProperty(value = "display_value", required = false) String displayValue) {
this.link = link;
this.value = value;
this.displayValue = displayValue;
}
public String getLink() {
return link;
}
public String getValue() {
return value;
}
public String getDisplayValue() {
return displayValue;
}
}
| Reference |
java | spring-projects__spring-boot | module/spring-boot-jdbc-test/src/test/java/org/springframework/boot/jdbc/test/autoconfigure/ExampleRepository.java | {
"start": 998,
"end": 1674
} | class ____ {
private static final ExampleEntityRowMapper ROW_MAPPER = new ExampleEntityRowMapper();
private final JdbcTemplate jdbcTemplate;
ExampleRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Transactional
void save(ExampleEntity entity) {
this.jdbcTemplate.update("insert into example (id, name) values (?, ?)", entity.getId(), entity.getName());
}
ExampleEntity findById(int id) {
return this.jdbcTemplate.queryForObject("select id, name from example where id =?", ROW_MAPPER, id);
}
Collection<ExampleEntity> findAll() {
return this.jdbcTemplate.query("select id, name from example", ROW_MAPPER);
}
}
| ExampleRepository |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/transaction/managed/ManagedTransactionWithConnectionTest.java | {
"start": 1207,
"end": 2592
} | class ____ extends ManagedTransactionBase {
@Mock
private Connection connection;
private Transaction transaction;
@BeforeEach
void setup() {
this.transaction = new ManagedTransaction(connection, true);
}
@Override
@Test
void shouldGetConnection() throws SQLException {
Connection result = transaction.getConnection();
assertEquals(connection, result);
}
@Test
@Override
void shouldNotCommitWhetherConnectionIsAutoCommit() throws SQLException {
transaction.commit();
verify(connection, never()).commit();
verify(connection, never()).getAutoCommit();
}
@Test
@Override
void shouldNotRollbackWhetherConnectionIsAutoCommit() throws SQLException {
transaction.commit();
verify(connection, never()).rollback();
verify(connection, never()).getAutoCommit();
}
@Test
@Override
void shouldCloseWhenSetCloseConnectionIsTrue() throws SQLException {
transaction.close();
verify(connection).close();
}
@Test
@Override
void shouldNotCloseWhenSetCloseConnectionIsFalse() throws SQLException {
this.transaction = new ManagedTransaction(connection, false);
transaction.close();
verify(connection, never()).close();
}
@Test
@Override
void shouldReturnNullWhenGetTimeout() throws SQLException {
assertNull(transaction.getTimeout());
}
}
| ManagedTransactionWithConnectionTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/LocalTimeOffset.java | {
"start": 16016,
"end": 18282
} | class ____ extends AbstractManyTransitionsLookup {
private final LocalTimeOffset[] offsets;
private final long[] transitionOutUtcMillis;
private TransitionArrayLookup(ZoneId zone, long minUtcMillis, long maxUtcMillis, List<ZoneOffsetTransition> transitions) {
super(zone, minUtcMillis, maxUtcMillis);
this.offsets = new LocalTimeOffset[transitions.size() + 1];
this.transitionOutUtcMillis = new long[transitions.size()];
this.offsets[0] = buildNoPrevious(transitions.get(0));
int i = 0;
for (ZoneOffsetTransition t : transitions) {
Transition transition = buildTransition(t, this.offsets[i]);
transitionOutUtcMillis[i] = transition.startUtcMillis();
i++;
this.offsets[i] = transition;
}
}
@Override
protected LocalTimeOffset innerLookup(long utcMillis) {
int index = Arrays.binarySearch(transitionOutUtcMillis, utcMillis);
if (index < 0) {
/*
* We're mostly not going to find the exact offset. Instead we'll
* end up at the "insertion point" for the utcMillis. We have no
* plans to insert utcMillis in the array, but the offset that
* contains utcMillis happens to be "insertion point" - 1.
*/
index = -index - 1;
} else {
index++;
}
assert index < offsets.length : "binarySearch did something weird";
return offsets[index];
}
@Override
int size() {
return offsets.length;
}
@Override
public boolean anyMoveBackToPreviousDay() {
return offsets[offsets.length - 1].anyMoveBackToPreviousDay();
}
@Override
public String toString() {
return String.format(
Locale.ROOT,
"TransitionArrayLookup[for %s between %s and %s]",
zone,
Instant.ofEpochMilli(minUtcMillis),
Instant.ofEpochMilli(maxUtcMillis)
);
}
}
private abstract static | TransitionArrayLookup |
java | redisson__redisson | redisson/src/main/java/org/redisson/client/protocol/decoder/AutoClaimMapReplayDecoder.java | {
"start": 952,
"end": 1762
} | class ____ implements MultiDecoder<Object> {
@Override
public Decoder<Object> getDecoder(Codec codec, int paramNum, State state, long size) {
if (state.getValue() != null) {
return new StreamIdDecoder();
}
return MultiDecoder.super.getDecoder(codec, paramNum, state, size);
}
@Override
public Object decode(List<Object> parts, State state) {
if (state.getValue() != null) {
return parts;
}
state.setValue(true);
List<List<Object>> list = (List<List<Object>>) (Object) parts;
return list.stream()
.filter(Objects::nonNull)
.collect(Collectors.toMap(e -> e.get(0), e -> e.get(1),
(a, b) -> a, LinkedHashMap::new));
}
}
| AutoClaimMapReplayDecoder |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/mapper/blockloader/docvalues/fn/MvMinIntsFromDocValuesBlockLoaderTests.java | {
"start": 1022,
"end": 3343
} | class ____ extends AbstractIntsFromDocValuesBlockLoaderTests {
public MvMinIntsFromDocValuesBlockLoaderTests(boolean blockAtATime, boolean multiValues, boolean missingValues) {
super(blockAtATime, multiValues, missingValues);
}
@Override
protected void innerTest(LeafReaderContext ctx, int mvCount) throws IOException {
var intsLoader = new IntsBlockLoader("field");
var mvMinIntsLoader = new MvMinIntsFromDocValuesBlockLoader("field");
var intsReader = intsLoader.reader(ctx);
var mvMinIntsReader = mvMinIntsLoader.reader(ctx);
assertThat(mvMinIntsReader, readerMatcher());
BlockLoader.Docs docs = TestBlock.docs(ctx);
try (
TestBlock ints = read(intsLoader, intsReader, ctx, docs);
TestBlock minInts = read(mvMinIntsLoader, mvMinIntsReader, ctx, docs);
) {
checkBlocks(ints, minInts);
}
intsReader = intsLoader.reader(ctx);
mvMinIntsReader = mvMinIntsLoader.reader(ctx);
for (int i = 0; i < ctx.reader().numDocs(); i += 10) {
int[] docsArray = new int[Math.min(10, ctx.reader().numDocs() - i)];
for (int d = 0; d < docsArray.length; d++) {
docsArray[d] = i + d;
}
docs = TestBlock.docs(docsArray);
try (
TestBlock ints = read(intsLoader, intsReader, ctx, docs);
TestBlock minInts = read(mvMinIntsLoader, mvMinIntsReader, ctx, docs);
) {
checkBlocks(ints, minInts);
}
}
}
private Matcher<Object> readerMatcher() {
if (multiValues) {
return hasToString("MvMinIntsFromDocValues.Sorted");
}
return hasToString("IntsFromDocValues.Singleton");
}
private void checkBlocks(TestBlock ints, TestBlock mvMin) {
for (int i = 0; i < ints.size(); i++) {
Object v = ints.get(i);
if (v == null) {
assertThat(mvMin.get(i), nullValue());
continue;
}
Integer min = (Integer) (v instanceof List<?> l ? l.stream().map(b -> (Integer) b).min(Comparator.naturalOrder()).get() : v);
assertThat(mvMin.get(i), equalTo(min));
}
}
}
| MvMinIntsFromDocValuesBlockLoaderTests |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java | {
"start": 10472,
"end": 10712
} | class ____ {
private String name;
public PropertyDependencyTestBean(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
@SuppressWarnings("unused")
private static | PropertyDependencyTestBean |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/vault/GcpVaultConfiguration.java | {
"start": 941,
"end": 3290
} | class ____ extends VaultConfiguration {
@Metadata(secret = true)
private String serviceAccountKey;
@Metadata
private String projectId;
@Metadata
private boolean useDefaultInstance;
@Metadata
private String subscriptionName;
@Metadata
private boolean refreshEnabled;
@Metadata(defaultValue = "30000")
private long refreshPeriod = 30000;
@Metadata
private String secrets;
public String getServiceAccountKey() {
return serviceAccountKey;
}
/**
* The Service Account Key location
*/
public void setServiceAccountKey(String serviceAccountKey) {
this.serviceAccountKey = serviceAccountKey;
}
public String getProjectId() {
return projectId;
}
/**
* The GCP Project ID
*/
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public boolean isUseDefaultInstance() {
return useDefaultInstance;
}
/**
* Define if we want to use the GCP Client Default Instance or not
*/
public void setUseDefaultInstance(boolean useDefaultInstance) {
this.useDefaultInstance = useDefaultInstance;
}
public String getSubscriptionName() {
return subscriptionName;
}
/**
* Define the Google Pubsub subscription Name to be used when checking for updates
*/
public void setSubscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
}
public boolean isRefreshEnabled() {
return refreshEnabled;
}
/**
* Whether to automatically reload Camel upon secrets being updated in AWS.
*/
public void setRefreshEnabled(boolean refreshEnabled) {
this.refreshEnabled = refreshEnabled;
}
public long getRefreshPeriod() {
return refreshPeriod;
}
/**
* The period (millis) between checking Google for updated secrets.
*/
public void setRefreshPeriod(long refreshPeriod) {
this.refreshPeriod = refreshPeriod;
}
public String getSecrets() {
return secrets;
}
/**
* Specify the secret names (or pattern) to check for updates. Multiple secrets can be separated by comma.
*/
public void setSecrets(String secrets) {
this.secrets = secrets;
}
}
| GcpVaultConfiguration |
java | apache__camel | components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/annotation/ReplaceBeanFromFieldWithMockTest.java | {
"start": 1665,
"end": 1815
} | class ____ that an existing bean can be replaced with a mock created by another extension.
*/
@ExtendWith(MockitoExtension.class)
@CamelMainTest
| ensuring |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4829ChecksumFailureWarningTest.java | {
"start": 1123,
"end": 2723
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify that artifacts with mismatching checksums cause a warning on the console.
*
* @throws Exception in case of failure
*/
@Test
public void testit() throws Exception {
File testDir = extractResources("/mng-4829");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.deleteArtifacts("org.apache.maven.its.mng4829");
verifier.addCliArgument("-s");
verifier.addCliArgument("settings.xml");
verifier.removeCIEnvironmentVariables();
verifier.filterFile("settings-template.xml", "settings.xml");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
List<String> lines = verifier.loadLogLines();
boolean foundWarningJar = false, foundWarningPom = false;
for (String line : lines) {
if (line.matches("(?i)\\[WARNING\\].*Checksum.*failed.*fa23720355eead3906fdf4ffd2a1a5f5.*")) {
foundWarningPom = true;
} else if (line.matches(
"(?i)\\[WARNING\\].*Checksum.*failed.*d912aa49cba88e7e9c578e042953f7ce307daac5.*")) {
foundWarningJar = true;
}
}
assertTrue(foundWarningPom, "Checksum warning for corrupt.pom has not been logged.");
assertTrue(foundWarningJar, "Checksum warning for corrupt.jar has not been logged.");
}
}
| MavenITmng4829ChecksumFailureWarningTest |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerLogString.java | {
"start": 1917,
"end": 2649
} | class ____ extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> LOG_STRING =
instanceMethod()
.onDescendantOf("com.google.common.flogger.LoggingApi")
.named("log")
.withParameters("java.lang.String");
private static final Matcher<ExpressionTree> COMPILE_TIME_CONSTANT =
CompileTimeConstantExpressionMatcher.instance();
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return LOG_STRING.matches(tree, state)
&& !COMPILE_TIME_CONSTANT.matches(tree.getArguments().getFirst(), state)
? describeMatch(tree)
: Description.NO_MATCH;
}
}
| FloggerLogString |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/server/observation/ServerRequestObservationConvention.java | {
"start": 988,
"end": 1241
} | interface ____ extends ObservationConvention<ServerRequestObservationContext> {
@Override
default boolean supportsContext(Observation.Context context) {
return context instanceof ServerRequestObservationContext;
}
}
| ServerRequestObservationConvention |
java | quarkusio__quarkus | extensions/reactive-routes/deployment/src/test/java/io/quarkus/vertx/web/params/RouteMethodParametersTest.java | {
"start": 7876,
"end": 8245
} | class ____ {
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
}
| Person |
java | apache__camel | core/camel-core-reifier/src/main/java/org/apache/camel/reifier/RemoveHeadersReifier.java | {
"start": 1152,
"end": 2368
} | class ____ extends ProcessorReifier<RemoveHeadersDefinition> {
public RemoveHeadersReifier(Route route, ProcessorDefinition<?> definition) {
super(route, (RemoveHeadersDefinition) definition);
}
@Override
public Processor createProcessor() throws Exception {
ObjectHelper.notNull(definition.getPattern(), "patterns", definition);
RemoveHeadersProcessor answer;
if (definition.getExcludePatterns() != null) {
answer = new RemoveHeadersProcessor(
parseString(definition.getPattern()), parseStrings(definition.getExcludePatterns()));
} else if (definition.getExcludePattern() != null) {
answer = new RemoveHeadersProcessor(
parseString(definition.getPattern()), parseStrings(new String[] { definition.getExcludePattern() }));
} else {
answer = new RemoveHeadersProcessor(parseString(definition.getPattern()), null);
}
answer.setDisabled(isDisabled(camelContext, definition));
return answer;
}
private String[] parseStrings(String[] array) {
return Stream.of(array).map(this::parseString).toArray(String[]::new);
}
}
| RemoveHeadersReifier |
java | elastic__elasticsearch | x-pack/plugin/profiling/src/main/java/org/elasticsearch/xpack/profiling/action/SubGroupCollector.java | {
"start": 731,
"end": 3843
} | class ____ {
/**
* Users may provide a custom field via the API that is used to sub-divide profiling events. This is useful in the context of TopN
* where we want to provide additional breakdown of where a certain function has been called (e.g. a certain service or transaction).
*/
static final String CUSTOM_EVENT_SUB_AGGREGATION_NAME = "custom_event_group_";
private static final Logger log = LogManager.getLogger(SubGroupCollector.class);
private final String[] aggregationFields;
public static SubGroupCollector attach(AbstractAggregationBuilder<?> parentAggregation, String[] aggregationFields) {
SubGroupCollector c = new SubGroupCollector(aggregationFields);
c.addAggregations(parentAggregation);
return c;
}
private SubGroupCollector(String[] aggregationFields) {
this.aggregationFields = aggregationFields;
}
private boolean hasAggregationFields() {
return aggregationFields != null && aggregationFields.length > 0;
}
private void addAggregations(AbstractAggregationBuilder<?> parentAggregation) {
if (hasAggregationFields()) {
// cast to Object to disambiguate this from a varargs call
log.trace("Grouping stacktrace events by {}.", (Object) aggregationFields);
AbstractAggregationBuilder<?> parentAgg = parentAggregation;
for (String aggregationField : aggregationFields) {
String aggName = CUSTOM_EVENT_SUB_AGGREGATION_NAME + aggregationField;
TermsAggregationBuilder agg = new TermsAggregationBuilder(aggName).field(aggregationField);
parentAgg.subAggregation(agg);
parentAgg = agg;
}
}
}
void collectResults(MultiBucketsAggregation.Bucket bucket, TraceEvent event) {
collectResults(new BucketAdapter(bucket), event);
}
void collectResults(Bucket bucket, TraceEvent event) {
if (hasAggregationFields()) {
if (event.subGroups == null) {
event.subGroups = SubGroup.root(aggregationFields[0]);
}
collectInternal(bucket.getAggregations(), event.subGroups, 0);
}
}
private void collectInternal(Agg parentAgg, SubGroup parentGroup, int aggField) {
if (aggField == aggregationFields.length) {
return;
}
String aggName = CUSTOM_EVENT_SUB_AGGREGATION_NAME + aggregationFields[aggField];
for (Bucket b : parentAgg.getBuckets(aggName)) {
String subGroupName = b.getKey();
parentGroup.addCount(subGroupName, b.getCount());
SubGroup currentGroup = parentGroup.getSubGroup(subGroupName);
int nextAggField = aggField + 1;
if (nextAggField < aggregationFields.length) {
collectInternal(b.getAggregations(), currentGroup.getOrAddChild(aggregationFields[nextAggField]), nextAggField);
}
}
}
// The sole purpose of the code below is to abstract our code from the aggs framework to make it unit-testable
| SubGroupCollector |
java | quarkusio__quarkus | extensions/hibernate-search-orm-elasticsearch/deployment/src/test/java/io/quarkus/hibernate/search/orm/elasticsearch/test/configuration/CustomMappingFileNotFoundTest.java | {
"start": 434,
"end": 1376
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class).addClass(IndexedEntity.class))
.withConfigurationResource("application.properties")
.overrideConfigKey("quarkus.hibernate-search-orm.elasticsearch.schema-management.mapping-file",
"does-not-exist.json")
.assertException(throwable -> assertThat(throwable)
.isInstanceOf(ConfigurationException.class)
.hasMessageContainingAll(
"Unable to find file referenced in 'quarkus.hibernate-search-orm.elasticsearch.schema-management.mapping-file=does-not-exist.json'",
"Remove property or add file to your path"));
@Test
public void test() {
// an exception should be thrown
}
}
| CustomMappingFileNotFoundTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.