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-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/tvf/asyncprocessing/state/WindowAsyncState.java | {
"start": 1041,
"end": 1145
} | interface ____ manipulate state with window namespace.
*
* <p>Different with {@link WindowState}, this | for |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/repositories/blobstore/ShardSnapshotTaskRunner.java | {
"start": 1580,
"end": 1967
} | class ____ {
private static final Logger logger = LogManager.getLogger(ShardSnapshotTaskRunner.class);
private final PrioritizedThrottledTaskRunner<SnapshotTask> taskRunner;
private final Consumer<SnapshotShardContext> shardSnapshotter;
private final CheckedBiConsumer<SnapshotShardContext, FileInfo, IOException> fileSnapshotter;
abstract static | ShardSnapshotTaskRunner |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryParenthesesTest.java | {
"start": 6566,
"end": 6804
} | class ____ {
int f(boolean b, Integer x) {
assert (b);
return (x);
}
}
""")
.addOutputLines(
"Test.java",
"""
| Test |
java | google__dagger | javatests/dagger/internal/codegen/MapRequestRepresentationWithGuavaTest.java | {
"start": 3001,
"end": 3666
} | interface ____ {",
" @Provides @IntoMap @LongKey(3) static long provideLong3() { return 3; }",
" @Provides @IntoMap @LongKey(4) static long provideLong4() { return 4; }",
" @Provides @IntoMap @LongKey(5) static long provideLong5() { return 5; }",
"}");
Source componentFile =
CompilerTests.javaSource(
"test.TestComponent",
"package test;",
"",
"import dagger.Component;",
"import java.util.Map;",
"import javax.inject.Provider;",
"",
"@Component(modules = MapModule.class)",
" | SubcomponentMapModule |
java | micronaut-projects__micronaut-core | core-reactive/src/main/java/io/micronaut/core/async/subscriber/LazySendingSubscriber.java | {
"start": 1159,
"end": 1395
} | class ____ for the first item of a publisher before completing an ExecutionFlow with a
* publisher containing the same items.
*
* @param <T> The publisher item type
* @since 4.8.0
* @author Jonas Konrad
*/
@Internal
public final | waits |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/JSONObjectTest.java | {
"start": 880,
"end": 7594
} | class ____ extends TestCase {
public void test_toJSONObject() throws Exception {
{
Assert.assertNull(JSONObject.parse(null));
}
}
public void test_writeJSONString() throws Exception {
{
StringWriter out = new StringWriter();
new JSONObject().writeJSONString(out);
Assert.assertEquals("{}", out.toString());
}
}
public void test_getLong() throws Exception {
JSONObject json = new JSONObject(true);
json.put("A", 55L);
json.put("B", 55);
json.put("K", true);
Assert.assertEquals(json.getLong("A").longValue(), 55L);
Assert.assertEquals(json.getLong("B").longValue(), 55L);
Assert.assertEquals(json.getLong("C"), null);
Assert.assertEquals(json.getBooleanValue("K"), true);
Assert.assertEquals(json.getBoolean("K"), Boolean.TRUE);
}
public void test_getLong_1() throws Exception {
JSONObject json = new JSONObject(false);
json.put("A", 55L);
json.put("B", 55);
Assert.assertEquals(json.getLong("A").longValue(), 55L);
Assert.assertEquals(json.getLong("B").longValue(), 55L);
Assert.assertEquals(json.getLong("C"), null);
}
public void test_getDate() throws Exception {
long currentTimeMillis = System.currentTimeMillis();
JSONObject json = new JSONObject();
json.put("A", new Date(currentTimeMillis));
json.put("B", currentTimeMillis);
Assert.assertEquals(json.getDate("A").getTime(), currentTimeMillis);
Assert.assertEquals(json.getDate("B").getTime(), currentTimeMillis);
Assert.assertEquals(json.getLong("C"), null);
}
public void test_getBoolean() throws Exception {
JSONObject json = new JSONObject();
json.put("A", true);
Assert.assertEquals(json.getBoolean("A").booleanValue(), true);
Assert.assertEquals(json.getLong("C"), null);
}
public void test_getInt() throws Exception {
JSONObject json = new JSONObject();
json.put("A", 55L);
json.put("B", 55);
Assert.assertEquals(json.getInteger("A").intValue(), 55);
Assert.assertEquals(json.getInteger("B").intValue(), 55);
Assert.assertEquals(json.getInteger("C"), null);
}
public void test_order() throws Exception {
JSONObject json = new JSONObject(true);
json.put("C", 55L);
json.put("B", 55);
json.put("A", 55);
Assert.assertEquals("C", json.keySet().toArray()[0]);
Assert.assertEquals("B", json.keySet().toArray()[1]);
Assert.assertEquals("A", json.keySet().toArray()[2]);
Assert.assertEquals(0, json.getIntValue("D"));
Assert.assertEquals(0L, json.getLongValue("D"));
Assert.assertEquals(false, json.getBooleanValue("D"));
}
public void test_all() throws Exception {
JSONObject json = new JSONObject();
Assert.assertEquals(true, json.isEmpty());
json.put("C", 51L);
json.put("B", 52);
json.put("A", 53);
Assert.assertEquals(false, json.isEmpty());
Assert.assertEquals(true, json.containsKey("C"));
Assert.assertEquals(false, json.containsKey("D"));
Assert.assertEquals(true, json.containsValue(52));
Assert.assertEquals(false, json.containsValue(33));
Assert.assertEquals(null, json.remove("D"));
Assert.assertEquals(51L, json.remove("C"));
Assert.assertEquals(2, json.keySet().size());
Assert.assertEquals(2, json.values().size());
Assert.assertEquals(new BigDecimal("53"), json.getBigDecimal("A"));
json.putAll(Collections.singletonMap("E", 99));
Assert.assertEquals(3, json.values().size());
json.clear();
Assert.assertEquals(0, json.values().size());
json.putAll(Collections.singletonMap("E", 99));
Assert.assertEquals(99L, json.getLongValue("E"));
Assert.assertEquals(99, json.getIntValue("E"));
Assert.assertEquals("99", json.getString("E"));
Assert.assertEquals(null, json.getString("F"));
Assert.assertEquals(null, json.getDate("F"));
Assert.assertEquals(null, json.getBoolean("F"));
}
public void test_all_2() throws Exception {
JSONObject array = new JSONObject();
array.put("0", 123);
array.put("1", "222");
array.put("2", 3);
array.put("3", true);
array.put("4", "true");
array.put("5", "2.0");
Assert.assertEquals(123, array.getIntValue("0"));
Assert.assertEquals(123, array.getLongValue("0"));
Assert.assertEquals(new BigDecimal("123"), array.getBigDecimal("0"));
Assert.assertEquals(222, array.getIntValue("1"));
Assert.assertEquals(3, array.getByte("2").byteValue());
Assert.assertEquals(3, array.getByteValue("2"));
Assert.assertEquals(3, array.getShort("2").shortValue());
Assert.assertEquals(3, array.getShortValue("2"));
Assert.assertEquals(new Integer(222), array.getInteger("1"));
Assert.assertEquals(new Long(222), array.getLong("1"));
Assert.assertEquals(new BigDecimal("222"), array.getBigDecimal("1"));
Assert.assertEquals(true, array.getBooleanValue("4"));
Assert.assertTrue(2.0F == array.getFloat("5").floatValue());
Assert.assertTrue(2.0F == array.getFloatValue("5"));
Assert.assertTrue(2.0D == array.getDouble("5").doubleValue());
Assert.assertTrue(2.0D == array.getDoubleValue("5"));
}
public void test_getObject_null() throws Exception {
JSONObject json = new JSONObject();
json.put("obj", null);
Assert.assertTrue(json.getJSONObject("obj") == null);
}
public void test_bytes () throws Exception {
JSONObject object = new JSONObject();
Assert.assertNull(object.getBytes("bytes"));
}
public void test_getObject() throws Exception {
JSONObject json = new JSONObject();
json.put("obj", new JSONObject());
Assert.assertEquals(0, json.getJSONObject("obj").size());
}
public void test_getObject_map() throws Exception {
JSONObject json = new JSONObject();
json.put("obj", new HashMap());
Assert.assertEquals(0, json.getJSONObject("obj").size());
}
public void test_getObjectOrDefault() {
JSONObject json = new JSONObject();
json.put("testKey", "testVal");
json.put("testKey2", null);
Assert.assertEquals("default", json.getOrDefault("testNonKet", "default"));
Assert.assertEquals("default", json.getOrDefault("testKey2", "default"));
}
}
| JSONObjectTest |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/resultmatches/XpathAssertionTests.java | {
"start": 8178,
"end": 8567
} | class ____ {
@RequestMapping(value = "/blog.atom", method = {GET, HEAD})
@ResponseBody
public String listPublishedPosts() {
return """
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Test Feed</title>
<icon>https://www.example.com/favicon.ico</icon>
</feed>""".replaceAll("\n", "\r\n");
}
}
}
| BlogFeedController |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/exchanges/Include.java | {
"start": 916,
"end": 2011
} | enum ____ {
/**
* Include request headers.
*/
REQUEST_HEADERS,
/**
* Include the remote address from the request.
*/
REMOTE_ADDRESS,
/**
* Include "Cookie" header (if any) in request headers and "Set-Cookie" (if any) in
* response headers.
*/
COOKIE_HEADERS,
/**
* Include authorization header (if any).
*/
AUTHORIZATION_HEADER,
/**
* Include response headers.
*/
RESPONSE_HEADERS,
/**
* Include the principal.
*/
PRINCIPAL,
/**
* Include the session ID.
*/
SESSION_ID,
/**
* Include the time taken to service the request.
*/
TIME_TAKEN;
private static final Set<Include> DEFAULT_INCLUDES;
static {
Set<Include> defaultIncludes = new LinkedHashSet<>();
defaultIncludes.add(Include.TIME_TAKEN);
defaultIncludes.add(Include.REQUEST_HEADERS);
defaultIncludes.add(Include.RESPONSE_HEADERS);
DEFAULT_INCLUDES = Collections.unmodifiableSet(defaultIncludes);
}
/**
* Return the default {@link Include}.
* @return the default include.
*/
public static Set<Include> defaultIncludes() {
return DEFAULT_INCLUDES;
}
}
| Include |
java | google__guice | core/src/com/google/inject/internal/aop/FastClass.java | {
"start": 3009,
"end": 3799
} | class ____ represents a bound invoker
* {
* private final int index; // the bound trampoline index
*
* public HostClass$$FastClassByGuice(int index) {
* this.index = index;
* }
*
* public Object apply(Object context, Object args) {
* return GUICE$TRAMPOLINE(index, context, (Object[]) args);
* }
*
* public static Object GUICE$TRAMPOLINE(int index, Object context, Object[] args) {
* switch (index) {
* case 0: {
* return new HostClass(...);
* }
* case 1: {
* return ((HostClass) context).instanceMethod(...);
* }
* case 2: {
* return HostClass.staticMethod(...);
* }
* }
* return null;
* }
* }
* </pre>
*
* @author mcculls@gmail.com (Stuart McCulloch)
*/
final | instance |
java | google__guice | core/test/com/google/inject/KeyTest.java | {
"start": 3935,
"end": 9564
} | class ____ uses raw type
public void testPrimitivesAndWrappersAreEqual() {
Class[] primitives =
new Class[] {
boolean.class,
byte.class,
short.class,
int.class,
long.class,
float.class,
double.class,
char.class,
void.class
};
Class[] wrappers =
new Class[] {
Boolean.class,
Byte.class,
Short.class,
Integer.class,
Long.class,
Float.class,
Double.class,
Character.class,
Void.class
};
for (int t = 0; t < primitives.length; t++) {
@SuppressWarnings("unchecked")
Key primitiveKey = Key.get(primitives[t]);
@SuppressWarnings("unchecked")
Key wrapperKey = Key.get(wrappers[t]);
assertEquals(primitiveKey, wrapperKey);
assertEquals(wrappers[t], primitiveKey.getRawType());
assertEquals(wrappers[t], wrapperKey.getRawType());
assertEquals(wrappers[t], primitiveKey.getTypeLiteral().getType());
assertEquals(wrappers[t], wrapperKey.getTypeLiteral().getType());
}
Key<Integer> integerKey = Key.get(Integer.class);
Key<Integer> integerKey2 = Key.get(Integer.class, Named.class);
Key<Integer> integerKey3 = Key.get(Integer.class, Names.named("int"));
Class<Integer> intClassLiteral = int.class;
assertEquals(integerKey, Key.get(intClassLiteral));
assertEquals(integerKey2, Key.get(intClassLiteral, Named.class));
assertEquals(integerKey3, Key.get(intClassLiteral, Names.named("int")));
Type intType = int.class;
assertEquals(integerKey, Key.get(intType));
assertEquals(integerKey2, Key.get(intType, Named.class));
assertEquals(integerKey3, Key.get(intType, Names.named("int")));
TypeLiteral<Integer> intTypeLiteral = TypeLiteral.get(int.class);
assertEquals(integerKey, Key.get(intTypeLiteral));
assertEquals(integerKey2, Key.get(intTypeLiteral, Named.class));
assertEquals(integerKey3, Key.get(intTypeLiteral, Names.named("int")));
}
public void testSerialization() throws IOException, NoSuchFieldException {
assertNotSerializable(Key.get(B.class));
assertNotSerializable(Key.get(B.class, Names.named("bee")));
assertNotSerializable(Key.get(B.class, Named.class));
assertNotSerializable(Key.get(B[].class));
assertNotSerializable(Key.get(new TypeLiteral<Map<List<B>, B>>() {}));
assertNotSerializable(Key.get(new TypeLiteral<List<B[]>>() {}));
assertNotSerializable(Key.get(Types.listOf(Types.subtypeOf(CharSequence.class))));
}
public void testEqualityOfAnnotationTypesAndInstances() throws NoSuchFieldException {
Foo instance = getClass().getDeclaredField("baz").getAnnotation(Foo.class);
Key<String> keyWithInstance = Key.get(String.class, instance);
Key<String> keyWithLiteral = Key.get(String.class, Foo.class);
assertEqualsBothWays(keyWithInstance, keyWithLiteral);
}
public void testNonBindingAnnotationOnKey() {
try {
Key.get(String.class, Deprecated.class);
fail();
} catch (IllegalArgumentException expected) {
assertContains(
expected.getMessage(),
"java.lang.Deprecated is not a binding annotation. ",
"Please annotate it with @Qualifier.");
}
}
public void testBindingAnnotationWithoutRuntimeRetention() {
try {
Key.get(String.class, Bar.class);
fail();
} catch (IllegalArgumentException expected) {
assertContains(
expected.getMessage(),
Bar.class.getName() + " is not retained at runtime.",
"Please annotate it with @Retention(RUNTIME).");
}
}
<T> void parameterizedWithVariable(List<T> typeWithVariables) {}
/** Test for issue 186 */
public void testCannotCreateKeysWithTypeVariables() throws NoSuchMethodException {
ParameterizedType listOfTType =
(ParameterizedType)
getClass()
.getDeclaredMethod("parameterizedWithVariable", List.class)
.getGenericParameterTypes()[
0];
TypeLiteral<?> listOfT = TypeLiteral.get(listOfTType);
try {
Key.get(listOfT);
fail("Guice should not allow keys for java.util.List<T>");
} catch (ConfigurationException e) {
assertContains(e.getMessage(), "List<T> cannot be used as a key; It is not fully specified.");
}
TypeVariable<?> tType = (TypeVariable) listOfTType.getActualTypeArguments()[0];
TypeLiteral<?> t = TypeLiteral.get(tType);
try {
Key.get(t);
fail("Guice should not allow keys for T");
} catch (ConfigurationException e) {
assertContains(e.getMessage(), "T cannot be used as a key; It is not fully specified.");
}
}
public void testCannotGetKeyWithUnspecifiedTypeVariables() {
TypeLiteral<Integer> typeLiteral = KeyTest.createTypeLiteral();
try {
Key.get(typeLiteral);
fail("Guice should not allow keys for T");
} catch (ConfigurationException e) {
assertContains(e.getMessage(), "T cannot be used as a key; It is not fully specified.");
}
}
private static <T> TypeLiteral<T> createTypeLiteral() {
return new TypeLiteral<T>() {};
}
public void testCannotCreateKeySubclassesWithUnspecifiedTypeVariables() {
try {
KeyTest.<Integer>createKey();
fail("Guice should not allow keys for T");
} catch (ConfigurationException e) {
assertContains(e.getMessage(), "T cannot be used as a key; It is not fully specified.");
}
}
private static <T> Key<T> createKey() {
return new Key<T>() {};
}
| literal |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/ParameterizedCtxConfigTestClassScopedExtensionContextNestedTests.java | {
"start": 5751,
"end": 6454
} | class ____ implements TestInterface {
@Autowired
ApplicationContext localContext;
@Autowired(required = false)
@Qualifier("foo")
String localFoo;
@Autowired
String bar;
@Autowired
String baz;
@Test
void test() {
assertThat(foo).isEqualTo(FOO);
assertThat(this.localFoo).as("foo bean should not be present").isNull();
assertThat(this.bar).isEqualTo(BAR);
assertThat(this.baz).isEqualTo(BAZ);
if (beanName.equals(BAR)) {
assertThat(localContext.getBean(beanName, String.class)).isEqualTo(beanName);
}
}
}
}
}
@Configuration(proxyBeanMethods = false)
static | TripleNestedWithInheritedConfigAndTestInterfaceTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/lockhint/AbstractLockHintTest.java | {
"start": 1312,
"end": 2120
} | class ____ {
private final String aliasToLock;
private final String rawSql;
private final String expectedProcessedSql;
public SyntaxChecker(String template) {
this( template, "" );
}
public SyntaxChecker(String template, String aliasToLock) {
this.aliasToLock = aliasToLock;
rawSql = StringHelper.replace( template, "$HOLDER$", aliasToLock );
expectedProcessedSql = StringHelper.replace( template, "$HOLDER$", aliasToLock + " " + getLockHintUsed() );
}
public void verify() {
final HashMap<String, String[]> aliasMap = new HashMap<>();
aliasMap.put( aliasToLock, new String[] { "id" } );
String actualProcessedSql = dialect.applyLocksToSql( rawSql, lockOptions( aliasToLock ), aliasMap );
assertEquals( expectedProcessedSql, actualProcessedSql );
}
}
}
| SyntaxChecker |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingReferenceDifferentSubclassTest.java | {
"start": 1564,
"end": 1676
} | class ____ {
@Id
@GeneratedValue
Long id;
String name;
}
@Entity(name = "SubclassA")
static | BaseClass |
java | micronaut-projects__micronaut-core | core/src/main/java/io/micronaut/core/type/Argument.java | {
"start": 1394,
"end": 7752
} | interface ____<T> extends TypeInformation<T>, AnnotatedElement, Type {
/**
* Constant for string argument.
*/
Argument<String> STRING = Argument.of(String.class);
/**
* Constant for int argument. Used by generated code, do not remove.
*/
@SuppressWarnings("unused")
Argument<Integer> INT = Argument.of(int.class);
/**
* Constant for long argument. Used by generated code, do not remove.
*/
@SuppressWarnings("unused")
Argument<Long> LONG = Argument.of(long.class);
/**
* Constant for float argument. Used by generated code, do not remove.
*/
@SuppressWarnings("unused")
Argument<Float> FLOAT = Argument.of(float.class);
/**
* Constant for double argument. Used by generated code, do not remove.
*/
@SuppressWarnings("unused")
Argument<Double> DOUBLE = Argument.of(double.class);
/**
* Constant for void argument. Used by generated code, do not remove.
*/
@SuppressWarnings("unused")
Argument<Void> VOID = Argument.of(void.class);
/**
* Constant for byte argument. Used by generated code, do not remove.
*/
@SuppressWarnings("unused")
Argument<Byte> BYTE = Argument.of(byte.class);
/**
* Constant for boolean argument. Used by generated code, do not remove.
*/
@SuppressWarnings("unused")
Argument<Boolean> BOOLEAN = Argument.of(boolean.class);
/**
* Constant char argument. Used by generated code, do not remove.
*/
@SuppressWarnings("unused")
Argument<Character> CHAR = Argument.of(char.class);
/**
* Constant short argument. Used by generated code, do not remove.
*/
@SuppressWarnings("unused")
Argument<Short> SHORT = Argument.of(short.class);
/**
* Constant representing zero arguments. Used by generated code, do not remove.
*/
@SuppressWarnings("unused")
@UsedByGeneratedCode
Argument[] ZERO_ARGUMENTS = new Argument[0];
/**
* Default Object argument. Used by generated code, do not remove.
*/
@SuppressWarnings("unused")
Argument<Object> OBJECT_ARGUMENT = of(Object.class);
/**
* Constant for {@code List<String>} argument.
*/
Argument<List<String>> LIST_OF_STRING = Argument.listOf(String.class);
/**
* Constant for Void object argument.
*/
Argument<Void> VOID_OBJECT = Argument.of(Void.class);
/**
* @return The name of the argument
*/
@Override
@NonNull
String getName();
/**
* Whether the types are equivalent. The regular {@link Object#equals(Object)} implementation includes the argument
* name within the comparison so this method offers a variation that just compares types.
*
* @param other The type
* @return True if they are equal
*/
boolean equalsType(@Nullable Argument<?> other);
/**
* The hash code including only the types. The regular {@link Object#hashCode()} implementation includes the
* argument name within the comparison so this method offers a variation that just compares types.
*
* @return The type hash code
*/
int typeHashCode();
/**
* Whether this argument is a type variable used in generics.
*
* @return True if it is a variable
* @since 3.0.0
*/
default boolean isTypeVariable() {
return false;
}
/**
* Whether the given argument is an instance.
*
* @param o The object
* @return True if it is an instance of this type
*/
default boolean isInstance(@Nullable Object o) {
if (o == null) {
return false;
}
return getType().isInstance(o);
}
/**
* Delegates to {@link Class#isAssignableFrom(Class)} for this argument.
*
* @param candidateType The candidate type
* @return True if it is assignable from.
* @since 3.0.0
*/
default boolean isAssignableFrom(@NonNull Class<?> candidateType) {
return getType().isAssignableFrom(Objects.requireNonNull(candidateType, "Candidate type cannot be null"));
}
/**
* Checks if the argument can be assigned to this argument.
*
* @param candidateArgument The candidate argument
* @return True if it is assignable from.
* @since 3.0.0
*/
default boolean isAssignableFrom(@NonNull Argument<?> candidateArgument) {
Objects.requireNonNull(candidateArgument, "Candidate type cannot be null");
if (!isAssignableFrom(candidateArgument.getType())) {
return false;
}
Argument[] typeParameters = getTypeParameters();
Argument[] candidateArgumentTypeParameters = candidateArgument.getTypeParameters();
if (typeParameters.length == 0) {
// Wildcard or no type parameters
return candidateArgumentTypeParameters.length >= 0;
}
if (candidateArgumentTypeParameters.length == 0) {
for (Argument typeParameter : typeParameters) {
if (typeParameter.getType() != Object.class) {
return false;
}
}
// Wildcard
return true;
}
for (int i = 0; i < typeParameters.length; i++) {
Argument typeParameter = typeParameters[i];
Argument candidateArgumentTypeParameter = candidateArgumentTypeParameters[i];
if (!typeParameter.isAssignableFrom(candidateArgumentTypeParameter)) {
return false;
}
}
return true;
}
/**
* Creates a copy of this argument with a different name.
* @param name The new name
* @return A new argument
* @since 4.6
*/
@NonNull
default Argument<T> withName(@Nullable String name) {
return Argument.of(getType(), name, getAnnotationMetadata(), getTypeParameters());
}
/**
* Creates a copy of this argument with a different annotation metadata.
* @param annotationMetadata The annotation metadata
* @return A new argument
* @since 4.6
*/
@NonNull
default Argument<T> withAnnotationMetadata(@NonNull AnnotationMetadata annotationMetadata) {
return Argument.of(getType(), getName(), annotationMetadata, getTypeParameters());
}
/**
* Convert an argument array to a | Argument |
java | processing__processing4 | app/src/processing/app/syntax/KeywordMap.java | {
"start": 783,
"end": 4547
} | class ____ {
// private Keyword[] map;
// protected int mapLength;
private boolean ignoreCase;
private Keyword[] literalMap;
private Keyword[] parenMap;
// A value of 52 will give good performance for most maps.
static private int MAP_LENGTH = 52;
/**
* Creates a new <code>KeywordMap</code>.
* @param ignoreCase True if keys are case insensitive
*/
public KeywordMap(boolean ignoreCase) {
// this(ignoreCase, 52);
this.ignoreCase = ignoreCase;
literalMap = new Keyword[MAP_LENGTH];
parenMap = new Keyword[MAP_LENGTH];
}
// /**
// * Creates a new <code>KeywordMap</code>.
// * @param ignoreCase True if the keys are case insensitive
// * @param mapLength The number of `buckets' to create.
// * A value of 52 will give good performance for most maps.
// */
// public KeywordMap(boolean ignoreCase, int mapLength) {
// this.mapLength = mapLength;
// this.ignoreCase = ignoreCase;
// map = new Keyword[mapLength];
// }
/**
* Looks up a key.
* @param text The text segment
* @param offset The offset of the substring within the text segment
* @param length The length of the substring
*/
public byte lookup(Segment text, int offset, int length, boolean paren) {
if (length == 0) {
return Token.NULL;
}
int key = getSegmentMapKey(text, offset, length);
Keyword k = paren ? parenMap[key] : literalMap[key];
while (k != null) {
// if (length != k.keyword.length) {
// k = k.next;
// continue;
// }
if (length == k.keyword.length) {
if (regionMatches(ignoreCase, text, offset, k.keyword)) {
return k.id;
}
}
k = k.next;
}
return Token.NULL;
}
/**
* Checks if a subregion of a <code>Segment</code> is equal to a
* character array.
* @param ignoreCase True if case should be ignored, false otherwise
* @param text The segment
* @param offset The offset into the segment
* @param match The character array to match
*/
static public boolean regionMatches(boolean ignoreCase, Segment text,
int offset, char[] match) {
int length = offset + match.length;
char[] textArray = text.array;
if (length > text.offset + text.count) {
return false;
}
for (int i = offset, j = 0; i < length; i++, j++) {
char c1 = textArray[i];
char c2 = match[j];
if (ignoreCase) {
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
}
if (c1 != c2) {
return false;
}
}
return true;
}
/**
* Adds a key-value mapping.
* @param keyword The key
* @param id The value
*/
public void add(String keyword, byte id, boolean paren) {
int key = getStringMapKey(keyword);
Keyword[] map = paren ? parenMap : literalMap;
map[key] = new Keyword(keyword.toCharArray(), id, map[key]);
}
/**
* Returns true if the keyword map is set to be case insensitive,
* false otherwise.
*/
public boolean getIgnoreCase() {
return ignoreCase;
}
/**
* Sets if the keyword map should be case insensitive.
* @param ignoreCase True if the keyword map should be case
* insensitive, false otherwise
*/
public void setIgnoreCase(boolean ignoreCase) {
this.ignoreCase = ignoreCase;
}
protected int getStringMapKey(String s) {
return (Character.toUpperCase(s.charAt(0)) +
Character.toUpperCase(s.charAt(s.length()-1)))
% MAP_LENGTH;
}
protected int getSegmentMapKey(Segment s, int off, int len) {
return (Character.toUpperCase(s.array[off]) +
Character.toUpperCase(s.array[off + len - 1]))
% MAP_LENGTH;
}
// private members
private static | KeywordMap |
java | micronaut-projects__micronaut-core | http-client-tck/src/main/java/io/micronaut/http/client/tck/tests/RedirectTest.java | {
"start": 10209,
"end": 10566
} | class ____ {
@Get("/host-header")
@Produces("text/plain")
HttpResponse<?> hostHeader(@Header String host) {
return HttpResponse.ok(host);
}
}
@SuppressWarnings("checkstyle:MissingJavadocType")
@Requires(property = "spec.name", value = SPEC_NAME)
@Client("/redirect")
| RedirectHostHeaderController |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/completable/CompletableConcatIterable.java | {
"start": 976,
"end": 1763
} | class ____ extends Completable {
final Iterable<? extends CompletableSource> sources;
public CompletableConcatIterable(Iterable<? extends CompletableSource> sources) {
this.sources = sources;
}
@Override
public void subscribeActual(CompletableObserver observer) {
Iterator<? extends CompletableSource> it;
try {
it = Objects.requireNonNull(sources.iterator(), "The iterator returned is null");
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
EmptyDisposable.error(e, observer);
return;
}
ConcatInnerObserver inner = new ConcatInnerObserver(observer, it);
observer.onSubscribe(inner.sd);
inner.next();
}
static final | CompletableConcatIterable |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/RGeoReactive.java | {
"start": 888,
"end": 14953
} | interface ____<V> extends RScoredSortedSetReactive<V> {
/**
* Adds geospatial member.
*
* @param longitude - longitude of object
* @param latitude - latitude of object
* @param member - object itself
* @return number of elements added to the sorted set,
* not including elements already existing for which
* the score was updated
*/
Mono<Long> add(double longitude, double latitude, V member);
/**
* Adds geospatial members.
*
* @param entries - objects
* @return number of elements added to the sorted set,
* not including elements already existing for which
* the score was updated
*/
Mono<Long> add(GeoEntry... entries);
/**
* Adds geospatial member only if it's already exists.
* <p>
* Requires <b>Redis 6.2.0 and higher.</b>
*
* @param longitude - longitude of object
* @param latitude - latitude of object
* @param member - object itself
* @return number of elements added to the sorted set
*/
Mono<Long> addIfExists(double longitude, double latitude, V member);
/**
* Adds geospatial members only if it's already exists.
* <p>
* Requires <b>Redis 6.2.0 and higher.</b>
*
* @param entries - objects
* @return number of elements added to the sorted set
*/
Mono<Long> addIfExists(GeoEntry... entries);
/**
* Adds geospatial member only if has not been added before.
* <p>
* Requires <b>Redis 6.2.0 and higher.</b>
*
* @param longitude - longitude of object
* @param latitude - latitude of object
* @param member - object itself
* @return number of elements added to the sorted set
*/
Mono<Boolean> tryAdd(double longitude, double latitude, V member);
/**
* Adds geospatial members only if has not been added before.
* <p>
* Requires <b>Redis 6.2.0 and higher.</b>
*
* @param entries - objects
* @return number of elements added to the sorted set
*/
Mono<Long> tryAdd(GeoEntry... entries);
/**
* Returns distance between members in <code>GeoUnit</code> units.
*
* @param firstMember - first object
* @param secondMember - second object
* @param geoUnit - geo unit
* @return distance
*/
Mono<Double> dist(V firstMember, V secondMember, GeoUnit geoUnit);
/**
* Returns 11 characters long Geohash string mapped by defined member.
*
* @param members - objects
* @return hash mapped by object
*/
Mono<Map<V, String>> hash(V... members);
/**
* Returns geo-position mapped by defined member.
*
* @param members - objects
* @return geo position mapped by object
*/
Mono<Map<V, GeoPosition>> pos(V... members);
/**
* Returns the members of a sorted set, which are within the
* borders of specified search conditions.
* <p>
* Usage examples:
* <pre>
* List objects = geo.search(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)
* .order(GeoOrder.ASC)
* .count(1)));
* </pre>
* <pre>
* List objects = geo.search(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)));
* </pre>
* <p>
* Requires <b>Redis 3.2.10 and higher.</b>
*
* @param args - search conditions object
* @return list of memebers
*/
Mono<List<V>> search(GeoSearchArgs args);
/*
* Use search() method instead
*
*/
@Deprecated
Mono<List<V>> radius(double longitude, double latitude, double radius, GeoUnit geoUnit);
/*
* Use search() method instead
*
*/
@Deprecated
Mono<List<V>> radius(double longitude, double latitude, double radius, GeoUnit geoUnit, int count);
/*
* Use search() method instead
*
*/
@Deprecated
Mono<List<V>> radius(double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder);
/*
* Use search() method instead
*
*/
@Deprecated
Mono<List<V>> radius(double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/**
* Returns the distance mapped by member of a sorted set,
* which are within the borders of specified search conditions.
* <p>
* Usage examples:
* <pre>
* Map objects = geo.searchWithDistance(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)
* .order(GeoOrder.ASC)
* .count(1)));
* </pre>
* <pre>
* Map objects = geo.searchWithDistance(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)));
* </pre>
* <p>
* Requires <b>Redis 3.2.10 and higher.</b>
*
* @param args - search conditions object
* @return distance mapped by object
*/
Mono<Map<V, Double>> searchWithDistance(GeoSearchArgs args);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Mono<Map<V, Double>> radiusWithDistance(double longitude, double latitude, double radius, GeoUnit geoUnit);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Mono<Map<V, Double>> radiusWithDistance(double longitude, double latitude, double radius, GeoUnit geoUnit, int count);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Mono<Map<V, Double>> radiusWithDistance(double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Mono<Map<V, Double>> radiusWithDistance(double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/**
* Returns the position mapped by member of a sorted set,
* which are within the borders of specified search conditions.
* <p>
* Usage examples:
* <pre>
* Map objects = geo.searchWithPosition(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)
* .order(GeoOrder.ASC)
* .count(1)));
* </pre>
* <pre>
* Map objects = geo.searchWithPosition(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)));
* </pre>
* <p>
* Requires <b>Redis 3.2.10 and higher.</b>
*
* @param args - search conditions object
* @return position mapped by object
*/
Mono<Map<V, GeoPosition>> searchWithPosition(GeoSearchArgs args);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Mono<Map<V, GeoPosition>> radiusWithPosition(double longitude, double latitude, double radius, GeoUnit geoUnit);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Mono<Map<V, GeoPosition>> radiusWithPosition(double longitude, double latitude, double radius, GeoUnit geoUnit, int count);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Mono<Map<V, GeoPosition>> radiusWithPosition(double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Mono<Map<V, GeoPosition>> radiusWithPosition(double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/*
* Use search() method instead
*
*/
@Deprecated
Mono<List<V>> radius(V member, double radius, GeoUnit geoUnit);
/*
* Use search() method instead
*
*/
@Deprecated
Mono<List<V>> radius(V member, double radius, GeoUnit geoUnit, int count);
/*
* Use search() method instead
*
*/
@Deprecated
Mono<List<V>> radius(V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder);
/*
* Use search() method instead
*
*/
@Deprecated
Mono<List<V>> radius(V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Mono<Map<V, Double>> radiusWithDistance(V member, double radius, GeoUnit geoUnit);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Mono<Map<V, Double>> radiusWithDistance(V member, double radius, GeoUnit geoUnit, int count);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Mono<Map<V, Double>> radiusWithDistance(V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Mono<Map<V, Double>> radiusWithDistance(V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Mono<Map<V, GeoPosition>> radiusWithPosition(V member, double radius, GeoUnit geoUnit);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Mono<Map<V, GeoPosition>> radiusWithPosition(V member, double radius, GeoUnit geoUnit, int count);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Mono<Map<V, GeoPosition>> radiusWithPosition(V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Mono<Map<V, GeoPosition>> radiusWithPosition(V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/**
* Finds the members of a sorted set,
* which are within the borders of specified search conditions.
* <p>
* Stores result to <code>destName</code>.
* <p>
* Usage examples:
* <pre>
* long count = geo.storeSearchTo(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)
* .order(GeoOrder.ASC)
* .count(1)));
* </pre>
* <pre>
* long count = geo.storeSearchTo(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)));
* </pre>
*
* @param args - search conditions object
* @return length of result
*/
Mono<Long> storeSearchTo(String destName, GeoSearchArgs args);
/*
* Use storeSearchTo() method instead
*
*/
@Deprecated
Mono<Long> radiusStoreTo(String destName, double longitude, double latitude, double radius, GeoUnit geoUnit);
/*
* Use storeSearchTo() method instead
*
*/
@Deprecated
Mono<Long> radiusStoreTo(String destName, double longitude, double latitude, double radius, GeoUnit geoUnit, int count);
/*
* Use storeSearchTo() method instead
*
*/
@Deprecated
Mono<Long> radiusStoreTo(String destName, double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/*
* Use storeSearchTo() method instead
*
*/
@Deprecated
Mono<Long> radiusStoreTo(String destName, V member, double radius, GeoUnit geoUnit);
/*
* Use storeSearchTo() method instead
*
*/
@Deprecated
Mono<Long> radiusStoreTo(String destName, V member, double radius, GeoUnit geoUnit, int count);
/*
* Use storeSearchTo() method instead
*
*/
@Deprecated
Mono<Long> radiusStoreTo(String destName, V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/**
* Finds the members of a sorted set,
* which are within the borders of specified search conditions.
* <p>
* Stores result to <code>destName</code> sorted by distance.
* <p>
* Usage examples:
* <pre>
* long count = geo.storeSortedSearchTo(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)
* .order(GeoOrder.ASC)
* .count(1)));
* </pre>
* <pre>
* long count = geo.storeSortedSearchTo(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)));
* </pre>
*
* @param args - search conditions object
* @return length of result
*/
RFuture<Long> storeSortedSearchTo(String destName, GeoSearchArgs args);
/*
* Use storeSortedSearchTo() method instead
*
*/
@Deprecated
Mono<Long> radiusStoreSortedTo(String destName, double longitude, double latitude, double radius, GeoUnit geoUnit);
/*
* Use storeSortedSearchTo() method instead
*
*/
@Deprecated
Mono<Long> radiusStoreSortedTo(String destName, double longitude, double latitude, double radius, GeoUnit geoUnit, int count);
/*
* Use storeSortedSearchTo() method instead
*
*/
@Deprecated
Mono<Long> radiusStoreSortedTo(String destName, double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/*
* Use storeSortedSearchTo() method instead
*
*/
@Deprecated
Mono<Long> radiusStoreSortedTo(String destName, V member, double radius, GeoUnit geoUnit);
/*
* Use storeSortedSearchTo() method instead
*
*/
@Deprecated
Mono<Long> radiusStoreSortedTo(String destName, V member, double radius, GeoUnit geoUnit, int count);
/*
* Use storeSortedSearchTo() method instead
*
*/
@Deprecated
Mono<Long> radiusStoreSortedTo(String destName, V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
}
| RGeoReactive |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_3668/Child.java | {
"start": 426,
"end": 459
} | class ____ extends Child { }
}
| ChildB |
java | apache__dubbo | dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceImpl.java | {
"start": 877,
"end": 1651
} | class ____ implements MultiClassLoaderService {
private AtomicReference<MultiClassLoaderServiceRequest> innerRequestReference;
private AtomicReference<MultiClassLoaderServiceResult> innerResultReference;
public MultiClassLoaderServiceImpl(
AtomicReference<MultiClassLoaderServiceRequest> innerRequestReference,
AtomicReference<MultiClassLoaderServiceResult> innerResultReference) {
this.innerRequestReference = innerRequestReference;
this.innerResultReference = innerResultReference;
}
@Override
public MultiClassLoaderServiceResult call(MultiClassLoaderServiceRequest innerRequest) {
innerRequestReference.set(innerRequest);
return innerResultReference.get();
}
}
| MultiClassLoaderServiceImpl |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/cohere/CohereServiceSettings.java | {
"start": 2779,
"end": 12093
} | enum ____ {
V1,
V2;
public static CohereApiVersion fromString(String name) {
return valueOf(name.trim().toUpperCase(Locale.ROOT));
}
}
private static final Logger logger = LogManager.getLogger(CohereServiceSettings.class);
// Production key rate limits for all endpoints: https://docs.cohere.com/docs/going-live#production-key-specifications
// 10K requests a minute
public static final RateLimitSettings DEFAULT_RATE_LIMIT_SETTINGS = new RateLimitSettings(10_000);
public static CohereServiceSettings fromMap(Map<String, Object> map, ConfigurationParseContext context) {
ValidationException validationException = new ValidationException();
String url = extractOptionalString(map, URL, ModelConfigurations.SERVICE_SETTINGS, validationException);
SimilarityMeasure similarity = extractSimilarity(map, ModelConfigurations.SERVICE_SETTINGS, validationException);
Integer dims = removeAsType(map, DIMENSIONS, Integer.class);
Integer maxInputTokens = removeAsType(map, MAX_INPUT_TOKENS, Integer.class);
URI uri = convertToUri(url, URL, ModelConfigurations.SERVICE_SETTINGS, validationException);
String oldModelId = extractOptionalString(map, OLD_MODEL_ID_FIELD, ModelConfigurations.SERVICE_SETTINGS, validationException);
RateLimitSettings rateLimitSettings = RateLimitSettings.of(
map,
DEFAULT_RATE_LIMIT_SETTINGS,
validationException,
CohereService.NAME,
context
);
String modelId = extractOptionalString(map, MODEL_ID, ModelConfigurations.SERVICE_SETTINGS, validationException);
if (context == ConfigurationParseContext.REQUEST && oldModelId != null) {
logger.info("The cohere [service_settings.model] field is deprecated. Please use [service_settings.model_id] instead.");
}
var resolvedModelId = modelId(oldModelId, modelId);
var apiVersion = apiVersionFromMap(map, context, validationException);
if (apiVersion == CohereApiVersion.V2) {
if (resolvedModelId == null) {
validationException.addValidationError(MODEL_REQUIRED_FOR_V2_API);
}
}
if (validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
return new CohereServiceSettings(uri, similarity, dims, maxInputTokens, resolvedModelId, rateLimitSettings, apiVersion);
}
public static CohereApiVersion apiVersionFromMap(
Map<String, Object> map,
ConfigurationParseContext context,
ValidationException validationException
) {
return switch (context) {
case REQUEST -> CohereApiVersion.V2; // new endpoints all use the V2 API.
case PERSISTENT -> {
var apiVersion = ServiceUtils.extractOptionalEnum(
map,
API_VERSION,
ModelConfigurations.SERVICE_SETTINGS,
CohereApiVersion::fromString,
EnumSet.allOf(CohereApiVersion.class),
validationException
);
if (apiVersion == null) {
yield CohereApiVersion.V1; // If the API version is not persisted then it must be V1
} else {
yield apiVersion;
}
}
};
}
private static String modelId(@Nullable String model, @Nullable String modelId) {
return modelId != null ? modelId : model;
}
private final URI uri;
private final SimilarityMeasure similarity;
private final Integer dimensions;
private final Integer maxInputTokens;
private final String modelId;
private final RateLimitSettings rateLimitSettings;
private final CohereApiVersion apiVersion;
public CohereServiceSettings(
@Nullable URI uri,
@Nullable SimilarityMeasure similarity,
@Nullable Integer dimensions,
@Nullable Integer maxInputTokens,
@Nullable String modelId,
@Nullable RateLimitSettings rateLimitSettings,
CohereApiVersion apiVersion
) {
this.uri = uri;
this.similarity = similarity;
this.dimensions = dimensions;
this.maxInputTokens = maxInputTokens;
this.modelId = modelId;
this.rateLimitSettings = Objects.requireNonNullElse(rateLimitSettings, DEFAULT_RATE_LIMIT_SETTINGS);
this.apiVersion = apiVersion;
}
public CohereServiceSettings(
@Nullable String url,
@Nullable SimilarityMeasure similarity,
@Nullable Integer dimensions,
@Nullable Integer maxInputTokens,
@Nullable String modelId,
@Nullable RateLimitSettings rateLimitSettings,
CohereApiVersion apiVersion
) {
this(createOptionalUri(url), similarity, dimensions, maxInputTokens, modelId, rateLimitSettings, apiVersion);
}
public CohereServiceSettings(StreamInput in) throws IOException {
uri = createOptionalUri(in.readOptionalString());
similarity = in.readOptionalEnum(SimilarityMeasure.class);
dimensions = in.readOptionalVInt();
maxInputTokens = in.readOptionalVInt();
modelId = in.readOptionalString();
rateLimitSettings = new RateLimitSettings(in);
if (in.getTransportVersion().supports(ML_INFERENCE_COHERE_API_VERSION)) {
this.apiVersion = in.readEnum(CohereServiceSettings.CohereApiVersion.class);
} else {
this.apiVersion = CohereServiceSettings.CohereApiVersion.V1;
}
}
// should only be used for testing, public because it's accessed outside of the package
public CohereServiceSettings(CohereApiVersion apiVersion) {
this((URI) null, null, null, null, null, null, apiVersion);
}
@Override
public RateLimitSettings rateLimitSettings() {
return rateLimitSettings;
}
@Override
public CohereApiVersion apiVersion() {
return apiVersion;
}
public URI uri() {
return uri;
}
@Override
public SimilarityMeasure similarity() {
return similarity;
}
@Override
public Integer dimensions() {
return dimensions;
}
public Integer maxInputTokens() {
return maxInputTokens;
}
@Override
public String modelId() {
return modelId;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
toXContentFragment(builder, params);
builder.endObject();
return builder;
}
public XContentBuilder toXContentFragment(XContentBuilder builder, Params params) throws IOException {
toXContentFragmentOfExposedFields(builder, params);
return builder.field(API_VERSION, apiVersion); // API version is persisted but not exposed to the user
}
@Override
public XContentBuilder toXContentFragmentOfExposedFields(XContentBuilder builder, Params params) throws IOException {
if (uri != null) {
builder.field(URL, uri.toString());
}
if (similarity != null) {
builder.field(SIMILARITY, similarity);
}
if (dimensions != null) {
builder.field(DIMENSIONS, dimensions);
}
if (maxInputTokens != null) {
builder.field(MAX_INPUT_TOKENS, maxInputTokens);
}
if (modelId != null) {
builder.field(MODEL_ID, modelId);
}
rateLimitSettings.toXContent(builder, params);
return builder;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersions.V_8_13_0;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
var uriToWrite = uri != null ? uri.toString() : null;
out.writeOptionalString(uriToWrite);
out.writeOptionalEnum(SimilarityMeasure.translateSimilarity(similarity, out.getTransportVersion()));
out.writeOptionalVInt(dimensions);
out.writeOptionalVInt(maxInputTokens);
out.writeOptionalString(modelId);
rateLimitSettings.writeTo(out);
if (out.getTransportVersion().supports(ML_INFERENCE_COHERE_API_VERSION)) {
out.writeEnum(apiVersion);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CohereServiceSettings that = (CohereServiceSettings) o;
return Objects.equals(uri, that.uri)
&& Objects.equals(similarity, that.similarity)
&& Objects.equals(dimensions, that.dimensions)
&& Objects.equals(maxInputTokens, that.maxInputTokens)
&& Objects.equals(modelId, that.modelId)
&& Objects.equals(rateLimitSettings, that.rateLimitSettings)
&& apiVersion == that.apiVersion;
}
@Override
public int hashCode() {
return Objects.hash(uri, similarity, dimensions, maxInputTokens, modelId, rateLimitSettings, apiVersion);
}
}
| CohereApiVersion |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/EnclosedInSquareBracketsConverter.java | {
"start": 1584,
"end": 2889
} | class ____ extends LogEventPatternConverter {
private final List<PatternFormatter> formatters;
private EnclosedInSquareBracketsConverter(List<PatternFormatter> formatters) {
super("enclosedInSquareBrackets", null);
this.formatters = formatters;
}
@Override
public void format(LogEvent event, StringBuilder toAppendTo) {
StringBuilder buf = new StringBuilder();
for (PatternFormatter formatter : this.formatters) {
formatter.format(event, buf);
}
if (buf.isEmpty()) {
return;
}
toAppendTo.append("[");
toAppendTo.append(buf);
toAppendTo.append("] ");
}
/**
* Creates a new instance of the class. Required by Log4J2.
* @param config the configuration
* @param options the options
* @return a new instance, or {@code null} if the options are invalid
*/
public static @Nullable EnclosedInSquareBracketsConverter newInstance(@Nullable Configuration config,
String[] options) {
if (options.length < 1) {
LOGGER.error("Incorrect number of options on style. Expected at least 1, received {}", options.length);
return null;
}
PatternParser parser = PatternLayout.createPatternParser(config);
List<PatternFormatter> formatters = parser.parse(options[0]);
return new EnclosedInSquareBracketsConverter(formatters);
}
}
| EnclosedInSquareBracketsConverter |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/StartupCondition.java | {
"start": 1109,
"end": 1882
} | interface ____ {
/**
* The name of condition used for logging purposes.
*/
default String getName() {
return this.getClass().getSimpleName();
}
/**
* Optional logging message to log before waiting for the condition
*/
default String getWaitMessage() {
return null;
}
/**
* Optional logging message to log if condition was not meet.
*/
default String getFailureMessage() {
return null;
}
/**
* Checks if the condition is accepted
*
* @param camelContext the Camel context (is not fully initialized)
* @return true to continue, false to stop and fail.
*/
boolean canContinue(CamelContext camelContext) throws Exception;
}
| StartupCondition |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/response/ResponseTest.java | {
"start": 263,
"end": 1418
} | class ____ {
@Test
public void testCaseInsensitivity() {
Response response = Response.status(Response.Status.METHOD_NOT_ALLOWED)
.header("allow", "HEAD").header(HttpHeaders.HOST, "whatever").build();
Assertions.assertEquals("HEAD", response.getHeaders().getFirst("allow"));
Assertions.assertEquals("HEAD", response.getHeaders().getFirst(HttpHeaders.ALLOW));
}
@Test
public void testLocation() {
final var location = UriBuilder.fromUri("http://localhost:8080").path("{language}")
.build("en/us");
Response response = Response.ok("Hello").location(location).build();
Assertions.assertEquals("http://localhost:8080/en%2Fus", response.getLocation().toString());
}
@Test
public void testContentLocation() {
final var location = UriBuilder.fromUri("http://localhost:8080").path("{language}")
.build("en/us");
Response response = Response.ok("Hello").contentLocation(location).build();
Assertions.assertEquals("http://localhost:8080/en%2Fus", response.getHeaderString("Content-Location"));
}
}
| ResponseTest |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/FluxMetricsFuseable.java | {
"start": 1530,
"end": 2601
} | class ____<T> extends InternalFluxOperator<T, T> implements Fuseable {
final String name;
final Tags tags;
final MeterRegistry registryCandidate;
FluxMetricsFuseable(Flux<? extends T> flux) {
super(flux);
this.name = resolveName(flux);
this.tags = resolveTags(flux, FluxMetrics.DEFAULT_TAGS_FLUX);
this.registryCandidate = Metrics.MicrometerConfiguration.getRegistry();
}
@Override
public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) {
return new MetricsFuseableSubscriber<>(actual, registryCandidate, Clock.SYSTEM, this.name, this.tags);
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return super.scanUnsafe(key);
}
/**
* @param <T>
*
* @implNote we don't want to particularly track fusion-specific calls, as this subscriber would only detect fused
* subsequences immediately upstream of it, so Counters would be a bit irrelevant. We however want to instrument
* onNext counts.
*/
static final | FluxMetricsFuseable |
java | spring-projects__spring-framework | spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJEnableCachingIsolatedTests.java | {
"start": 6484,
"end": 6742
} | class ____ {
@Bean
public CacheManager cm1() {
return new NoOpCacheManager();
}
@Bean
public CacheManager cm2() {
return new NoOpCacheManager();
}
}
@Configuration
@EnableCaching(mode = AdviceMode.ASPECTJ)
static | MultiCacheManagerConfig |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/spring/tx/error/TransactionErrorHandlerBuilderAsSpringBeanIT.java | {
"start": 1344,
"end": 2170
} | class ____ extends AbstractSpringJMSITSupport {
@Override
protected ClassPathXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext(
"/org/apache/camel/component/jms/integration/spring/tx/error/TransactionErrorHandlerBuilderAsSpringBeanIT.xml");
}
@Test
public void testTransactionSuccess() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.expectedBodiesReceived("Bye World");
// success at 3rd attempt
mock.message(0).header("count").isEqualTo(3);
template.sendBody("activemq:queue:okay.TransactionErrorHandlerBuilderAsSpringBeanTest", "Hello World");
mock.assertIsSatisfied();
}
}
| TransactionErrorHandlerBuilderAsSpringBeanIT |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/predicate/operator/comparison/LessThanOrEqualDoublesEvaluator.java | {
"start": 1210,
"end": 5094
} | class ____ implements EvalOperator.ExpressionEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(LessThanOrEqualDoublesEvaluator.class);
private final Source source;
private final EvalOperator.ExpressionEvaluator lhs;
private final EvalOperator.ExpressionEvaluator rhs;
private final DriverContext driverContext;
private Warnings warnings;
public LessThanOrEqualDoublesEvaluator(Source source, EvalOperator.ExpressionEvaluator lhs,
EvalOperator.ExpressionEvaluator rhs, DriverContext driverContext) {
this.source = source;
this.lhs = lhs;
this.rhs = rhs;
this.driverContext = driverContext;
}
@Override
public Block eval(Page page) {
try (DoubleBlock lhsBlock = (DoubleBlock) lhs.eval(page)) {
try (DoubleBlock rhsBlock = (DoubleBlock) rhs.eval(page)) {
DoubleVector lhsVector = lhsBlock.asVector();
if (lhsVector == null) {
return eval(page.getPositionCount(), lhsBlock, rhsBlock);
}
DoubleVector rhsVector = rhsBlock.asVector();
if (rhsVector == null) {
return eval(page.getPositionCount(), lhsBlock, rhsBlock);
}
return eval(page.getPositionCount(), lhsVector, rhsVector).asBlock();
}
}
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += lhs.baseRamBytesUsed();
baseRamBytesUsed += rhs.baseRamBytesUsed();
return baseRamBytesUsed;
}
public BooleanBlock eval(int positionCount, DoubleBlock lhsBlock, DoubleBlock rhsBlock) {
try(BooleanBlock.Builder result = driverContext.blockFactory().newBooleanBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
switch (lhsBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
switch (rhsBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
double lhs = lhsBlock.getDouble(lhsBlock.getFirstValueIndex(p));
double rhs = rhsBlock.getDouble(rhsBlock.getFirstValueIndex(p));
result.appendBoolean(LessThanOrEqual.processDoubles(lhs, rhs));
}
return result.build();
}
}
public BooleanVector eval(int positionCount, DoubleVector lhsVector, DoubleVector rhsVector) {
try(BooleanVector.FixedBuilder result = driverContext.blockFactory().newBooleanVectorFixedBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
double lhs = lhsVector.getDouble(p);
double rhs = rhsVector.getDouble(p);
result.appendBoolean(p, LessThanOrEqual.processDoubles(lhs, rhs));
}
return result.build();
}
}
@Override
public String toString() {
return "LessThanOrEqualDoublesEvaluator[" + "lhs=" + lhs + ", rhs=" + rhs + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(lhs, rhs);
}
private Warnings warnings() {
if (warnings == null) {
this.warnings = Warnings.createWarnings(
driverContext.warningsMode(),
source.source().getLineNumber(),
source.source().getColumnNumber(),
source.text()
);
}
return warnings;
}
static | LessThanOrEqualDoublesEvaluator |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/filter/FilterDefinitionOrderTest.java | {
"start": 1265,
"end": 2370
} | class ____ extends AbstractStatefulStatelessFilterTest {
@BeforeEach
void setUp() {
scope.inTransaction(session -> {
AMyEntity entity1 = new AMyEntity();
entity1.setField("test");
AMyEntity entity2 = new AMyEntity();
entity2.setField("Hello");
session.persist(entity1);
session.persist(entity2);
});
}
@AfterEach
void tearDown() {
scope.dropData();
}
@ParameterizedTest
@MethodSource("transactionKind")
void smokeTest(BiConsumer<SessionFactoryScope, Consumer<? extends SharedSessionContract>> inTransaction) {
inTransaction.accept(scope, session -> {
session.enableFilter("x_filter");
List<AMyEntity> entities = session.createQuery("FROM AMyEntity", AMyEntity.class).getResultList();
assertThat(entities).hasSize(1)
.allSatisfy(entity -> assertThat(entity.getField()).isEqualTo("Hello"));
session.disableFilter("x_filter");
entities = session.createQuery("FROM AMyEntity", AMyEntity.class).getResultList();
assertThat(entities).hasSize(2);
});
}
@Entity(name = "AMyEntity")
@Filter(name = "x_filter")
public static | FilterDefinitionOrderTest |
java | alibaba__nacos | common/src/main/java/com/alibaba/nacos/common/packagescan/resource/AntPathMatcher.java | {
"start": 31701,
"end": 34206
} | class ____ implements Comparator<String> {
private final String path;
public AntPatternComparator(String path) {
this.path = path;
}
/**
* Compare two patterns to determine which should match first, i.e. which
* is the most specific regarding the current path.
*
* @return a negative integer, zero, or a positive integer as pattern1 is
* more specific, equally specific, or less specific than pattern2.
*/
@Override
public int compare(String pattern1, String pattern2) {
PatternInfo info1 = new PatternInfo(pattern1);
PatternInfo info2 = new PatternInfo(pattern2);
if (info1.isLeastSpecific() && info2.isLeastSpecific()) {
return 0;
} else if (info1.isLeastSpecific()) {
return 1;
} else if (info2.isLeastSpecific()) {
return -1;
}
boolean pattern1EqualsPath = pattern1.equals(this.path);
boolean pattern2EqualsPath = pattern2.equals(this.path);
if (pattern1EqualsPath && pattern2EqualsPath) {
return 0;
} else if (pattern1EqualsPath) {
return -1;
} else if (pattern2EqualsPath) {
return 1;
}
if (info1.isPrefixPattern() && info2.isPrefixPattern()) {
return info2.getLength() - info1.getLength();
} else if (info1.isPrefixPattern() && info2.getDoubleWildcards() == 0) {
return 1;
} else if (info2.isPrefixPattern() && info1.getDoubleWildcards() == 0) {
return -1;
}
if (info1.getTotalCount() != info2.getTotalCount()) {
return info1.getTotalCount() - info2.getTotalCount();
}
if (info1.getLength() != info2.getLength()) {
return info2.getLength() - info1.getLength();
}
if (info1.getSingleWildcards() < info2.getSingleWildcards()) {
return -1;
} else if (info2.getSingleWildcards() < info1.getSingleWildcards()) {
return 1;
}
if (info1.getUriVars() < info2.getUriVars()) {
return -1;
} else if (info2.getUriVars() < info1.getUriVars()) {
return 1;
}
return 0;
}
/**
* Value | AntPatternComparator |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/engine/creation/internal/SharedSessionCreationOptions.java | {
"start": 757,
"end": 1866
} | interface ____ extends SessionCreationOptions {
boolean isTransactionCoordinatorShared();
TransactionCoordinator getTransactionCoordinator();
JdbcCoordinator getJdbcCoordinator();
Transaction getTransaction();
TransactionCompletionCallbacksImplementor getTransactionCompletionCallbacks();
/**
* Registers callbacks for the child session to integrate with events of the parent session.
*/
void registerParentSessionObserver(ParentSessionObserver observer);
/**
* Consolidated implementation of adding the parent session observer.
*/
default void registerParentSessionObserver(ParentSessionObserver observer, SharedSessionContractImplementor original) {
original.getEventListenerManager().addListener( new SessionEventListener() {
@Override
public void flushEnd(int numberOfEntities, int numberOfCollections) {
observer.onParentFlush();
}
@Override
public void partialFlushEnd(int numberOfEntities, int numberOfCollections) {
observer.onParentFlush();
}
@Override
public void end() {
observer.onParentClose();
}
} );
}
}
| SharedSessionCreationOptions |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/EmbeddedAnyTest.java | {
"start": 3080,
"end": 3473
} | class ____ {
@Id
private Integer id;
@Embedded
private FooEmbeddable fooEmbedded;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public FooEmbeddable getFooEmbedded() {
return fooEmbedded;
}
public void setFooEmbedded(FooEmbeddable fooEmbedded) {
this.fooEmbedded = fooEmbedded;
}
}
@Embeddable
public static | Foo |
java | apache__dubbo | dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactoryTest.java | {
"start": 1070,
"end": 1526
} | class ____ {
@Test
void test() {
ApplicationModel applicationModel = ApplicationModel.defaultModel();
PrometheusMetricsReporterFactory factory = new PrometheusMetricsReporterFactory(applicationModel);
MetricsReporter reporter = factory.createMetricsReporter(URL.valueOf("prometheus://localhost:9090/"));
Assertions.assertTrue(reporter instanceof PrometheusMetricsReporter);
}
}
| PrometheusMetricsReporterFactoryTest |
java | google__guice | core/test/com/google/inject/AllTests.java | {
"start": 2057,
"end": 5423
} | class ____ {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTestSuite(BinderTest.class);
suite.addTest(BinderTestSuite.suite());
suite.addTestSuite(BindingAnnotationTest.class);
suite.addTestSuite(BindingOrderTest.class);
suite.addTestSuite(BoundInstanceInjectionTest.class);
suite.addTestSuite(BoundProviderTest.class);
suite.addTestSuite(CircularDependencyTest.class);
suite.addTestSuite(DuplicateBindingsTest.class);
suite.addTestSuite(EagerSingletonTest.class);
suite.addTestSuite(GenericInjectionTest.class);
suite.addTestSuite(ImplicitBindingTest.class);
suite.addTestSuite(ImplicitBindingJdkPackagePrivateTest.class);
suite.addTestSuite(InjectorTest.class);
suite.addTestSuite(JitBindingsTest.class);
suite.addTestSuite(Java8LanguageFeatureBindingTest.class);
suite.addTestSuite(KeyTest.class);
suite.addTestSuite(LoggerInjectionTest.class);
suite.addTestSuite(MembersInjectorTest.class);
suite.addTestSuite(ModulesTest.class);
suite.addTestSuite(ModuleTest.class);
suite.addTestSuite(NullableInjectionPointTest.class);
suite.addTestSuite(OptionalBindingTest.class);
suite.addTestSuite(OverrideModuleTest.class);
suite.addTestSuite(PrivateModuleTest.class);
suite.addTestSuite(ProviderInjectionTest.class);
suite.addTestSuite(ProvisionExceptionTest.class);
suite.addTestSuite(ProvisionListenerTest.class);
suite.addTestSuite(ReflectionTest.class);
suite.addTestSuite(RequestInjectionTest.class);
suite.addTestSuite(RequireAtInjectOnConstructorsTest.class);
suite.addTestSuite(SerializationTest.class);
suite.addTestSuite(SuperclassTest.class);
suite.addTestSuite(TypeConversionTest.class);
suite.addTestSuite(TypeLiteralInjectionTest.class);
suite.addTestSuite(TypeLiteralTest.class);
suite.addTestSuite(TypeLiteralTypeResolutionTest.class);
suite.addTestSuite(WeakKeySetTest.class);
// internal
suite.addTestSuite(MoreTypesTest.class);
suite.addTestSuite(UniqueAnnotationsTest.class);
// matcher
suite.addTestSuite(MatcherTest.class);
// names
suite.addTestSuite(NamesTest.class);
suite.addTestSuite(NamedEquivalanceTest.class);
// spi
suite.addTestSuite(BindingTargetVisitorTest.class);
suite.addTestSuite(ElementsTest.class);
suite.addTestSuite(ElementApplyToTest.class);
suite.addTestSuite(HasDependenciesTest.class);
suite.addTestSuite(InjectionPointTest.class);
suite.addTestSuite(InjectorSpiTest.class);
suite.addTestSuite(ModuleRewriterTest.class);
suite.addTestSuite(SpiBindingsTest.class);
suite.addTestSuite(ToolStageInjectorTest.class);
suite.addTestSuite(ModuleSourceTest.class);
suite.addTestSuite(ElementSourceTest.class);
suite.addTestSuite(MessageTest.class);
// tools
// suite.addTestSuite(JmxTest.class); not a testcase
// util
suite.addTestSuite(NoopOverrideTest.class);
suite.addTestSuite(ProvidersTest.class);
suite.addTestSuite(TypesTest.class);
// multibindings tests
suite.addTestSuite(MapBinderTest.class);
suite.addTestSuite(MultibinderTest.class);
suite.addTestSuite(OptionalBinderTest.class);
suite.addTestSuite(RealElementTest.class);
suite.addTestSuite(ProvidesIntoTest.class);
return suite;
}
}
| AllTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java | {
"start": 163032,
"end": 163578
} | class ____ implements CacheEntryHelper {
private final EntityPersister persister;
private ReferenceCacheEntryHelper(EntityPersister persister) {
this.persister = persister;
}
@Override
public CacheEntryStructure getCacheEntryStructure() {
return UnstructuredCacheEntry.INSTANCE;
}
@Override
public CacheEntry buildCacheEntry(Object entity, Object[] state, Object version, SharedSessionContractImplementor session) {
return new ReferenceCacheEntryImpl( entity, persister );
}
}
private static | ReferenceCacheEntryHelper |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java | {
"start": 93042,
"end": 94457
} | interface ____ the contract for classes that know how to convert a String into some domain object.
* Custom converters can be registered with the {@link #registerConverter(Class, ITypeConverter)} method.
* </p><p>
* Java 8 lambdas make it easy to register custom type converters:
* </p>
* <pre>
* commandLine.registerConverter(java.nio.file.Path.class, s -> java.nio.file.Paths.get(s));
* commandLine.registerConverter(java.time.Duration.class, s -> java.time.Duration.parse(s));</pre>
* <p>
* Built-in type converters are pre-registered for the following java 1.5 types:
* </p>
* <ul>
* <li>all primitive types</li>
* <li>all primitive wrapper types: Boolean, Byte, Character, Double, Float, Integer, Long, Short</li>
* <li>any enum</li>
* <li>java.io.File</li>
* <li>java.math.BigDecimal</li>
* <li>java.math.BigInteger</li>
* <li>java.net.InetAddress</li>
* <li>java.net.URI</li>
* <li>java.net.URL</li>
* <li>java.nio.charset.Charset</li>
* <li>java.sql.Time</li>
* <li>java.util.Date</li>
* <li>java.util.UUID</li>
* <li>java.util.regex.Pattern</li>
* <li>StringBuilder</li>
* <li>CharSequence</li>
* <li>String</li>
* </ul>
* @param <K> the type of the object that is the result of the conversion
*/
public | defines |
java | spring-projects__spring-framework | spring-tx/src/main/java/org/springframework/dao/TransientDataAccessResourceException.java | {
"start": 898,
"end": 1429
} | class ____ extends TransientDataAccessException {
/**
* Constructor for TransientDataAccessResourceException.
* @param msg the detail message
*/
public TransientDataAccessResourceException(String msg) {
super(msg);
}
/**
* Constructor for TransientDataAccessResourceException.
* @param msg the detail message
* @param cause the root cause from the data access API in use
*/
public TransientDataAccessResourceException(String msg, Throwable cause) {
super(msg, cause);
}
}
| TransientDataAccessResourceException |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/ref/RefTest15.java | {
"start": 164,
"end": 791
} | class ____ extends TestCase {
public void test_0 () throws Exception {
List<Object> a = new ArrayList<Object>();
List<Object> b = new ArrayList<Object>();
List<Object> c = new ArrayList<Object>();
List<Object> d = new ArrayList<Object>();
a.add(b);
a.add(c);
a.add(d);
b.add(a);
b.add(c);
b.add(d);
c.add(a);
c.add(b);
c.add(d);
d.add(a);
d.add(b);
d.add(c);
String text = JSON.toJSONString(a);
System.out.println(text);
}
}
| RefTest15 |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/utils/AbstractIterator.java | {
"start": 922,
"end": 1043
} | class ____ simplifies implementing an iterator
* @param <T> The type of thing we are iterating over
*/
public abstract | that |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Mogujie_01.java | {
"start": 768,
"end": 1549
} | class ____ {
public int f0;
public int f1;
public int f2;
public int f3;
public int f4;
public int f5;
public int f6;
public int f7;
public int f8;
public int f9;
public int f10;
public int f11;
public int f12;
public int f13;
public int f14;
public int f15;
public int f16;
public int f17;
public int f18;
public int f19;
public int f20;
public int f21;
public int f22;
public int f23;
public int f24;
public int f25;
public int f26;
public int f27;
public int f28;
public int f29;
public int f30;
public int f31;
}
}
| Model |
java | netty__netty | transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpServerChannel.java | {
"start": 1830,
"end": 7035
} | class ____ extends AbstractNioMessageChannel
implements io.netty.channel.sctp.SctpServerChannel {
private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16);
private static SctpServerChannel newSocket() {
try {
return SctpServerChannel.open();
} catch (IOException e) {
throw new ChannelException(
"Failed to open a server socket.", e);
}
}
private final SctpServerChannelConfig config;
/**
* Create a new instance
*/
public NioSctpServerChannel() {
super(null, newSocket(), SelectionKey.OP_ACCEPT);
config = new NioSctpServerChannelConfig(this, javaChannel());
}
@Override
public ChannelMetadata metadata() {
return METADATA;
}
@Override
public Set<InetSocketAddress> allLocalAddresses() {
try {
final Set<SocketAddress> allLocalAddresses = javaChannel().getAllLocalAddresses();
final Set<InetSocketAddress> addresses = new LinkedHashSet<InetSocketAddress>(allLocalAddresses.size());
for (SocketAddress socketAddress : allLocalAddresses) {
addresses.add((InetSocketAddress) socketAddress);
}
return addresses;
} catch (Throwable ignored) {
return Collections.emptySet();
}
}
@Override
public SctpServerChannelConfig config() {
return config;
}
@Override
public boolean isActive() {
return isOpen() && !allLocalAddresses().isEmpty();
}
@Override
public InetSocketAddress remoteAddress() {
return null;
}
@Override
public InetSocketAddress localAddress() {
return (InetSocketAddress) super.localAddress();
}
@Override
protected SctpServerChannel javaChannel() {
return (SctpServerChannel) super.javaChannel();
}
@Override
protected SocketAddress localAddress0() {
try {
Iterator<SocketAddress> i = javaChannel().getAllLocalAddresses().iterator();
if (i.hasNext()) {
return i.next();
}
} catch (IOException e) {
// ignore
}
return null;
}
@Override
protected void doBind(SocketAddress localAddress) throws Exception {
javaChannel().bind(localAddress, config.getBacklog());
}
@Override
protected void doClose() throws Exception {
javaChannel().close();
}
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
SctpChannel ch = javaChannel().accept();
if (ch == null) {
return 0;
}
buf.add(new NioSctpChannel(this, ch));
return 1;
}
@Override
public ChannelFuture bindAddress(InetAddress localAddress) {
return bindAddress(localAddress, newPromise());
}
@Override
public ChannelFuture bindAddress(final InetAddress localAddress, final ChannelPromise promise) {
if (eventLoop().inEventLoop()) {
try {
javaChannel().bindAddress(localAddress);
promise.setSuccess();
} catch (Throwable t) {
promise.setFailure(t);
}
} else {
eventLoop().execute(new Runnable() {
@Override
public void run() {
bindAddress(localAddress, promise);
}
});
}
return promise;
}
@Override
public ChannelFuture unbindAddress(InetAddress localAddress) {
return unbindAddress(localAddress, newPromise());
}
@Override
public ChannelFuture unbindAddress(final InetAddress localAddress, final ChannelPromise promise) {
if (eventLoop().inEventLoop()) {
try {
javaChannel().unbindAddress(localAddress);
promise.setSuccess();
} catch (Throwable t) {
promise.setFailure(t);
}
} else {
eventLoop().execute(new Runnable() {
@Override
public void run() {
unbindAddress(localAddress, promise);
}
});
}
return promise;
}
// Unnecessary stuff
@Override
protected boolean doConnect(
SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected void doFinishConnect() throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected SocketAddress remoteAddress0() {
return null;
}
@Override
protected void doDisconnect() throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected Object filterOutboundMessage(Object msg) throws Exception {
throw new UnsupportedOperationException();
}
private final | NioSctpServerChannel |
java | apache__camel | components/camel-jt400/src/test/java/org/apache/camel/component/jt400/Jt400DataQueueConsumerManualTest.java | {
"start": 1679,
"end": 3973
} | class ____ {
/**
* The deviation of the actual timeout value that we permit in our timeout tests.
*/
private static final long TIMEOUT_TOLERANCE = 300L;
/**
* Timeout value in milliseconds used to test <code>receive(long)</code>.
*/
private static final long TIMEOUT_VALUE = 3999L;
/**
* The amount of time in milliseconds to pass so that a call is assumed to be a blocking call.
*/
private static final long BLOCKING_THRESHOLD = 5000L;
/**
* The consumer instance used in the tests.
*/
private Jt400DataQueueConsumer consumer;
/**
* Flag that indicates whether <code>receive()</code> has returned from call.
*/
private boolean receiveFlag;
@BeforeEach
public void setUp() throws Exception {
// Load endpoint URI
Properties props = TestSupport.loadExternalProperties(getClass(), "jt400test.properties");
String endpointURI = props.getProperty("org.apache.camel.component.jt400.emptydtaq.uri");
// Instantiate consumer
CamelContext camel = new DefaultCamelContext();
Jt400Component component = new Jt400Component();
component.setCamelContext(camel);
consumer = (Jt400DataQueueConsumer) component.createEndpoint(endpointURI).createPollingConsumer();
camel.start();
}
/**
* Tests whether <code>receive(long)</code> honours the <code>timeout</code> parameter.
*/
@Test
public void testReceiveLong() {
assertTimeout(Duration.ofMillis(TIMEOUT_VALUE + TIMEOUT_TOLERANCE),
() -> consumer.receive(TIMEOUT_VALUE));
}
/**
* Tests whether receive() blocks indefinitely.
*/
@Test
public void testReceive() throws InterruptedException {
new Thread(new Runnable() {
public void run() {
consumer.receive();
receiveFlag = true;
}
}).start();
StopWatch watch = new StopWatch();
while (!receiveFlag) {
if ((watch.taken()) > BLOCKING_THRESHOLD) {
/* Passed test. */
return;
}
Thread.sleep(50L);
}
fail("Method receive() has returned from call.");
}
}
| Jt400DataQueueConsumerManualTest |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/java/typeutils/runtime/Tuple0Serializer.java | {
"start": 1255,
"end": 3585
} | class ____ extends TupleSerializer<Tuple0> {
private static final long serialVersionUID = 1278813169022975971L;
public static final Tuple0Serializer INSTANCE = new Tuple0Serializer();
// ------------------------------------------------------------------------
private Tuple0Serializer() {
super(Tuple0.class, new TypeSerializer<?>[0]);
}
// ------------------------------------------------------------------------
@Override
public Tuple0Serializer duplicate() {
return this;
}
@Override
public Tuple0 createInstance() {
return Tuple0.INSTANCE;
}
@Override
public Tuple0 createInstance(Object[] fields) {
if (fields == null || fields.length == 0) {
return Tuple0.INSTANCE;
}
throw new UnsupportedOperationException(
"Tuple0 cannot take any data, as it has zero fields.");
}
@Override
public Tuple0 copy(Tuple0 from) {
return from;
}
@Override
public Tuple0 copy(Tuple0 from, Tuple0 reuse) {
return reuse;
}
@Override
public int getLength() {
return 1;
}
@Override
public void serialize(Tuple0 record, DataOutputView target) throws IOException {
Preconditions.checkNotNull(record);
target.writeByte(42);
}
@Override
public Tuple0 deserialize(DataInputView source) throws IOException {
source.readByte();
return Tuple0.INSTANCE;
}
@Override
public Tuple0 deserialize(Tuple0 reuse, DataInputView source) throws IOException {
source.readByte();
return reuse;
}
@Override
public void copy(DataInputView source, DataOutputView target) throws IOException {
target.writeByte(source.readByte());
}
@Override
public TypeSerializerSnapshot<Tuple0> snapshotConfiguration() {
return new Tuple0SerializerSnapshot();
}
// ------------------------------------------------------------------------
@Override
public int hashCode() {
return Tuple0Serializer.class.hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof Tuple0Serializer;
}
@Override
public String toString() {
return "Tuple0Serializer";
}
}
| Tuple0Serializer |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/discovery/DiscoverySelectorResolverTests.java | {
"start": 38211,
"end": 38277
} | class ____ {
@Test
void testB() {
}
@Nested
| NestedTestCase |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/AutoCloseableBDDSoftAssertionsTest.java | {
"start": 1663,
"end": 10942
} | class ____ {
@Test
void all_assertions_should_pass() {
try (AutoCloseableBDDSoftAssertions softly = new AutoCloseableBDDSoftAssertions()) {
softly.then(1).isEqualTo(1);
softly.then(Lists.newArrayList(1, 2)).containsOnly(1, 2);
}
}
@Test
void should_be_able_to_catch_exceptions_thrown_by_all_proxied_methods() {
try (AutoCloseableBDDSoftAssertions softly = new AutoCloseableBDDSoftAssertions()) {
softly.then(BigDecimal.ZERO).isEqualTo(BigDecimal.ONE);
softly.then(Boolean.FALSE).isTrue();
softly.then(false).isTrue();
softly.then(new boolean[] { false }).isEqualTo(new boolean[] { true });
softly.then(Byte.valueOf((byte) 0)).isEqualTo((byte) 1);
softly.then((byte) 2).inHexadecimal().isEqualTo((byte) 3);
softly.then(new byte[] { 4 }).isEqualTo(new byte[] { 5 });
softly.then(Character.valueOf((char) 65)).isEqualTo(Character.valueOf((char) 66));
softly.then((char) 67).isEqualTo((char) 68);
softly.then(new char[] { 69 }).isEqualTo(new char[] { 70 });
softly.then(new StringBuilder("a")).isEqualTo(new StringBuilder("b"));
softly.then(Object.class).isEqualTo(String.class);
softly.then(parseDatetime("1999-12-31T23:59:59")).isEqualTo(parseDatetime("2000-01-01T00:00:01"));
softly.then(Double.valueOf(6.0d)).isEqualTo(Double.valueOf(7.0d));
softly.then(8.0d).isEqualTo(9.0d);
softly.then(new double[] { 10.0d }).isEqualTo(new double[] { 11.0d });
softly.then(new File("a"))
.overridingErrorMessage(shouldBeEqualMessage("File(a)", "File(b)"))
.isEqualTo(new File("b"));
softly.then(Float.valueOf(12f)).isEqualTo(Float.valueOf(13f));
softly.then(14f).isEqualTo(15f);
softly.then(new float[] { 16f }).isEqualTo(new float[] { 17f });
softly.then(new ByteArrayInputStream(new byte[] { (byte) 65 }))
.hasSameContentAs(new ByteArrayInputStream(new byte[] { (byte) 66 }));
softly.then(Integer.valueOf(20)).isEqualTo(Integer.valueOf(21));
softly.then(22).isEqualTo(23);
softly.then(new int[] { 24 }).isEqualTo(new int[] { 25 });
softly.then((Iterable<String>) Lists.newArrayList("26")).isEqualTo(Lists.newArrayList("27"));
softly.then(list("28").iterator()).isExhausted();
softly.then(list("30")).isEqualTo(Lists.newArrayList("31"));
softly.then(Long.valueOf(32L)).isEqualTo(Long.valueOf(33L));
softly.then(34L).isEqualTo(35L);
softly.then(new long[] { 36L }).isEqualTo(new long[] { 37L });
softly.then(mapOf(MapEntry.entry("38", "39"))).isEqualTo(mapOf(MapEntry.entry("40", "41")));
softly.then(Short.valueOf((short) 42)).isEqualTo(Short.valueOf((short) 43));
softly.then((short) 44).isEqualTo((short) 45);
softly.then(new short[] { (short) 46 }).isEqualTo(new short[] { (short) 47 });
softly.then("48").isEqualTo("49");
softly.then(new Object() {
@Override
public String toString() {
return "50";
}
}).isEqualTo(new Object() {
@Override
public String toString() {
return "51";
}
});
softly.then(new Object[] { new Object() {
@Override
public String toString() {
return "52";
}
} }).isEqualTo(new Object[] { new Object() {
@Override
public String toString() {
return "53";
}
} });
final IllegalArgumentException illegalArgumentException = new IllegalArgumentException("IllegalArgumentException message");
softly.then(illegalArgumentException).hasMessage("NullPointerException message");
softly.then(Optional.of("not empty")).isEqualTo("empty");
softly.then(OptionalInt.of(0)).isEqualTo(1);
softly.then(OptionalDouble.of(0.0)).isEqualTo(1.0);
softly.then(OptionalLong.of(0L)).isEqualTo(1L);
softly.then(LocalTime.of(12, 0)).isEqualTo(LocalTime.of(13, 0));
softly.then(OffsetTime.of(12, 0, 0, 0, ZoneOffset.UTC)).isEqualTo(OffsetTime.of(13, 0, 0, 0, ZoneOffset.UTC));
softly.then(OffsetDateTime.MIN).isEqualTo(OffsetDateTime.MAX);
} catch (MultipleFailuresError e) {
List<String> errors = e.getFailures().stream().map(Object::toString).collect(toList());
assertThat(errors).hasSize(45);
assertThat(errors.get(0)).contains(shouldBeEqualMessage("0", "1"));
assertThat(errors.get(1)).contains("%nExpecting value to be true but was false".formatted());
assertThat(errors.get(2)).contains("%nExpecting value to be true but was false".formatted());
assertThat(errors.get(3)).contains(shouldBeEqualMessage("[false]", "[true]"));
assertThat(errors.get(4)).contains(shouldBeEqualMessage("0", "1"));
assertThat(errors.get(5)).contains(shouldBeEqualMessage("0x02", "0x03"));
assertThat(errors.get(6)).contains(shouldBeEqualMessage("[4]", "[5]"));
assertThat(errors.get(7)).contains(shouldBeEqualMessage("'A'", "'B'"));
assertThat(errors.get(8)).contains(shouldBeEqualMessage("'C'", "'D'"));
assertThat(errors.get(9)).contains(shouldBeEqualMessage("['E']", "['F']"));
assertThat(errors.get(10)).contains(shouldBeEqualMessage("\"a\"", "\"b\""));
assertThat(errors.get(11)).contains(shouldBeEqualMessage("java.lang.Object", "java.lang.String"));
assertThat(errors.get(12)).contains(shouldBeEqualMessage("1999-12-31T23:59:59.000 (java.util.Date)",
"2000-01-01T00:00:01.000 (java.util.Date)").formatted());
assertThat(errors.get(13)).contains(shouldBeEqualMessage("6.0", "7.0"));
assertThat(errors.get(14)).contains(shouldBeEqualMessage("8.0", "9.0"));
assertThat(errors.get(15)).contains(shouldBeEqualMessage("[10.0]", "[11.0]"));
assertThat(errors.get(16)).contains(shouldBeEqualMessage("File(a)", "File(b)"));
assertThat(errors.get(17)).contains(shouldBeEqualMessage("12.0f", "13.0f"));
assertThat(errors.get(18)).contains(shouldBeEqualMessage("14.0f", "15.0f"));
assertThat(errors.get(19)).contains(shouldBeEqualMessage("[16.0f]", "[17.0f]"));
assertThat(errors.get(20)).contains(format("%nInputStreams do not have same content:%n%n"
+ "Changed content at line 1:%n"
+ "expecting:%n"
+ " [\"B\"]%n"
+ "but was:%n"
+ " [\"A\"]%n"));
assertThat(errors.get(21)).contains(shouldBeEqualMessage("20", "21"));
assertThat(errors.get(22)).contains(shouldBeEqualMessage("22", "23"));
assertThat(errors.get(23)).contains(shouldBeEqualMessage("[24]", "[25]"));
assertThat(errors.get(24)).contains(shouldBeEqualMessage("[\"26\"]", "[\"27\"]"));
assertThat(errors.get(25)).contains("Expecting the iterator under test to be exhausted");
assertThat(errors.get(26)).contains(shouldBeEqualMessage("[\"30\"]", "[\"31\"]"));
assertThat(errors.get(27)).contains(shouldBeEqualMessage("32L", "33L"));
assertThat(errors.get(28)).contains(shouldBeEqualMessage("34L", "35L"));
assertThat(errors.get(29)).contains(shouldBeEqualMessage("[36L]", "[37L]"));
assertThat(errors.get(30)).contains(shouldBeEqualMessage("{\"38\"=\"39\"}", "{\"40\"=\"41\"}"));
assertThat(errors.get(31)).contains(shouldBeEqualMessage("42", "43"));
assertThat(errors.get(32)).contains(shouldBeEqualMessage("44", "45"));
assertThat(errors.get(33)).contains(shouldBeEqualMessage("[46]", "[47]"));
assertThat(errors.get(34)).contains(shouldBeEqualMessage("\"48\"", "\"49\""));
assertThat(errors.get(35)).contains(shouldBeEqualMessage("50", "51"));
assertThat(errors.get(36)).contains(shouldBeEqualMessage("[52]", "[53]"));
assertThat(errors.get(37)).contains(format("%nExpecting message to be:%n"
+ " \"NullPointerException message\"%n"
+ "but was:%n"
+ " \"IllegalArgumentException message\""));
assertThat(errors.get(38)).contains(shouldBeEqualMessage("Optional[not empty]", "\"empty\""));
assertThat(errors.get(39)).contains(shouldBeEqualMessage("OptionalInt[0]", "1"));
assertThat(errors.get(40)).contains(shouldBeEqualMessage("OptionalDouble[0.0]", "1.0"));
assertThat(errors.get(41)).contains(shouldBeEqualMessage("OptionalLong[0]", "1L"));
assertThat(errors.get(42)).contains(shouldBeEqualMessage("12:00", "13:00"));
assertThat(errors.get(43)).contains(shouldBeEqualMessage("12:00Z", "13:00Z"));
assertThat(errors.get(44)).contains(shouldBeEqualMessage(OffsetDateTime.MIN + " (java.time.OffsetDateTime)",
OffsetDateTime.MAX + " (java.time.OffsetDateTime)")
+ "%nwhen comparing values using '%s'".formatted(OffsetDateTimeByInstantComparator.getInstance()));
return;
}
fail("Should not reach here");
}
}
| AutoCloseableBDDSoftAssertionsTest |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/webapp/TestAMWebServicesTasks.java | {
"start": 3143,
"end": 3660
} | class ____ extends JerseyTestBase {
private static final Configuration CONF = new Configuration();
private static AppContext appContext;
@Override
protected Application configure() {
ResourceConfig config = new ResourceConfig();
config.register(new JerseyBinder());
config.register(AMWebServices.class);
config.register(GenericExceptionHandler.class);
config.register(new JettisonFeature()).register(JAXBContextResolver.class);
return config;
}
private static | TestAMWebServicesTasks |
java | apache__hadoop | hadoop-tools/hadoop-gridmix/src/main/java/org/apache/hadoop/mapred/gridmix/SubmitterUserResolver.java | {
"start": 1118,
"end": 1964
} | class ____ implements UserResolver {
public static final Logger LOG = LoggerFactory.getLogger(SubmitterUserResolver.class);
private UserGroupInformation ugi = null;
public SubmitterUserResolver() throws IOException {
LOG.info(" Current user resolver is SubmitterUserResolver ");
ugi = UserGroupInformation.getLoginUser();
}
public synchronized boolean setTargetUsers(URI userdesc, Configuration conf)
throws IOException {
return false;
}
public synchronized UserGroupInformation getTargetUgi(
UserGroupInformation ugi) {
return this.ugi;
}
/**
* {@inheritDoc}
* <p>
* Since {@link SubmitterUserResolver} returns the user name who is running
* gridmix, it doesn't need a target list of users.
*/
public boolean needsTargetUsersList() {
return false;
}
}
| SubmitterUserResolver |
java | apache__flink | flink-libraries/flink-cep/src/test/java/org/apache/flink/cep/NFASerializerUpgradeTest.java | {
"start": 4277,
"end": 4674
} | class ____
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<EventId> {
@Override
public TypeSerializer<EventId> createPriorSerializer() {
return EventId.EventIdSerializer.INSTANCE;
}
@Override
public EventId createTestData() {
return new EventId(42, 42L);
}
}
/**
* This | EventIdSerializerSetup |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/circular/CircularProducerTest.java | {
"start": 1218,
"end": 1758
} | class ____ {
@Produces
@Dependent
String producerMethod() {
return "foobar";
}
@Produces
@Dependent
@MyQualifier
String producerField = "quux";
final String value;
@Inject
MyBean(String foobar, @MyQualifier String quux) {
this.value = foobar + quux;
}
}
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
@ | MyBean |
java | micronaut-projects__micronaut-core | http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/textplain/TxtPlainBooleanTest.java | {
"start": 1685,
"end": 3055
} | class ____ {
public static final String SPEC_NAME = "TxtPlainBooleanTest";
private static final HttpResponseAssertion ASSERTION = HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.body(BodyAssertion.builder().body("true").equals())
.assertResponse(response -> {
assertTrue(response.getContentType().isPresent());
assertEquals(MediaType.TEXT_PLAIN_TYPE, response.getContentType().get());
}).build();
@Test
void txtBoolean() throws IOException {
asserts(SPEC_NAME,
HttpRequest.GET("/txt/boolean").accept(MediaType.TEXT_PLAIN),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, ASSERTION));
}
@Test
void txtBooleanMono() throws IOException {
asserts(SPEC_NAME,
HttpRequest.GET("/txt/boolean/mono").accept(MediaType.TEXT_PLAIN),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, ASSERTION));
}
@Test
void txtBooleanFlux() throws IOException {
asserts(SPEC_NAME,
HttpRequest.GET("/txt/boolean/flux").accept(MediaType.TEXT_PLAIN),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, ASSERTION));
}
@Controller("/txt")
@Requires(property = "spec.name", value = SPEC_NAME)
static | TxtPlainBooleanTest |
java | spring-projects__spring-framework | spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelAttributeMethodArgumentResolverTests.java | {
"start": 16620,
"end": 16938
} | class ____ {
@NotEmpty
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "ValidatedPojo [name=" + name + "]";
}
}
@SuppressWarnings("unused")
private static | ValidatedPojo |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/ThrowExceptionDefinition.java | {
"start": 3470,
"end": 3794
} | class ____ the exception to create using the message.
*
* @see #setMessage(String)
*/
public void setExceptionType(String exceptionType) {
this.exceptionType = exceptionType;
}
public Class<? extends Exception> getExceptionClass() {
return exceptionClass;
}
/**
* The | of |
java | elastic__elasticsearch | x-pack/plugin/eql/src/test/java/org/elasticsearch/xpack/eql/execution/assembler/SequenceSpecTests.java | {
"start": 7271,
"end": 11649
} | class ____ implements QueryClient {
@Override
public void query(QueryRequest r, ActionListener<SearchResponse> l) {
int ordinal = r.searchSource().terminateAfter();
if (ordinal != Integer.MAX_VALUE) {
r.searchSource().terminateAfter(Integer.MAX_VALUE);
}
Map<Integer, Tuple<String, String>> evs = ordinal != Integer.MAX_VALUE ? events.get(ordinal) : emptyMap();
EventsAsHits eah = new EventsAsHits(evs);
SearchHits searchHits = SearchHits.unpooled(
eah.hits.toArray(SearchHits.EMPTY),
new TotalHits(eah.hits.size(), Relation.EQUAL_TO),
0.0f
);
ActionListener.respondAndRelease(l, SearchResponseUtils.successfulResponse(searchHits));
}
@Override
public void fetchHits(Iterable<List<HitReference>> refs, ActionListener<List<List<SearchHit>>> listener) {
List<List<SearchHit>> searchHits = new ArrayList<>();
for (List<HitReference> ref : refs) {
List<SearchHit> hits = new ArrayList<>(ref.size());
for (HitReference hitRef : ref) {
hits.add(SearchHit.unpooled(-1, hitRef.id()));
}
searchHits.add(hits);
}
listener.onResponse(searchHits);
}
}
public SequenceSpecTests(String testName, int lineNumber, SeriesSpec spec) {
this.lineNumber = lineNumber;
this.events = spec.eventsPerCriterion;
this.matches = spec.matches;
this.allEvents = spec.allEvents;
this.hasKeys = spec.hasKeys;
this.keyExtractors = hasKeys ? singletonList(new KeyExtractor()) : emptyList();
this.tsExtractor = TimestampExtractor.INSTANCE;
this.tbExtractor = null;
this.implicitTbExtractor = ImplicitTbExtractor.INSTANCE;
}
@ParametersFactory(shuffle = false, argumentFormatting = PARAM_FORMATTING)
public static Iterable<Object[]> parameters() throws Exception {
return SeriesUtils.readSpec("/" + QUERIES_FILENAME);
}
public void test() throws Exception {
int stages = events.size();
List<SequenceCriterion> criteria = new ArrayList<>(stages);
// pass the items for each query through the Criterion
for (int i = 0; i < stages; i++) {
// set the index as size in the search source
criteria.add(new TestCriterion(i));
}
// convert the results through a test specific payload
SequenceMatcher matcher = new SequenceMatcher(
stages,
false,
TimeValue.MINUS_ONE,
null,
booleanArrayOf(stages, false),
NOOP_CIRCUIT_BREAKER
);
QueryClient testClient = new TestQueryClient();
TumblingWindow window = new TumblingWindow(
testClient,
criteria,
null,
matcher,
Collections.emptyList(),
randomBoolean(),
randomBoolean()
);
// finally make the assertion at the end of the listener
window.execute(ActionTestUtils.assertNoFailureListener(this::checkResults));
}
private void checkResults(Payload payload) {
List<Sequence> seq = Results.fromPayload(payload).sequences();
String prefix = "Line " + lineNumber + ":";
assertNotNull(prefix + "no matches found", seq);
assertEquals(prefix + "different sequences matched ", matches.size(), seq.size());
for (int i = 0; i < seq.size(); i++) {
Sequence s = seq.get(i);
List<String> match = matches.get(i);
List<String> returned = new ArrayList<>();
for (int j = 0; j < match.size(); j++) {
int key = Integer.parseInt(s.events().get(j).id());
returned.add(allEvents.get(key));
}
String keys = "";
String values = returned.toString();
if (hasKeys) {
keys = s.joinKeys().toString();
keys = keys.substring(0, keys.length() - 1);
keys += "|";
values = values.substring(1);
}
// remove [ ]
assertEquals(prefix, match.toString(), keys + values);
}
}
}
| TestQueryClient |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/Test3TypeBuilder.java | {
"start": 1067,
"end": 1472
} | class ____ implements TypeBuilder {
// it is smaller than the implements of TypeBuilder
@Override
public int getPriority() {
return 10;
}
@Override
public boolean accept(Class<?> clazz) {
return false;
}
@Override
public TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) {
return null;
}
}
| Test3TypeBuilder |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointMetaData.java | {
"start": 942,
"end": 2971
} | class ____ implements Serializable {
private static final long serialVersionUID = -2387652345781312442L;
/** The ID of the checkpoint. */
private final long checkpointId;
/** The timestamp of the checkpoint triggering. */
private final long timestamp;
/** The timestamp of the checkpoint receiving by this subtask. */
private final long receiveTimestamp;
public CheckpointMetaData(long checkpointId, long timestamp) {
this(checkpointId, timestamp, System.currentTimeMillis());
}
public CheckpointMetaData(long checkpointId, long timestamp, long receiveTimestamp) {
this.checkpointId = checkpointId;
this.timestamp = timestamp;
this.receiveTimestamp = receiveTimestamp;
}
public long getCheckpointId() {
return checkpointId;
}
public long getTimestamp() {
return timestamp;
}
public long getReceiveTimestamp() {
return receiveTimestamp;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CheckpointMetaData that = (CheckpointMetaData) o;
return (checkpointId == that.checkpointId)
&& (timestamp == that.timestamp)
&& (receiveTimestamp == that.receiveTimestamp);
}
@Override
public int hashCode() {
int result = (int) (checkpointId ^ (checkpointId >>> 32));
result = 31 * result + (int) (timestamp ^ (timestamp >>> 32));
result = 31 * result + (int) (receiveTimestamp ^ (receiveTimestamp >>> 32));
return result;
}
@Override
public String toString() {
return "CheckpointMetaData{"
+ "checkpointId="
+ checkpointId
+ ", receiveTimestamp="
+ receiveTimestamp
+ ", timestamp="
+ timestamp
+ '}';
}
}
| CheckpointMetaData |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/testFixtures/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointInfrastructureProvider.java | {
"start": 818,
"end": 987
} | interface ____ provide the web endpoint configuration for a target
* {@linkplain Infrastructure infrastructure}.
*
* @author Stephane Nicoll
* @since 4.0.0
*/
public | to |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/collection/bag/BagElementNullBasicTest.java | {
"start": 5387,
"end": 5721
} | class ____ {
@Id
@GeneratedValue
private int id;
@ElementCollection
@CollectionTable(name = "e_2_string", joinColumns = @JoinColumn(name = "e_id"))
@Column(name = "string_value", unique = false, nullable = true, insertable = true, updatable = true)
private List<String> list = new ArrayList<>();
}
}
| NullableElementsEntity |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/search/SearchAsyncActionTests.java | {
"start": 36835,
"end": 37420
} | class ____ extends SearchResponse {
final Set<ShardId> queried = new HashSet<>();
TestSearchResponse() {
super(
SearchHits.EMPTY_WITH_TOTAL_HITS,
null,
null,
false,
null,
null,
1,
null,
0,
0,
0,
0L,
ShardSearchFailure.EMPTY_ARRAY,
Clusters.EMPTY,
null
);
}
}
public static | TestSearchResponse |
java | apache__camel | components/camel-cm-sms/src/main/java/org/apache/camel/component/cm/exceptions/cmresponse/UnknownErrorException.java | {
"start": 964,
"end": 1068
} | class ____ extends CMResponseException {
public UnknownErrorException() {
}
}
| UnknownErrorException |
java | apache__kafka | metadata/src/main/java/org/apache/kafka/metadata/LeaderRecoveryState.java | {
"start": 871,
"end": 2306
} | enum ____ {
/**
* Represent that the election for the partition was either an ISR election or the
* leader recovered from an unclean leader election.
*/
RECOVERED((byte) 0),
/**
* Represent that the election for the partition was an unclean leader election and
* that the leader is recovering from it.
*/
RECOVERING((byte) 1);
/**
* A special value used to represent that the LeaderRecoveryState field of a
* PartitionChangeRecord didn't change.
*/
public static final byte NO_CHANGE = (byte) -1;
public static LeaderRecoveryState of(byte value) {
return optionalOf(value)
.orElseThrow(() -> new IllegalArgumentException(String.format("Value %s is not a valid leader recovery state", value)));
}
public static Optional<LeaderRecoveryState> optionalOf(byte value) {
if (value == RECOVERED.value()) {
return Optional.of(RECOVERED);
}
if (value == RECOVERING.value()) {
return Optional.of(RECOVERING);
}
return Optional.empty();
}
private final byte value;
LeaderRecoveryState(byte value) {
this.value = value;
}
public byte value() {
return value;
}
public LeaderRecoveryState changeTo(byte value) {
if (value == NO_CHANGE) {
return this;
}
return of(value);
}
}
| LeaderRecoveryState |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/ModuleTest.java | {
"start": 1024,
"end": 1395
} | class ____ implements Module {
@Override
public ObjectDeserializer createDeserializer(ParserConfig config, Class type) {
return MiscCodec.instance;
}
@Override
public ObjectSerializer createSerializer(SerializeConfig config, Class type) {
return MiscCodec.instance;
}
}
public static | MyModuel |
java | netty__netty | handler/src/main/java/io/netty/handler/ssl/JdkAlpnApplicationProtocolNegotiator.java | {
"start": 5675,
"end": 6213
} | class ____ extends AllocatorAwareSslEngineWrapperFactory {
@Override
public SSLEngine wrapSslEngine(SSLEngine engine, ByteBufAllocator alloc,
JdkApplicationProtocolNegotiator applicationNegotiator, boolean isServer) {
throw new RuntimeException("ALPN unsupported. Does your JDK version support it?"
+ " For Conscrypt, add the appropriate Conscrypt JAR to classpath and set the security provider.");
}
}
private static final | FailureWrapper |
java | apache__flink | flink-table/flink-table-api-java-bridge/src/main/java/org/apache/flink/table/api/bridge/java/StreamTableEnvironment.java | {
"start": 22264,
"end": 26549
} | class ____ {
* public String name;
* public Integer age;
*
* // default constructor for DataStream API
* public MyPojo() {}
*
* // fully assigning constructor for field order in Table API
* public MyPojo(String name, Integer age) {
* this.name = name;
* this.age = age;
* }
* }
*
* tableEnv.toDataStream(table, DataTypes.of(MyPojo.class));
* </pre>
*
* <p>Since the DataStream API does not support changelog processing natively, this method
* assumes append-only/insert-only semantics during the table-to-stream conversion. Updating
* tables are not supported by this method and will produce an exception.
*
* <p>Note that the type system of the table ecosystem is richer than the one of the DataStream
* API. The table runtime will make sure to properly serialize the output records to the first
* operator of the DataStream API. Afterwards, the {@link Types} semantics of the DataStream API
* need to be considered.
*
* <p>If the input table contains a single rowtime column, it will be propagated into a stream
* record's timestamp. Watermarks will be propagated as well.
*
* @param table The {@link Table} to convert. It must be insert-only.
* @param targetDataType The {@link DataType} that decides about the final external
* representation in {@link DataStream} records.
* @param <T> External record.
* @return The converted {@link DataStream}.
* @see #toDataStream(Table)
* @see #toChangelogStream(Table, Schema)
*/
<T> DataStream<T> toDataStream(Table table, AbstractDataType<?> targetDataType);
/**
* Converts the given {@link Table} into a {@link DataStream} of changelog entries.
*
* <p>Compared to {@link #toDataStream(Table)}, this method produces instances of {@link Row}
* and sets the {@link RowKind} flag that is contained in every record during runtime. The
* runtime behavior is similar to that of a {@link DynamicTableSink}.
*
* <p>This method can emit a changelog containing all kinds of changes (enumerated in {@link
* RowKind}) that the given updating table requires as the default {@link ChangelogMode}. Use
* {@link #toChangelogStream(Table, Schema, ChangelogMode)} to limit the kinds of changes (e.g.
* for upsert mode).
*
* <p>Note that the type system of the table ecosystem is richer than the one of the DataStream
* API. The table runtime will make sure to properly serialize the output records to the first
* operator of the DataStream API. Afterwards, the {@link Types} semantics of the DataStream API
* need to be considered.
*
* <p>If the input table contains a single rowtime column, it will be propagated into a stream
* record's timestamp. Watermarks will be propagated as well.
*
* @param table The {@link Table} to convert. It can be updating or insert-only.
* @return The converted changelog stream of {@link Row}.
*/
DataStream<Row> toChangelogStream(Table table);
/**
* Converts the given {@link Table} into a {@link DataStream} of changelog entries.
*
* <p>Compared to {@link #toDataStream(Table)}, this method produces instances of {@link Row}
* and sets the {@link RowKind} flag that is contained in every record during runtime. The
* runtime behavior is similar to that of a {@link DynamicTableSink}.
*
* <p>This method can emit a changelog containing all kinds of changes (enumerated in {@link
* RowKind}) that the given updating table requires as the default {@link ChangelogMode}. Use
* {@link #toChangelogStream(Table, Schema, ChangelogMode)} to limit the kinds of changes (e.g.
* for upsert mode).
*
* <p>The given {@link Schema} is used to configure the table runtime to convert columns and
* internal data structures to the desired representation. The following example shows how to
* convert a table column into a POJO type.
*
* <pre>
* // given a Table of (id BIGINT, payload ROW < name STRING , age INT >)
*
* public static | MyPojo |
java | playframework__playframework | dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/src/test/java/controllers/HomeControllerTest.java | {
"start": 840,
"end": 7437
} | class ____ extends WithApplication {
@Rule
public ExpectedException exceptionGrabber = ExpectedException.none();
@Test
public void testOnlyFormDataNoFiles() throws ExecutionException, InterruptedException, TimeoutException {
final Map<String, String[]> postParams = new HashMap<>();
postParams.put("key1", new String[]{"value1"});
Http.RequestBuilder request = new Http.RequestBuilder()
.method(POST)
.bodyMultipart(postParams, Collections.emptyList())
.uri("/multipart-form-data-no-files");
Result result = route(app, request);
String content = result.body().consumeData(mat).thenApply(bs -> bs.utf8String()).toCompletableFuture().get(5, TimeUnit.SECONDS);
assertEquals(OK, result.status());
assertEquals("Files: 0, Data: 1 [value1]", content);
}
@Test
public void testStringFilePart() throws ExecutionException, InterruptedException, TimeoutException {
String content = "Twas brillig and the slithy Toves...";
testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", content,
data -> Optional.of(ByteString.fromString(data)))));
}
@Test
public void testStringFilePartToRefToBytesDefined() throws ExecutionException, InterruptedException, TimeoutException {
exceptionGrabber.expect(RuntimeException.class);
exceptionGrabber.expectMessage("To be able to convert this FilePart's ref to bytes you need to define refToBytes of FilePart[java.lang.String]");
String content = "Twas brillig and the slithy Toves...";
testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", content)));
}
@Test
public void testJavaTemporaryFile() throws IOException, ExecutionException, InterruptedException, TimeoutException {
Files.TemporaryFile tempFile = Files.singletonTemporaryFileCreator().create("temp", "txt");
write(tempFile.path(), "Twas brillig and the slithy Toves...".getBytes());
testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", tempFile)));
}
@Test
public void testScalaTemporaryFile() throws IOException, ExecutionException, InterruptedException, TimeoutException {
play.api.libs.Files.TemporaryFile tempFile = play.api.libs.Files.SingletonTemporaryFileCreator$.MODULE$.create("temp", "txt");
write(tempFile.path(), "Twas brillig and the slithy Toves...".getBytes());
testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", tempFile)));
}
@Test
public void testFile() throws IOException, ExecutionException, InterruptedException, TimeoutException {
play.api.libs.Files.TemporaryFile tempFile = play.api.libs.Files.SingletonTemporaryFileCreator$.MODULE$.create("temp", "txt");
write(tempFile.path(), "Twas brillig and the slithy Toves...".getBytes());
testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", tempFile.file())));
}
@Test
public void testPath() throws IOException, ExecutionException, InterruptedException, TimeoutException {
play.api.libs.Files.TemporaryFile tempFile = play.api.libs.Files.SingletonTemporaryFileCreator$.MODULE$.create("temp", "txt");
write(tempFile.path(), "Twas brillig and the slithy Toves...".getBytes());
testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", tempFile.path())));
}
@Test
public void testTmpFileExists() throws IOException, ExecutionException, InterruptedException, TimeoutException {
play.api.libs.Files.TemporaryFile tempFile = play.api.libs.Files.SingletonTemporaryFileCreator$.MODULE$.create("temp", "txt");
write(tempFile.path(), "Hello".getBytes());
Http.RequestBuilder request = new Http.RequestBuilder()
.method(POST)
.bodyMultipart(Map.of(), List.of(new Http.MultipartFormData.FilePart<>("file", "file.txt", "text/plain", tempFile.path())))
.uri("/multipart-form-data-tmpfileexists");
Result result = route(app, request);
String content = result.body().consumeData(mat).thenApply(bs -> bs.utf8String()).toCompletableFuture().get(5, TimeUnit.SECONDS);
assertEquals(OK, result.status());
assertEquals("exists", content);
// Now let's check if the tmp file still gets removed when garbage collection takes place
request = new Http.RequestBuilder()
.method(GET)
.uri("/check-tmp-file-still-exists");
result = route(app, request);
content = result.body().consumeData(mat).thenApply(bs -> bs.utf8String()).toCompletableFuture().get(5, TimeUnit.SECONDS);
assertEquals(OK, result.status());
assertEquals("exists", content);
request = new Http.RequestBuilder()
.method(GET)
.uri("/gc");
result = route(app, request);
assertEquals(OK, result.status());
request = new Http.RequestBuilder()
.method(GET)
.uri("/check-tmp-file-still-exists");
result = route(app, request);
content = result.body().consumeData(mat).thenApply(bs -> bs.utf8String()).toCompletableFuture().get(5, TimeUnit.SECONDS);
assertEquals(OK, result.status());
assertEquals("not exists", content);
}
private void testTemporaryFile(final List<Http.MultipartFormData.FilePart> files) throws ExecutionException, InterruptedException, TimeoutException {
final Map<String, String[]> data = new HashMap<>();
data.put("author", new String[]{"Lewis Carrol"});
Http.RequestBuilder request = new Http.RequestBuilder()
.method(POST)
.bodyMultipart(data, files)
.uri("/multipart-form-data");
Result result = route(app, request);
String content = result.body().consumeData(mat).thenApply(bs -> bs.utf8String()).toCompletableFuture().get(5, TimeUnit.SECONDS);
assertEquals(OK, result.status());
assertEquals("author: Lewis Carrol\n"
+ "filename: jabberwocky.txt\n"
+ "contentType: text/plain\n"
+ "contents: Twas brillig and the slithy Toves...\n",
content);
}
}
| HomeControllerTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/join/AttributeJoinWithTablePerClassInheritanceTest.java | {
"start": 9506,
"end": 9704
} | class ____ extends ChildEntityA {
public SubChildEntityA1() {
}
public SubChildEntityA1(Integer id) {
super( id );
}
}
@Entity( name = "SubChildEntityA2" )
public static | SubChildEntityA1 |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/protocol/RatioDecodeBufferPolicy.java | {
"start": 567,
"end": 1870
} | class ____ implements DecodeBufferPolicy {
private final float discardReadBytesRatio;
/**
* Create a new {@link RatioDecodeBufferPolicy} using {@code bufferUsageRatio}.
*
* @param bufferUsageRatio the buffer usage ratio. Must be between {@code 0} and {@code 2^31-1}, typically a value between 1
* and 10 representing 50% to 90%.
*
*/
public RatioDecodeBufferPolicy(float bufferUsageRatio) {
LettuceAssert.isTrue(bufferUsageRatio > 0 && bufferUsageRatio < Integer.MAX_VALUE,
"BufferUsageRatio must be greater than 0");
this.discardReadBytesRatio = bufferUsageRatio / (bufferUsageRatio + 1);
}
@Override
public void afterPartialDecode(ByteBuf buffer) {
discardReadBytesIfNecessary(buffer);
}
@Override
public void afterDecoding(ByteBuf buffer) {
discardReadBytesIfNecessary(buffer);
}
@Override
public void afterCommandDecoded(ByteBuf buffer) {
discardReadBytesIfNecessary(buffer);
}
private void discardReadBytesIfNecessary(ByteBuf buffer) {
float usedRatio = (float) buffer.readerIndex() / buffer.capacity();
if (usedRatio >= discardReadBytesRatio) {
buffer.discardReadBytes();
}
}
}
| RatioDecodeBufferPolicy |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/VerificationException.java | {
"start": 436,
"end": 919
} | class ____ extends EsqlClientException {
public VerificationException(String message, Object... args) {
super(message, args);
}
public VerificationException(Collection<Failure> sources) {
super(Failure.failMessage(sources));
}
public VerificationException(Failures failures) {
super(failures.toString());
}
public VerificationException(String message, Throwable cause) {
super(message, cause);
}
}
| VerificationException |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/FluxSwitchMapNoPrefetch.java | {
"start": 8812,
"end": 27829
} | class ____<T, R> implements InnerConsumer<R> {
final @Nullable StateLogger logger;
final SwitchMapMain<T, R> parent;
final CoreSubscriber<? super R> actual;
final int index;
@SuppressWarnings("NotNullFieldNotInitialized") // s initialized in onSubscribe
Subscription s;
long produced;
long requested;
boolean done;
@SuppressWarnings("NotNullFieldNotInitialized") // set when switching
T nextElement;
@SuppressWarnings("NotNullFieldNotInitialized") // set when switching
SwitchMapInner<T, R> nextInner;
SwitchMapInner(SwitchMapMain<T, R> parent, CoreSubscriber<? super R> actual, int index, @Nullable StateLogger logger) {
this.parent = parent;
this.actual = actual;
this.index = index;
this.logger = logger;
}
@Override
public Context currentContext() {
return parent.currentContext();
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.CANCELLED) return isCancelledByParent();
if (key == Attr.PARENT) return this.parent;
if (key == Attr.ACTUAL) return this.actual;
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return null;
}
@Override
public void onSubscribe(Subscription s) {
if (Operators.validate(this.s, s)) {
this.s = s;
final int expectedIndex = this.index;
final SwitchMapMain<T, R> parent = this.parent;
final long state = setInnerSubscribed(parent, expectedIndex);
if (state == TERMINATED) {
s.cancel();
return;
}
final int actualIndex = index(state);
if (expectedIndex != actualIndex) {
s.cancel();
parent.subscribeInner(this.nextElement, this.nextInner, actualIndex);
return;
}
if (hasRequest(state) > 0) {
long requested = parent.requested;
this.requested = requested;
s.request(requested);
}
}
}
@Override
public void onNext(R t) {
if (this.done) {
Operators.onNextDropped(t, this.actual.currentContext());
return;
}
final SwitchMapMain<T, R> parent = this.parent;
final Subscription s = this.s;
final int expectedIndex = this.index;
long requested = this.requested;
long state = setWip(parent, expectedIndex);
if (state == TERMINATED) {
Operators.onDiscard(t, this.actual.currentContext());
return;
}
int actualIndex = index(state);
if (actualIndex != expectedIndex) {
Operators.onDiscard(t, this.actual.currentContext());
return;
}
this.actual.onNext(t);
long produced = 0;
boolean isDemandFulfilled = false;
int expectedHasRequest = hasRequest(state);
if (requested != Long.MAX_VALUE) {
produced = this.produced + 1;
this.produced = produced;
if (expectedHasRequest > 1) {
long actualRequested = parent.requested;
long toRequestInAddition = actualRequested - requested;
if (toRequestInAddition > 0) {
requested = actualRequested;
this.requested = requested;
if (requested == Long.MAX_VALUE) {
// we need to reset stats if unbounded requested
this.produced = produced = 0;
s.request(Long.MAX_VALUE);
}
else {
s.request(toRequestInAddition);
}
}
}
isDemandFulfilled = produced == requested;
if (isDemandFulfilled) {
this.produced = 0;
requested = SwitchMapMain.REQUESTED.addAndGet(parent, -produced);
this.requested = requested;
produced = 0;
isDemandFulfilled = requested == 0;
if (!isDemandFulfilled) {
s.request(requested);
}
}
}
for (;;) {
state = unsetWip(parent, expectedIndex, isDemandFulfilled, expectedHasRequest);
if (state == TERMINATED) {
return;
}
actualIndex = index(state);
if (expectedIndex != actualIndex) {
if (produced > 0) {
this.produced = 0;
this.requested = 0;
SwitchMapMain.REQUESTED.addAndGet(parent, -produced);
}
parent.subscribeInner(this.nextElement, this.nextInner, actualIndex);
return;
}
int actualHasRequest = hasRequest(state);
if (isDemandFulfilled && expectedHasRequest < actualHasRequest) {
expectedHasRequest = actualHasRequest;
long currentRequest = parent.requested;
long toRequestInAddition = currentRequest - requested;
if (toRequestInAddition > 0) {
requested = currentRequest;
this.requested = requested;
isDemandFulfilled = false;
s.request(requested == Long.MAX_VALUE ? Long.MAX_VALUE : toRequestInAddition);
}
continue;
}
return;
}
}
@Override
public void onError(Throwable t) {
if (this.done) {
Operators.onErrorDropped(t, this.actual.currentContext());
return;
}
this.done = true;
final SwitchMapMain<T, R> parent = this.parent;
// ensures that racing on setting error will pass smoothly
if (!Exceptions.addThrowable(SwitchMapMain.THROWABLE, parent, t)) {
Operators.onErrorDropped(t, this.actual.currentContext());
return;
}
final long state = setTerminated(parent);
if (state == TERMINATED) {
return;
}
if (!hasMainCompleted(state)) {
parent.s.cancel();
}
//noinspection ConstantConditions
this.actual.onError(Exceptions.terminate(SwitchMapMain.THROWABLE, parent));
}
@Override
public void onComplete() {
if (this.done) {
return;
}
this.done = true;
final SwitchMapMain<T, R> parent = this.parent;
final int expectedIndex = this.index;
long state = setWip(parent, expectedIndex);
if (state == TERMINATED) {
return;
}
int actualIndex = index(state);
if (actualIndex != expectedIndex) {
return;
}
final long produced = this.produced;
if (produced > 0) {
this.produced = 0;
this.requested = 0;
SwitchMapMain.REQUESTED.addAndGet(parent, -produced);
}
if (hasMainCompleted(state)) {
this.actual.onComplete();
return;
}
state = setInnerCompleted(parent);
if (state == TERMINATED) {
return;
}
actualIndex = index(state);
if (expectedIndex != actualIndex) {
parent.subscribeInner(this.nextElement, this.nextInner, actualIndex);
} else if (hasMainCompleted(state)) {
this.actual.onComplete();
}
}
void request(long n) {
long requested = this.requested;
this.requested = Operators.addCap(requested, n);
this.s.request(n);
}
boolean isCancelledByParent() {
long state = parent.state;
return (this.index != index(state) && !this.done) || (!parent.done && state == TERMINATED);
}
void cancelFromParent() {
this.s.cancel();
}
@Override
public String toString() {
return new StringJoiner(", ",
SwitchMapInner.class.getSimpleName() + "[",
"]").add("index=" + index)
.toString();
}
}
static int INDEX_OFFSET = 32;
static int HAS_REQUEST_OFFSET = 4;
static long TERMINATED =
0b11111111111111111111111111111111_1111111111111111111111111111_1_1_1_1L;
static long INNER_WIP_MASK =
0b00000000000000000000000000000000_0000000000000000000000000000_0_0_0_1L;
static long INNER_SUBSCRIBED_MASK =
0b00000000000000000000000000000000_0000000000000000000000000000_0_0_1_0L;
static long INNER_COMPLETED_MASK =
0b00000000000000000000000000000000_0000000000000000000000000000_0_1_0_0L;
static long COMPLETED_MASK =
0b00000000000000000000000000000000_0000000000000000000000000000_1_0_0_0L;
static long HAS_REQUEST_MASK =
0b00000000000000000000000000000000_1111111111111111111111111111_0_0_0_0L;
static int MAX_HAS_REQUEST = 0b0000_1111111111111111111111111111;
/**
* Atomically set state as terminated
*
* @return previous state
*/
static long setTerminated(SwitchMapMain<?, ?> instance) {
for (;;) {
final long state = instance.state;
// do nothing if stream is terminated
if (state == TERMINATED) {
return TERMINATED;
}
if (SwitchMapMain.STATE.compareAndSet(instance, state, TERMINATED)) {
if (instance.logger != null) {
instance.logger.log(instance.toString(), "std", state, TERMINATED);
}
return state;
}
}
}
/**
* Atomically set main completed flag.
*
* The flag will not be set if the current state is {@link #TERMINATED}
*
* @return previous state
*/
static long setMainCompleted(SwitchMapMain<?, ?> instance) {
for (; ; ) {
final long state = instance.state;
// do nothing if stream is terminated
if (state == TERMINATED) {
return TERMINATED;
}
if ((state & COMPLETED_MASK) == COMPLETED_MASK) {
return state;
}
final long nextState = state | COMPLETED_MASK;
if (SwitchMapMain.STATE.compareAndSet(instance, state, nextState)) {
if (instance.logger != null) {
instance.logger.log(instance.toString(), "smc", state, nextState);
}
return state;
}
}
}
/**
* Atomically add increment hasRequest value to indicate that we added capacity to
* {@link SwitchMapMain#requested}
*
* <p>
* Note, If the given {@code previousRequested} param value is greater than zero it
* works as an indicator that in some scenarios prevents setting HasRequest to 1.
* Due to racing nature, the {@link SwitchMapMain#requested} may be incremented but
* the following addRequest may be delayed. That will lead that Inner may
* read the new value and request more data from the inner upstream. In turn, the
* delay may be that big that inner may fulfill new demand and set hasRequest to 0
* faster that addRequest happens and leave {@link SwitchMapMain#requested} at
* zero as well. Thus, we use previousRequested to check if inner was requested,
* and if it was, we assume the explained case happened and newly added demand was
* already fulfilled
* </p>
*
* @param previousRequested received from {@link Operators#addCap} method.
* @return next state
*/
static long addRequest(SwitchMapMain<?, ?> instance, long previousRequested) {
for (;;) {
long state = instance.state;
// do nothing if stream is terminated
if (state == TERMINATED) {
return TERMINATED;
}
final int hasRequest = hasRequest(state);
// if the current hasRequest is zero and previousRequested is greater than
// zero, it means that Inner was faster then this operation and has already
// fulfilled the demand. In that case we do not have to increment
// hasRequest and just need to return
if (hasRequest == 0 && previousRequested > 0) {
return state;
}
final long nextState = state(index(state), // keep index as is
isWip(state), // keep wip flag as is
hasRequest + 1, // increment hasRequest by 1
isInnerSubscribed(state), // keep inner subscribed flag as is
hasMainCompleted(state), // keep main completed flag as is
hasInnerCompleted(state)); // keep inner completed flag as is
if (SwitchMapMain.STATE.compareAndSet(instance, state, nextState)) {
if (instance.logger != null) {
instance.logger.log(instance.toString(), "adr", state, nextState);
}
return nextState;
}
}
}
/**
* Atomically increment the index of the active inner subscriber.
*
* The index will not be changed if the current state is {@link #TERMINATED}
*
* @return previous state
*/
static long incrementIndex(SwitchMapMain<?, ?> instance) {
long state = instance.state;
// do nothing if stream is terminated
if (state == TERMINATED) {
return TERMINATED;
}
// generate next index once. Main#OnNext will never race with another Main#OnNext. Also,
// this method is only called from Main#Onnext
int nextIndex = nextIndex(state);
for (; ; ) {
final long nextState = state(nextIndex, // set actual index to the next index
isWip(state), // keep WIP flag unchanged
hasRequest(state), // keep requested as is
false, // unset inner subscribed flag
false, // main completed flag can not be set at this stage
false);// set inner completed to false since another inner comes in
if (SwitchMapMain.STATE.compareAndSet(instance, state, nextState)) {
if (instance.logger != null) {
instance.logger.log(instance.toString(), "ini", state, nextState);
}
return state;
}
state = instance.state;
// do nothing if stream is terminated
if (state == TERMINATED) {
return TERMINATED;
}
}
}
/**
* Atomically set a bit on the current state indicating that current inner has
* received a subscription.
*
* If the index has changed during the subscription or stream was cancelled, the bit
* will not bit set
*
* @return previous state
*/
static long setInnerSubscribed(SwitchMapMain<?, ?> instance, int expectedIndex) {
for (;;) {
final long state = instance.state;
// do nothing if stream is terminated
if (state == TERMINATED) {
return TERMINATED;
}
int actualIndex = index(state);
// do nothing if index has changed before Subscription was received
if (expectedIndex != actualIndex) {
return state;
}
final long nextState = state(expectedIndex, // keep expected index
false, // wip assumed to be false
hasRequest(state), // keep existing request state
true, // set inner subscribed bit
hasMainCompleted(state), // keep main completed flag as is
false);// inner can not be completed at this phase
if (SwitchMapMain.STATE.compareAndSet(instance,
state, nextState)) {
if (instance.logger != null) {
instance.logger.log(instance.toString(), "sns", state, nextState);
}
return state;
}
}
}
/**
* Atomically set WIP flag to indicate that we do some work from Inner#OnNext or
* Inner#OnComplete.
*
* If the current state is {@link #TERMINATED} or the index is
* one equals to expected then the flag will not be set
*
* @return previous state
*/
static long setWip(SwitchMapMain<?, ?> instance, int expectedIndex) {
for (;;) {
final long state = instance.state;
// do nothing if stream is terminated
if (state == TERMINATED) {
return TERMINATED;
}
int actualIndex = index(state);
// do nothing if index has changed before Subscription was received
if (expectedIndex != actualIndex) {
return state;
}
final long nextState = state(expectedIndex, // keep expected index
true, // set wip bit
hasRequest(state), // keep request as is
true, // assumed inner subscribed if index has not changed
hasMainCompleted(state), // keep main completed flag as is
false);// inner can not be completed at this phase
if (SwitchMapMain.STATE.compareAndSet(instance, state, nextState)) {
if (instance.logger != null) {
instance.logger.log(instance.toString(), "swp", state, nextState);
}
return state;
}
}
}
/**
* Atomically unset WIP flag to indicate that we have done the work from
* Inner#OnNext
*
* If the current state is {@link #TERMINATED} or the index is
* one equals to expected then the flag will not be set
*
* @return previous state
*/
static long unsetWip(SwitchMapMain<?, ?> instance,
int expectedIndex,
boolean isDemandFulfilled,
int expectedRequest) {
for (; ; ) {
final long state = instance.state;
// do nothing if stream is terminated
if (state == TERMINATED) {
return TERMINATED;
}
final int actualIndex = index(state);
final int actualRequest = hasRequest(state);
final boolean sameIndex = expectedIndex == actualIndex;
// if during onNext we fulfilled the requested demand and index has not
// changed and it is observed that downstream requested more demand, we
// have to repeat and see of we can request more from the inner upstream.
// We dont have to chang WIP if we have isDemandFulfilled set to true
if (isDemandFulfilled && expectedRequest < actualRequest && sameIndex) {
return state;
}
final long nextState = state(
actualIndex,// set actual index; assumed index may change and if we have done with the work we have to unset WIP flag
false,// unset wip flag
isDemandFulfilled && expectedRequest == actualRequest ? 0 : actualRequest,// set hasRequest to 0 if we know that demand was fulfilled an expectedRequest is equal to the actual one (so it has not changed)
isInnerSubscribed(state),// keep inner state unchanged; if index has changed the flag is unset, otherwise it is set
hasMainCompleted(state),// keep main completed flag as it is
false); // this flag is always unset in this method since we do call from Inner#OnNext
if (SwitchMapMain.STATE.compareAndSet(instance, state, nextState)) {
if (instance.logger != null) {
instance.logger.log(instance.toString(), "uwp", state, nextState);
}
return state;
}
}
}
/**
* Atomically set the inner completed flag.
*
* The flag will not be set if the current state is {@link #TERMINATED}
*
* @return previous state
*/
static long setInnerCompleted(SwitchMapMain<?, ?> instance) {
for (; ; ) {
final long state = instance.state;
// do nothing if stream is terminated
if (state == TERMINATED) {
return TERMINATED;
}
final boolean isInnerSubscribed = isInnerSubscribed(state);
final long nextState = state(index(state), // keep the index unchanged
false, // unset WIP flag
hasRequest(state), // keep hasRequest flag as is
isInnerSubscribed, // keep inner subscribed flag as is
hasMainCompleted(state), // keep main completed flag as is
isInnerSubscribed); // if index has changed then inner subscribed remains set, thus we are safe to set inner completed flag
if (SwitchMapMain.STATE.compareAndSet(instance, state, nextState)) {
if (instance.logger != null) {
instance.logger.log(instance.toString(), "sic", state, nextState);
}
return state;
}
}
}
/**
* Generic method to encode state from the given params into a long value
*
* @return encoded state
*/
static long state(int index, boolean wip, int hasRequest, boolean innerSubscribed,
boolean mainCompleted, boolean innerCompleted) {
return ((long) index << INDEX_OFFSET)
| (wip ? INNER_WIP_MASK : 0)
| ((long) Math.max(Math.min(hasRequest, MAX_HAS_REQUEST), 0) << HAS_REQUEST_OFFSET)
| (innerSubscribed ? INNER_SUBSCRIBED_MASK : 0)
| (mainCompleted ? COMPLETED_MASK : 0)
| (innerCompleted ? INNER_COMPLETED_MASK : 0);
}
static boolean isInnerSubscribed(long state) {
return (state & INNER_SUBSCRIBED_MASK) == INNER_SUBSCRIBED_MASK;
}
static boolean hasMainCompleted(long state) {
return (state & COMPLETED_MASK) == COMPLETED_MASK;
}
static boolean hasInnerCompleted(long state) {
return (state & INNER_COMPLETED_MASK) == INNER_COMPLETED_MASK;
}
static int hasRequest(long state) {
return (int) (state & HAS_REQUEST_MASK) >> HAS_REQUEST_OFFSET;
}
static int index(long state) {
return (int) (state >>> INDEX_OFFSET);
}
static int nextIndex(long state) {
return ((int) (state >>> INDEX_OFFSET)) + 1;
}
static boolean isWip(long state) {
return (state & INNER_WIP_MASK) == INNER_WIP_MASK;
}
}
| SwitchMapInner |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/nestedbeans/House.java | {
"start": 226,
"end": 1755
} | class ____ {
private String name;
private int year;
private Roof roof;
public House() {
}
public House(String name, int year, Roof roof) {
this.name = name;
this.year = year;
this.roof = roof;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public Roof getRoof() {
return roof;
}
public void setRoof(Roof roof) {
this.roof = roof;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
House house = (House) o;
if ( year != house.year ) {
return false;
}
if ( !Objects.equals( name, house.name ) ) {
return false;
}
return Objects.equals( roof, house.roof );
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + year;
result = 31 * result + ( roof != null ? roof.hashCode() : 0 );
return result;
}
@Override
public String toString() {
return "House{" +
"name='" + name + '\'' +
", year=" + year +
", roof=" + roof +
'}';
}
}
| House |
java | elastic__elasticsearch | libs/x-content/src/main/java/org/elasticsearch/xcontent/CopyingXContentParser.java | {
"start": 783,
"end": 1713
} | class ____ extends FilterXContentParserWrapper {
private final XContentBuilder builder;
public CopyingXContentParser(XContentParser delegate) throws IOException {
super(delegate);
this.builder = XContentBuilder.builder(delegate.contentType().xContent());
switch (delegate.currentToken()) {
case START_OBJECT -> builder.startObject();
case START_ARRAY -> builder.startArray();
default -> throw new IllegalArgumentException(
"can only copy parsers pointed to START_OBJECT or START_ARRAY but found: " + delegate.currentToken()
);
}
}
@Override
public Token nextToken() throws IOException {
XContentParser.Token next = delegate().nextToken();
builder.copyCurrentEvent(delegate());
return next;
}
public XContentBuilder getBuilder() {
return builder;
}
}
| CopyingXContentParser |
java | spring-projects__spring-framework | spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateMultiEntityManagerFactoryIntegrationTests.java | {
"start": 1273,
"end": 2562
} | class ____ extends AbstractContainerEntityManagerFactoryIntegrationTests {
@Autowired
private EntityManagerFactory entityManagerFactory2;
@Override
protected String[] getConfigLocations() {
return new String[] {"/org/springframework/orm/jpa/hibernate/hibernate-manager-multi.xml",
"/org/springframework/orm/jpa/memdb.xml"};
}
@Override
@Test
protected void testEntityManagerFactoryImplementsEntityManagerFactoryInfo() {
boolean condition = this.entityManagerFactory instanceof EntityManagerFactoryInfo;
assertThat(condition).as("Must have introduced config interface").isTrue();
EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) this.entityManagerFactory;
assertThat(emfi.getPersistenceUnitName()).isEqualTo("Drivers");
assertThat(emfi.getPersistenceUnitInfo()).as("PersistenceUnitInfo must be available").isNotNull();
assertThat(emfi.getNativeEntityManagerFactory()).as("Raw EntityManagerFactory must be available").isNotNull();
}
@Test
void testEntityManagerFactory2() {
EntityManager em = this.entityManagerFactory2.createEntityManager();
try {
assertThatIllegalArgumentException().isThrownBy(() ->
em.createQuery("select tb from TestBean"));
}
finally {
em.close();
}
}
}
| HibernateMultiEntityManagerFactoryIntegrationTests |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java | {
"start": 30155,
"end": 31355
} | class ____ {
public static @Nullable Locale getJstlLocale(HttpServletRequest request, @Nullable ServletContext servletContext) {
Object localeObject = Config.get(request, Config.FMT_LOCALE);
if (localeObject == null) {
HttpSession session = request.getSession(false);
if (session != null) {
localeObject = Config.get(session, Config.FMT_LOCALE);
}
if (localeObject == null && servletContext != null) {
localeObject = Config.get(servletContext, Config.FMT_LOCALE);
}
}
return (localeObject instanceof Locale locale ? locale : null);
}
public static @Nullable TimeZone getJstlTimeZone(HttpServletRequest request, @Nullable ServletContext servletContext) {
Object timeZoneObject = Config.get(request, Config.FMT_TIME_ZONE);
if (timeZoneObject == null) {
HttpSession session = request.getSession(false);
if (session != null) {
timeZoneObject = Config.get(session, Config.FMT_TIME_ZONE);
}
if (timeZoneObject == null && servletContext != null) {
timeZoneObject = Config.get(servletContext, Config.FMT_TIME_ZONE);
}
}
return (timeZoneObject instanceof TimeZone timeZone ? timeZone : null);
}
}
}
| JstlLocaleResolver |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/TypeMappedAnnotationTests.java | {
"start": 1189,
"end": 6654
} | class ____ {
@Test
void mappingWhenMirroredReturnsMirroredValues() {
testExplicitMirror(WithExplicitMirrorA.class);
testExplicitMirror(WithExplicitMirrorB.class);
}
private void testExplicitMirror(Class<?> annotatedClass) {
TypeMappedAnnotation<ExplicitMirror> annotation = getTypeMappedAnnotation(
annotatedClass, ExplicitMirror.class);
assertThat(annotation.getString("a")).isEqualTo("test");
assertThat(annotation.getString("b")).isEqualTo("test");
}
@Test
void mappingExplicitAliasToMetaAnnotationReturnsMappedValues() {
TypeMappedAnnotation<?> annotation = getTypeMappedAnnotation(
WithExplicitAliasToMetaAnnotation.class,
ExplicitAliasToMetaAnnotation.class,
ExplicitAliasMetaAnnotationTarget.class);
assertThat(annotation.getString("aliased")).isEqualTo("aliased");
assertThat(annotation.getString("nonAliased")).isEqualTo("nonAliased");
}
@Test
void mappingConventionAliasToMetaAnnotationReturnsMappedValues() {
TypeMappedAnnotation<?> annotation = getTypeMappedAnnotation(
WithConventionAliasToMetaAnnotation.class,
ConventionAliasToMetaAnnotation.class);
assertThat(annotation.getString("value")).isEqualTo("value");
assertThat(annotation.getString("convention")).isEqualTo("convention");
annotation = getTypeMappedAnnotation(
WithConventionAliasToMetaAnnotation.class,
ConventionAliasToMetaAnnotation.class,
ConventionAliasMetaAnnotationTarget.class);
assertThat(annotation.getString("value")).isEmpty();
// Convention-based annotation attribute overrides are no longer supported as of
// Spring Framework 7.0. Otherwise, we would expect "convention".
assertThat(annotation.getString("convention")).isEmpty();
}
@Test
void adaptFromEmptyArrayToAnyComponentType() {
AttributeMethods methods = AttributeMethods.forAnnotationType(ArrayTypes.class);
Map<String, Object> attributes = new HashMap<>();
for (int i = 0; i < methods.size(); i++) {
attributes.put(methods.get(i).getName(), new Object[] {});
}
MergedAnnotation<ArrayTypes> annotation = TypeMappedAnnotation.of(null, null,
ArrayTypes.class, attributes);
assertThat(annotation.getValue("stringValue")).contains(new String[] {});
assertThat(annotation.getValue("byteValue")).contains(new byte[] {});
assertThat(annotation.getValue("shortValue")).contains(new short[] {});
assertThat(annotation.getValue("intValue")).contains(new int[] {});
assertThat(annotation.getValue("longValue")).contains(new long[] {});
assertThat(annotation.getValue("booleanValue")).contains(new boolean[] {});
assertThat(annotation.getValue("charValue")).contains(new char[] {});
assertThat(annotation.getValue("doubleValue")).contains(new double[] {});
assertThat(annotation.getValue("floatValue")).contains(new float[] {});
assertThat(annotation.getValue("classValue")).contains(new Class<?>[] {});
assertThat(annotation.getValue("annotationValue")).contains(new MergedAnnotation<?>[] {});
assertThat(annotation.getValue("enumValue")).contains(new ExampleEnum[] {});
}
@Test
void adaptFromNestedMergedAnnotation() {
MergedAnnotation<Nested> nested = MergedAnnotation.of(Nested.class);
MergedAnnotation<?> annotation = TypeMappedAnnotation.of(null, null,
NestedContainer.class, Collections.singletonMap("value", nested));
assertThat(annotation.getAnnotation("value", Nested.class)).isSameAs(nested);
}
@Test
void adaptFromStringToClass() {
MergedAnnotation<?> annotation = TypeMappedAnnotation.of(null, null,
ClassAttributes.class,
Collections.singletonMap("classValue", InputStream.class.getName()));
assertThat(annotation.getString("classValue")).isEqualTo(InputStream.class.getName());
assertThat(annotation.getClass("classValue")).isEqualTo(InputStream.class);
}
@Test
void adaptFromStringArrayToClassArray() {
MergedAnnotation<?> annotation = TypeMappedAnnotation.of(null, null, ClassAttributes.class,
Collections.singletonMap("classArrayValue", new String[] { InputStream.class.getName() }));
assertThat(annotation.getStringArray("classArrayValue")).containsExactly(InputStream.class.getName());
assertThat(annotation.getClassArray("classArrayValue")).containsExactly(InputStream.class);
}
private <A extends Annotation> TypeMappedAnnotation<A> getTypeMappedAnnotation(
Class<?> source, Class<A> annotationType) {
return getTypeMappedAnnotation(source, annotationType, annotationType);
}
private <A extends Annotation> TypeMappedAnnotation<A> getTypeMappedAnnotation(
Class<?> source, Class<? extends Annotation> rootAnnotationType,
Class<A> annotationType) {
Annotation rootAnnotation = source.getAnnotation(rootAnnotationType);
AnnotationTypeMapping mapping = getMapping(rootAnnotation, annotationType);
return TypeMappedAnnotation.createIfPossible(mapping, source, rootAnnotation, 0, IntrospectionFailureLogger.INFO);
}
private AnnotationTypeMapping getMapping(Annotation annotation,
Class<? extends Annotation> mappedAnnotationType) {
AnnotationTypeMappings mappings = AnnotationTypeMappings.forAnnotationType(annotation.annotationType());
for (int i = 0; i < mappings.size(); i++) {
AnnotationTypeMapping candidate = mappings.get(i);
if (candidate.getAnnotationType().equals(mappedAnnotationType)) {
return candidate;
}
}
throw new IllegalStateException(
"No mapping from " + annotation + " to " + mappedAnnotationType);
}
@Retention(RetentionPolicy.RUNTIME)
@ | TypeMappedAnnotationTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/CollectionIncompatibleTypeTest.java | {
"start": 24355,
"end": 24813
} | class ____ {
java.util.stream.Stream filter(List<Integer> xs, List<String> ss) {
// BUG: Diagnostic contains:
return xs.stream().filter(ss::contains);
}
}
""")
.doTest();
}
@Test
public void methodReferenceBinOp() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import java.util.List;
public | Test |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DoclingEndpointBuilderFactory.java | {
"start": 38813,
"end": 40894
} | interface ____ {
/**
* Docling (camel-docling)
* Process documents using Docling library for parsing and conversion.
*
* Category: transformation,ai
* Since: 4.15
* Maven coordinates: org.apache.camel:camel-docling
*
* @return the dsl builder for the headers' name.
*/
default DoclingHeaderNameBuilder docling() {
return DoclingHeaderNameBuilder.INSTANCE;
}
/**
* Docling (camel-docling)
* Process documents using Docling library for parsing and conversion.
*
* Category: transformation,ai
* Since: 4.15
* Maven coordinates: org.apache.camel:camel-docling
*
* Syntax: <code>docling:operationId</code>
*
* Path parameter: operationId (required)
* The operation identifier
*
* @param path operationId
* @return the dsl builder
*/
default DoclingEndpointBuilder docling(String path) {
return DoclingEndpointBuilderFactory.endpointBuilder("docling", path);
}
/**
* Docling (camel-docling)
* Process documents using Docling library for parsing and conversion.
*
* Category: transformation,ai
* Since: 4.15
* Maven coordinates: org.apache.camel:camel-docling
*
* Syntax: <code>docling:operationId</code>
*
* Path parameter: operationId (required)
* The operation identifier
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path operationId
* @return the dsl builder
*/
default DoclingEndpointBuilder docling(String componentName, String path) {
return DoclingEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
/**
* The builder of headers' name for the Docling component.
*/
public static | DoclingBuilders |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/internal/creation/bytebuddy/InlineDelegateByteBuddyMockMaker.java | {
"start": 5331,
"end": 5782
} | class ____
implements ClassCreatingMockMaker, InlineMockMaker, Instantiator {
private static final Instrumentation INSTRUMENTATION;
private static final Throwable INITIALIZATION_ERROR;
static {
Instrumentation instrumentation;
Throwable initializationError = null;
// ByteBuddy internally may attempt to fork a subprocess. In Java 11 and Java 19, the
// Java process | InlineDelegateByteBuddyMockMaker |
java | alibaba__fastjson | src/main/java/com/alibaba/fastjson/TypeReference.java | {
"start": 577,
"end": 1058
} | class ____ enables retrieval the type information even at
* runtime.
*
* <p>For example, to create a type literal for {@code List<String>}, you can
* create an empty anonymous inner class:
*
* <pre>
* TypeReference<List<String>> list = new TypeReference<List<String>>() {};
* </pre>
* This syntax cannot be used to create type literals that have wildcard
* parameters, such as {@code Class<?>} or {@code List<? extends CharSequence>}.
*/
public | which |
java | apache__flink | flink-connectors/flink-hadoop-compatibility/src/test/java/org/apache/flink/api/java/hadoop/mapred/HadoopInputFormatTest.java | {
"start": 9859,
"end": 10737
} | class ____
implements RecordReader<String, Long>, Configurable {
@Override
public void setConf(Configuration configuration) {}
@Override
public Configuration getConf() {
return null;
}
@Override
public boolean next(String s, Long aLong) throws IOException {
return false;
}
@Override
public String createKey() {
return null;
}
@Override
public Long createValue() {
return null;
}
@Override
public long getPos() throws IOException {
return 0;
}
@Override
public void close() throws IOException {}
@Override
public float getProgress() throws IOException {
return 0;
}
}
private | ConfigurableDummyRecordReader |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/state/internals/TimestampedKeyAndJoinSideDeserializer.java | {
"start": 1485,
"end": 3404
} | class ____<K> implements WrappingNullableDeserializer<TimestampedKeyAndJoinSide<K>, K, Void> {
private Deserializer<K> keyDeserializer;
private final Deserializer<Long> timestampDeserializer = new LongDeserializer();
TimestampedKeyAndJoinSideDeserializer(final Deserializer<K> keyDeserializer) {
this.keyDeserializer = keyDeserializer;
}
@SuppressWarnings("unchecked")
@Override
public void setIfUnset(final SerdeGetter getter) {
if (keyDeserializer == null) {
keyDeserializer = (Deserializer<K>) getter.keySerde().deserializer();
}
initNullableDeserializer(keyDeserializer, getter);
}
@Override
public void configure(final Map<String, ?> configs, final boolean isKey) {
keyDeserializer.configure(configs, isKey);
}
@Override
public TimestampedKeyAndJoinSide<K> deserialize(final String topic, final byte[] data) {
final boolean isLeft = data[StateSerdes.TIMESTAMP_SIZE] == 1;
final K key = keyDeserializer.deserialize(topic, rawKey(data));
final long timestamp = timestampDeserializer.deserialize(topic, rawTimestamp(data));
return isLeft ? TimestampedKeyAndJoinSide.makeLeft(key, timestamp) :
TimestampedKeyAndJoinSide.makeRight(key, timestamp);
}
private byte[] rawTimestamp(final byte[] data) {
final byte[] rawTimestamp = new byte[8];
System.arraycopy(data, 0, rawTimestamp, 0, 8);
return rawTimestamp;
}
private byte[] rawKey(final byte[] data) {
final byte[] rawKey = new byte[data.length - StateSerdes.TIMESTAMP_SIZE - StateSerdes.BOOLEAN_SIZE];
System.arraycopy(data, StateSerdes.TIMESTAMP_SIZE + StateSerdes.BOOLEAN_SIZE, rawKey, 0, rawKey.length);
return rawKey;
}
@Override
public void close() {
keyDeserializer.close();
}
}
| TimestampedKeyAndJoinSideDeserializer |
java | grpc__grpc-java | istio-interop-testing/src/main/java/io/grpc/testing/istio/EchoTestServer.java | {
"start": 19075,
"end": 19540
} | class ____ {
private final StringBuilder sb = new StringBuilder();
void writeKeyValue(String key, String value) {
sb.append(key).append("=").append(value).append("\n");
}
void writeKeyValueForRequest(String requestHeader, String key, String value) {
if (value != null) {
writeKeyValue(requestHeader, key + ":" + value);
}
}
@Override
public String toString() {
return sb.toString();
}
}
}
| EchoMessage |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/FormulaWithQuotedTableNamesAndQuotedColumnNamesTest.java | {
"start": 1842,
"end": 2713
} | class ____ {
@Id
@Column(name = "ID")
private Long id;
@Column(name = "INTEGER_VALUE")
private Integer integerValue;
@Formula(
"( select te.INTEGER_VALUE + te2.`select` + te2.ANOTHER_STRING_VALUE from TEST_ENTITY te, TEST_ENTITY_2 te2 where te.ID = 1)"
)
private Integer computedIntegerValue;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getComputedIntegerValue() {
return computedIntegerValue;
}
public void setComputedIntegerValue(Integer computedIntegerValue) {
this.computedIntegerValue = computedIntegerValue;
}
public Integer getIntegerValue() {
return integerValue;
}
public void setIntegerValue(Integer integerValue) {
this.integerValue = integerValue;
}
}
@Entity(name = "TestEntity2")
@Table(name = "TEST_ENTITY_2")
public static | TestEntity |
java | netty__netty | codec-stomp/src/main/java/io/netty/handler/codec/stomp/StompHeadersSubframe.java | {
"start": 808,
"end": 1030
} | interface ____ extends StompSubframe {
/**
* Returns command of this frame.
*/
StompCommand command();
/**
* Returns headers of this frame.
*/
StompHeaders headers();
}
| StompHeadersSubframe |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/webmonitor/history/ArchivedJson.java | {
"start": 1539,
"end": 2748
} | class ____ {
private static final ObjectMapper MAPPER = RestMapperUtils.getStrictObjectMapper();
private final String path;
private final String json;
public ArchivedJson(String path, String json) {
this.path = Preconditions.checkNotNull(path);
this.json = Preconditions.checkNotNull(json);
}
public ArchivedJson(String path, ResponseBody json) throws IOException {
this.path = Preconditions.checkNotNull(path);
StringWriter sw = new StringWriter();
MAPPER.writeValue(sw, Preconditions.checkNotNull(json));
this.json = sw.toString();
}
public String getPath() {
return path;
}
public String getJson() {
return json;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ArchivedJson) {
ArchivedJson other = (ArchivedJson) obj;
return this.path.equals(other.path) && this.json.equals(other.json);
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(path, json);
}
@Override
public String toString() {
return path + ":" + json;
}
}
| ArchivedJson |
java | apache__flink | flink-formats/flink-orc-nohive/src/test/java/org/apache/flink/orc/nohive/OrcColumnarRowSplitReaderNoHiveTest.java | {
"start": 1653,
"end": 4509
} | class ____ extends OrcColumnarRowSplitReaderTest {
@Override
protected void prepareReadFileWithTypes(String file, int rowSize) throws IOException {
// NOTE: orc has field name information, so name should be same as orc
TypeDescription schema =
TypeDescription.fromString(
"struct<"
+ "f0:float,"
+ "f1:double,"
+ "f2:timestamp,"
+ "f3:tinyint,"
+ "f4:smallint"
+ ">");
org.apache.hadoop.fs.Path filePath = new org.apache.hadoop.fs.Path(file);
Configuration conf = new Configuration();
Writer writer =
OrcFile.createWriter(filePath, OrcFile.writerOptions(conf).setSchema(schema));
VectorizedRowBatch batch = schema.createRowBatch(rowSize);
DoubleColumnVector col0 = (DoubleColumnVector) batch.cols[0];
DoubleColumnVector col1 = (DoubleColumnVector) batch.cols[1];
TimestampColumnVector col2 = (TimestampColumnVector) batch.cols[2];
LongColumnVector col3 = (LongColumnVector) batch.cols[3];
LongColumnVector col4 = (LongColumnVector) batch.cols[4];
col0.noNulls = false;
col1.noNulls = false;
col2.noNulls = false;
col3.noNulls = false;
col4.noNulls = false;
for (int i = 0; i < rowSize - 1; i++) {
col0.vector[i] = i;
col1.vector[i] = i;
Timestamp timestamp = toTimestamp(i);
col2.time[i] = timestamp.getTime();
col2.nanos[i] = timestamp.getNanos();
col3.vector[i] = i;
col4.vector[i] = i;
}
col0.isNull[rowSize - 1] = true;
col1.isNull[rowSize - 1] = true;
col2.isNull[rowSize - 1] = true;
col3.isNull[rowSize - 1] = true;
col4.isNull[rowSize - 1] = true;
batch.size = rowSize;
writer.addRowBatch(batch);
batch.reset();
writer.close();
}
@Override
protected OrcColumnarRowSplitReader createReader(
int[] selectedFields,
DataType[] fullTypes,
Map<String, Object> partitionSpec,
FileInputSplit split)
throws IOException {
return OrcNoHiveSplitReaderUtil.genPartColumnarRowReader(
new Configuration(),
IntStream.range(0, fullTypes.length).mapToObj(i -> "f" + i).toArray(String[]::new),
fullTypes,
partitionSpec,
selectedFields,
new ArrayList<>(),
BATCH_SIZE,
split.getPath(),
split.getStart(),
split.getLength());
}
}
| OrcColumnarRowSplitReaderNoHiveTest |
java | square__moshi | examples/src/main/java/com/squareup/moshi/recipes/CustomAdapterFactory.java | {
"start": 3031,
"end": 4000
} | class ____ implements JsonAdapter.Factory {
@Override
public @Nullable JsonAdapter<?> create(
Type type, Set<? extends Annotation> annotations, Moshi moshi) {
if (!annotations.isEmpty()) {
return null; // Annotations? This factory doesn't apply.
}
if (!(type instanceof ParameterizedType)) {
return null; // No type parameter? This factory doesn't apply.
}
ParameterizedType parameterizedType = (ParameterizedType) type;
if (parameterizedType.getRawType() != SortedSet.class) {
return null; // Not a sorted set? This factory doesn't apply.
}
Type elementType = parameterizedType.getActualTypeArguments()[0];
JsonAdapter<Object> elementAdapter = moshi.adapter(elementType);
return new SortedSetAdapter<>(elementAdapter).nullSafe();
}
}
public static void main(String[] args) throws Exception {
new CustomAdapterFactory().run();
}
}
| SortedSetAdapterFactory |
java | google__guava | android/guava/src/com/google/common/reflect/TypeToken.java | {
"start": 50075,
"end": 50389
} | class ____<T> extends TypeToken<T> {
SimpleTypeToken(Type type) {
super(type);
}
private static final long serialVersionUID = 0;
}
/**
* Collects parent types from a subtype.
*
* @param <K> The type "kind". Either a TypeToken, or Class.
*/
private abstract static | SimpleTypeToken |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/AbfsClientHandler.java | {
"start": 1641,
"end": 7910
} | class ____ implements Closeable {
public static final Logger LOG = LoggerFactory.getLogger(AbfsClientHandler.class);
private AbfsServiceType defaultServiceType;
private AbfsServiceType ingressServiceType;
private final AbfsDfsClient dfsAbfsClient;
private final AbfsBlobClient blobAbfsClient;
/**
* Constructs an AbfsClientHandler instance.
*
* Initializes the default and ingress service types from the provided configuration,
* then creates both DFS and Blob clients using the given params
*
* @param baseUrl the base URL for the file system.
* @param sharedKeyCredentials credentials for shared key authentication.
* @param abfsConfiguration the ABFS configuration.
* @param tokenProvider the access token provider, may be null.
* @param sasTokenProvider the SAS token provider, may be null.
* @param encryptionContextProvider the encryption context provider
* @param abfsClientContext the ABFS client context.
* @throws IOException if client creation or URL conversion fails.
*/
public AbfsClientHandler(final URL baseUrl,
final SharedKeyCredentials sharedKeyCredentials,
final AbfsConfiguration abfsConfiguration,
final AccessTokenProvider tokenProvider,
final SASTokenProvider sasTokenProvider,
final EncryptionContextProvider encryptionContextProvider,
final AbfsClientContext abfsClientContext) throws IOException {
// This will initialize the default and ingress service types.
// This is needed before creating the clients so that we can do cache warmup
// only for default client.
initServiceType(abfsConfiguration);
this.dfsAbfsClient = createDfsClient(baseUrl, sharedKeyCredentials,
abfsConfiguration, tokenProvider, sasTokenProvider, encryptionContextProvider,
abfsClientContext);
this.blobAbfsClient = createBlobClient(baseUrl, sharedKeyCredentials,
abfsConfiguration, tokenProvider, sasTokenProvider, encryptionContextProvider,
abfsClientContext);
}
/**
* Initialize the default service type based on the user configuration.
* @param abfsConfiguration set by user.
*/
private void initServiceType(final AbfsConfiguration abfsConfiguration) {
this.defaultServiceType = abfsConfiguration.getFsConfiguredServiceType();
this.ingressServiceType = abfsConfiguration.getIngressServiceType();
}
/**
* Get the AbfsClient based on the default service type.
* @return AbfsClient
*/
public AbfsClient getClient() {
return getClient(defaultServiceType);
}
/**
* Get the AbfsClient based on the ingress service type.
*
* @return AbfsClient for the ingress service type.
*/
public AbfsClient getIngressClient() {
return getClient(ingressServiceType);
}
/**
* Get the AbfsClient based on the service type.
* @param serviceType AbfsServiceType.
* @return AbfsClient
*/
public AbfsClient getClient(AbfsServiceType serviceType) {
return serviceType == AbfsServiceType.DFS ? dfsAbfsClient : blobAbfsClient;
}
/**
* Gets the AbfsDfsClient instance.
*
* @return the AbfsDfsClient instance.
*/
public AbfsDfsClient getDfsClient() {
return dfsAbfsClient;
}
/**
* Gets the AbfsBlobClient instance.
*
* @return the AbfsBlobClient instance.
*/
public AbfsBlobClient getBlobClient() {
return blobAbfsClient;
}
/**
* Create the AbfsDfsClient using the url used to configure file system.
* If URL is for Blob endpoint, it will be converted to DFS endpoint.
* @param baseUrl URL.
* @param creds SharedKeyCredentials.
* @param abfsConfiguration AbfsConfiguration.
* @param tokenProvider AccessTokenProvider.
* @param sasTokenProvider SASTokenProvider.
* @param encryptionContextProvider EncryptionContextProvider.
* @param abfsClientContext AbfsClientContext.
* @return AbfsDfsClient with DFS endpoint URL.
* @throws IOException if URL conversion fails.
*/
private AbfsDfsClient createDfsClient(final URL baseUrl,
final SharedKeyCredentials creds,
final AbfsConfiguration abfsConfiguration,
final AccessTokenProvider tokenProvider,
final SASTokenProvider sasTokenProvider,
final EncryptionContextProvider encryptionContextProvider,
final AbfsClientContext abfsClientContext) throws IOException {
URL dfsUrl = changeUrlFromBlobToDfs(baseUrl);
LOG.debug(
"Creating AbfsDfsClient with access token provider: %s and "
+ "SAS token provider: %s using the URL: %s",
tokenProvider, sasTokenProvider, dfsUrl);
return new AbfsDfsClient(dfsUrl, creds, abfsConfiguration,
tokenProvider, sasTokenProvider, encryptionContextProvider,
abfsClientContext);
}
/**
* Create the AbfsBlobClient using the url used to configure file system.
* If URL is for DFS endpoint, it will be converted to Blob endpoint.
* @param baseUrl URL.
* @param creds SharedKeyCredentials.
* @param abfsConfiguration AbfsConfiguration.
* @param tokenProvider AccessTokenProvider.
* @param sasTokenProvider SASTokenProvider.
* @param encryptionContextProvider EncryptionContextProvider.
* @param abfsClientContext AbfsClientContext.
* @return AbfsBlobClient with Blob endpoint URL.
* @throws IOException if URL conversion fails.
*/
private AbfsBlobClient createBlobClient(final URL baseUrl,
final SharedKeyCredentials creds,
final AbfsConfiguration abfsConfiguration,
final AccessTokenProvider tokenProvider,
final SASTokenProvider sasTokenProvider,
final EncryptionContextProvider encryptionContextProvider,
final AbfsClientContext abfsClientContext) throws IOException {
URL blobUrl = changeUrlFromDfsToBlob(baseUrl);
LOG.debug(
"Creating AbfsBlobClient with access token provider: %s and "
+ "SAS token provider: %s using the URL: %s",
tokenProvider, sasTokenProvider, blobUrl);
return new AbfsBlobClient(blobUrl, creds, abfsConfiguration,
tokenProvider, sasTokenProvider, encryptionContextProvider,
abfsClientContext);
}
@Override
public void close() throws IOException {
IOUtils.cleanupWithLogger(LOG, getDfsClient(), getBlobClient());
}
}
| AbfsClientHandler |
java | redisson__redisson | redisson/src/main/java/org/redisson/command/RedisBatchExecutor.java | {
"start": 1282,
"end": 2402
} | class ____<V, R> extends BaseRedisBatchExecutor<V, R> {
@SuppressWarnings("ParameterNumber")
public RedisBatchExecutor(boolean readOnlyMode, NodeSource source, Codec codec, RedisCommand<V> command,
Object[] params, CompletableFuture<R> mainPromise, boolean ignoreRedirect, ConnectionManager connectionManager,
RedissonObjectBuilder objectBuilder, ConcurrentMap<NodeSource, Entry> commands,
BatchOptions options, AtomicInteger index,
AtomicBoolean executed, RedissonObjectBuilder.ReferenceType referenceType, boolean noRetry) {
super(readOnlyMode, source, codec, command, params, mainPromise, ignoreRedirect, connectionManager, objectBuilder,
commands, options, index, executed, referenceType, noRetry);
}
@Override
public void execute() {
try {
addBatchCommandData(params);
} catch (Exception e) {
free();
handleError(connectionFuture, e);
throw e;
}
}
}
| RedisBatchExecutor |
java | apache__camel | components/camel-openstack/src/generated/java/org/apache/camel/component/openstack/swift/SwiftComponentConfigurer.java | {
"start": 742,
"end": 2303
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
SwiftComponent target = (SwiftComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
SwiftComponent target = (SwiftComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
default: return null;
}
}
}
| SwiftComponentConfigurer |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/common/util/BitArrayTests.java | {
"start": 1074,
"end": 12042
} | class ____ extends ESTestCase {
public void testRandom() {
try (BitArray bitArray = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
int numBits = randomIntBetween(1000, 10000);
for (int step = 0; step < 3; step++) {
boolean[] bits = new boolean[numBits];
List<Integer> slots = new ArrayList<>();
for (int i = 0; i < numBits; i++) {
bits[i] = randomBoolean();
slots.add(i);
}
Collections.shuffle(slots, random());
for (int i : slots) {
if (bits[i]) {
bitArray.set(i);
} else {
bitArray.clear(i);
}
}
for (int i = 0; i < numBits; i++) {
assertEquals(bitArray.get(i), bits[i]);
}
}
}
}
public void testRandomSetValue() {
try (BitArray bitArray = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
int numBits = randomIntBetween(1000, 10000);
for (int step = 0; step < 3; step++) {
boolean[] bits = new boolean[numBits];
List<Integer> slots = new ArrayList<>();
for (int i = 0; i < numBits; i++) {
bits[i] = randomBoolean();
slots.add(i);
}
Collections.shuffle(slots, random());
for (int i : slots) {
bitArray.set(i, bits[i]);
}
for (int i = 0; i < numBits; i++) {
assertEquals(bitArray.get(i), bits[i]);
}
}
}
}
public void testVeryLarge() {
assumeThat(Runtime.getRuntime().maxMemory(), greaterThanOrEqualTo(ByteSizeUnit.MB.toBytes(512)));
try (BitArray bitArray = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
long index = randomLongBetween(Integer.MAX_VALUE, (long) (Integer.MAX_VALUE * 1.5));
assertFalse(bitArray.get(index));
bitArray.set(index);
assertTrue(bitArray.get(index));
bitArray.clear(index);
assertFalse(bitArray.get(index));
}
}
public void testTooBigIsNotSet() throws IOException {
try (BitArray bits1 = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
for (int i = 0; i < 1000; i++) {
/*
* The first few times this is called we check within the
* array. But we quickly go beyond it and those all return
* false as well.
*/
assertFalse(bits1.get(i));
}
BytesStreamOutput out = new BytesStreamOutput();
bits1.writeTo(out);
try (BitArray bits2 = new BitArray(BigArrays.NON_RECYCLING_INSTANCE, randomBoolean(), out.bytes().streamInput())) {
for (int i = 0; i < 1000; i++) {
assertFalse(bits2.get(i));
}
}
}
}
public void testClearingDoesntAllocate() {
ByteSizeValue max = ByteSizeValue.of(1, ByteSizeUnit.KB);
MockBigArrays bigArrays = new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), max);
try (BitArray bitArray = new BitArray(1, bigArrays)) {
bitArray.clear(100000000);
}
}
public void testAllocation() {
MockBigArrays.assertFitsIn(ByteSizeValue.ofBytes(100), bigArrays -> new BitArray(1, bigArrays));
}
public void testOr() {
try (
BitArray bitArray1 = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE);
BitArray bitArray2 = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE);
BitArray bitArrayFull = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)
) {
int numBits = randomIntBetween(1000, 10000);
for (int step = 0; step < 3; step++) {
for (int i = 0; i < numBits; i++) {
if (randomBoolean()) {
if (rarely()) {
bitArray1.set(i);
bitArray2.set(i);
} else if (randomBoolean()) {
bitArray1.set(i);
} else {
bitArray2.set(i);
}
bitArrayFull.set(i);
}
}
bitArray1.or(bitArray2);
for (int i = 0; i < numBits; i++) {
assertEquals(bitArrayFull.get(i), bitArray1.get(i));
}
}
}
}
public void testNextBitSet() {
try (BitArray bitArray = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
int numBits = randomIntBetween(1000, 10000);
for (int step = 0; step < 3; step++) {
for (int i = 0; i < numBits; i++) {
if (randomBoolean()) {
bitArray.set(i);
}
}
long next = bitArray.nextSetBit(0);
for (int i = 0; i < numBits; i++) {
if (i == next) {
assertEquals(true, bitArray.get(i));
if (i < numBits - 1) {
next = bitArray.nextSetBit(i + 1);
}
} else {
assertEquals(false, bitArray.get(i));
}
}
}
}
}
public void testCardinality() {
try (BitArray bitArray = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
int numBits = randomIntBetween(1000, 10000);
long cardinality = 0;
for (int step = 0; step < 3; step++) {
for (int i = 0; i < numBits; i++) {
if (randomBoolean()) {
if (bitArray.get(i) == false) {
cardinality++;
}
bitArray.set(i);
}
}
assertEquals(cardinality, bitArray.cardinality());
}
}
}
public void testGetAndSet() {
try (BitArray bitArray = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
assertFalse(bitArray.getAndSet(100));
assertFalse(bitArray.getAndSet(1000));
assertTrue(bitArray.getAndSet(100));
assertFalse(bitArray.getAndSet(101));
assertFalse(bitArray.getAndSet(999));
assertTrue(bitArray.getAndSet(1000));
assertFalse(bitArray.get(99));
assertTrue(bitArray.get(100));
assertTrue(bitArray.get(101));
assertTrue(bitArray.get(999));
assertTrue(bitArray.get(1000));
assertFalse(bitArray.get(1001));
}
}
public void testFillTrueRandom() {
try (BitArray bitArray = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
int from = randomIntBetween(0, 1000);
int to = randomIntBetween(from, 1000);
bitArray.fill(0, 1000, false);
bitArray.fill(from, to, true);
for (int i = 0; i < 1000; i++) {
if (i < from || i >= to) {
assertFalse(bitArray.get(i));
} else {
assertTrue(bitArray.get(i));
}
}
}
}
public void testFillFalseRandom() {
try (BitArray bitArray = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
int from = randomIntBetween(0, 1000);
int to = randomIntBetween(from, 1000);
bitArray.fill(0, 1000, true);
bitArray.fill(from, to, false);
for (int i = 0; i < 1000; i++) {
if (i < from || i >= to) {
assertTrue(bitArray.get(i));
} else {
assertFalse(bitArray.get(i));
}
}
}
}
public void testFillTrueSingleWord() {
try (BitArray bitArray = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
int from = 8;
int to = 56;
bitArray.fill(0, 64, false);
bitArray.fill(from, to, true);
for (int i = 0; i < 64; i++) {
if (i < from || i >= to) {
assertFalse(bitArray.get(i));
} else {
assertTrue(bitArray.get(i));
}
}
}
}
public void testFillFalseSingleWord() {
try (BitArray bitArray = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
int from = 8;
int to = 56;
bitArray.fill(0, 64, true);
bitArray.fill(from, to, false);
for (int i = 0; i < 64; i++) {
if (i < from || i >= to) {
assertTrue(bitArray.get(i));
} else {
assertFalse(bitArray.get(i));
}
}
}
}
public void testFillTrueAfterArrayLength() {
try (BitArray bitArray = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
int from = 100;
int to = 200;
bitArray.fill(from, to, true);
for (int i = 0; i < to; i++) {
if (i < from) {
assertFalse(bitArray.get(i));
} else {
assertTrue(bitArray.get(i));
}
}
}
}
public void testFillFalseAfterArrayLength() {
try (BitArray bitArray = new BitArray(1, BigArrays.NON_RECYCLING_INSTANCE)) {
int from = 100;
int to = 200;
bitArray.fill(from, to, false);
for (int i = 0; i < to; i++) {
assertFalse(bitArray.get(i));
}
}
}
public void testSerialize() throws Exception {
int initial = randomIntBetween(1, 100_000);
BitArray bits1 = new BitArray(initial, BigArrays.NON_RECYCLING_INSTANCE);
int numBits = randomIntBetween(1, 1000_000);
for (int i = 0; i < numBits; i++) {
if (randomBoolean()) {
bits1.set(i);
}
if (rarely()) {
bits1.clear(i);
}
}
BytesStreamOutput out = new BytesStreamOutput();
bits1.writeTo(out);
BitArray bits2 = new BitArray(BigArrays.NON_RECYCLING_INSTANCE, randomBoolean(), out.bytes().streamInput());
assertThat(bits2.size(), equalTo(bits1.size()));
for (long i = 0; i < bits1.size(); i++) {
assertThat(bits2.get(i), equalTo(bits1.get(i)));
}
Releasables.close(bits1, bits2);
}
}
| BitArrayTests |
java | quarkusio__quarkus | integration-tests/hibernate-orm-jpamodelgen/src/test/java/io/quarkus/it/hibernate/jpamodelgen/HibernateJpaModelGenTest.java | {
"start": 234,
"end": 2241
} | class ____ {
private static final String ROOT = "/static-metamodel";
@Test
public void staticMetamodel() {
// Create/retrieve
given()
.pathParam("name", "foo")
.contentType(ContentType.JSON)
.when().get(ROOT + "/by/name/{name}")
.then()
.statusCode(404);
given()
.body(new MyStaticMetamodelEntity("foo"))
.contentType(ContentType.JSON)
.when().post(ROOT)
.then()
.statusCode(204);
given()
.pathParam("name", "foo")
.contentType(ContentType.JSON)
.when().get(ROOT + "/by/name/{name}")
.then()
.statusCode(200);
// Update
given()
.pathParam("name", "bar")
.contentType(ContentType.JSON)
.when().get(ROOT + "/by/name/{name}")
.then()
.statusCode(404);
given()
.pathParam("before", "foo")
.pathParam("after", "bar")
.contentType(ContentType.JSON)
.when().post(ROOT + "/rename/{before}/to/{after}")
.then()
.statusCode(204);
given()
.pathParam("name", "bar")
.contentType(ContentType.JSON)
.when().get(ROOT + "/by/name/{name}")
.then()
.statusCode(200);
// Delete
given()
.pathParam("name", "bar")
.contentType(ContentType.JSON)
.when().delete(ROOT + "/by/name/{name}")
.then()
.statusCode(204);
given()
.pathParam("name", "bar")
.contentType(ContentType.JSON)
.when().get(ROOT + "/by/name/{name}")
.then()
.statusCode(404);
}
}
| HibernateJpaModelGenTest |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/csrf/CsrfTokenRequestHandlerLoggerHolder.java | {
"start": 850,
"end": 1028
} | class ____ {
static final Log logger = LogFactory.getLog(CsrfTokenRequestHandler.class);
private CsrfTokenRequestHandlerLoggerHolder() {
}
}
| CsrfTokenRequestHandlerLoggerHolder |
java | alibaba__nacos | core/src/test/java/com/alibaba/nacos/core/CoreUtApplication.java | {
"start": 846,
"end": 992
} | class ____ {
public static void main(String[] args) {
SpringApplication.run(CoreUtApplication.class, args);
}
}
| CoreUtApplication |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/records/impl/pb/ResourceTypeInfoPBImpl.java | {
"start": 1495,
"end": 4243
} | class ____ extends ResourceTypeInfo {
ResourceTypeInfoProto proto = ResourceTypeInfoProto.getDefaultInstance();
ResourceTypeInfoProto.Builder builder = null;
boolean viaProto = false;
private String name = null;
private String defaultUnit = null;
private ResourceTypes resourceTypes = null;
public ResourceTypeInfoPBImpl() {
builder = ResourceTypeInfoProto.newBuilder();
}
public ResourceTypeInfoPBImpl(ResourceTypeInfoProto proto) {
this.proto = proto;
viaProto = true;
}
public ResourceTypeInfoProto getProto() {
mergeLocalToProto();
return proto;
}
private void mergeLocalToProto() {
if (viaProto) {
maybeInitBuilder();
}
mergeLocalToBuilder();
proto = builder.build();
viaProto = true;
}
private void mergeLocalToBuilder() {
if (this.name != null) {
builder.setName(this.name);
}
if (this.defaultUnit != null) {
builder.setUnits(this.defaultUnit);
}
if (this.resourceTypes != null) {
builder.setType(convertToProtoFormat(this.resourceTypes));
}
}
private void maybeInitBuilder() {
if (viaProto || builder == null) {
builder = YarnProtos.ResourceTypeInfoProto.newBuilder(proto);
}
viaProto = false;
}
@Override
public String getName() {
if (this.name != null) {
return this.name;
}
YarnProtos.ResourceTypeInfoProtoOrBuilder p = viaProto ? proto : builder;
return p.getName();
}
@Override
public void setName(String rName) {
maybeInitBuilder();
if (rName == null) {
builder.clearName();
}
this.name = rName;
}
@Override
public String getDefaultUnit() {
if (this.defaultUnit != null) {
return this.defaultUnit;
}
YarnProtos.ResourceTypeInfoProtoOrBuilder p = viaProto ? proto : builder;
return p.getUnits();
}
@Override
public void setDefaultUnit(String rUnits) {
maybeInitBuilder();
if (rUnits == null) {
builder.clearUnits();
}
this.defaultUnit = rUnits;
}
@Override
public ResourceTypes getResourceType() {
if (this.resourceTypes != null) {
return this.resourceTypes;
}
YarnProtos.ResourceTypeInfoProtoOrBuilder p = viaProto ? proto : builder;
return convertFromProtoFormat(p.getType());
}
@Override
public void setResourceType(ResourceTypes type) {
maybeInitBuilder();
if (type == null) {
builder.clearType();
}
this.resourceTypes = type;
}
public static ResourceTypesProto convertToProtoFormat(ResourceTypes e) {
return ResourceTypesProto.valueOf(e.name());
}
public static ResourceTypes convertFromProtoFormat(ResourceTypesProto e) {
return ResourceTypes.valueOf(e.name());
}
}
| ResourceTypeInfoPBImpl |
java | elastic__elasticsearch | x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/HitExtractorProcessor.java | {
"start": 779,
"end": 2170
} | class ____ implements Processor {
public static final String NAME = "h";
private final HitExtractor extractor;
public HitExtractorProcessor(HitExtractor extractor) {
this.extractor = extractor;
}
public HitExtractorProcessor(StreamInput in) throws IOException {
extractor = in.readNamedWriteable(HitExtractor.class);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeNamedWriteable(extractor);
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public Object process(Object input) {
if ((input instanceof SearchHit) == false) {
throw new QlIllegalArgumentException("Expected a SearchHit but received {}", input);
}
return extractor.extract((SearchHit) input);
}
@Override
public int hashCode() {
return Objects.hash(extractor);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
HitExtractorProcessor other = (HitExtractorProcessor) obj;
return Objects.equals(extractor, other.extractor);
}
@Override
public String toString() {
return extractor.toString();
}
}
| HitExtractorProcessor |
java | dropwizard__dropwizard | dropwizard-jersey/src/test/java/io/dropwizard/jersey/MyMessageParamConverterProvider.java | {
"start": 714,
"end": 1031
} | class ____ implements ParamConverter<MyMessage> {
@Override
public MyMessage fromString(String value) {
return new MyMessage(value);
}
@Override
public String toString(MyMessage value) {
return value.getMessage();
}
}
}
| MyMessageParamConverter |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/Mockito.java | {
"start": 100588,
"end": 100958
} | interface ____
* want to mock.
* @return the mock object.
* @since 5.1.0
*/
@SafeVarargs
public static <T> T mock(MockSettings settings, T... reified) {
if (reified == null || reified.length > 0) {
throw new IllegalArgumentException(
"Please don't pass any values here. Java will detect | you |
java | spring-projects__spring-boot | module/spring-boot-security-test/src/main/java/org/springframework/boot/security/test/autoconfigure/webmvc/SecurityMockMvcAutoConfiguration.java | {
"start": 2617,
"end": 3103
} | class ____ {
MockMvcHtmlUnitDriverCustomizer securityDelegateMockMvcHtmlUnitDriverCustomizer() {
return (driver) -> driver
.setExecutor(new DelegatingSecurityContextExecutor(Executors.newSingleThreadExecutor()));
}
}
/**
* {@link MockMvcBuilderCustomizer} that ensures that requests run with the user in
* the {@link TestSecurityContextHolder}.
*
* @see SecurityMockMvcRequestPostProcessors#testSecurityContext
*/
static | SecurityMockMvcHtmlUnitDriverConfiguration |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/serde/LogicalTypeJsonSerializer.java | {
"start": 19837,
"end": 24022
} | class ____ extends LogicalTypeDefaultVisitor<Boolean> {
private final boolean serializeCatalogObjects;
CompactSerializationChecker(boolean serializeCatalogObjects) {
this.serializeCatalogObjects = serializeCatalogObjects;
}
@Override
public Boolean visit(CharType charType) {
return charType.getLength() > 0;
}
@Override
public Boolean visit(VarCharType varCharType) {
return varCharType.getLength() > 0;
}
@Override
public Boolean visit(BinaryType binaryType) {
return binaryType.getLength() > 0;
}
@Override
public Boolean visit(VarBinaryType varBinaryType) {
return varBinaryType.getLength() > 0;
}
@Override
public Boolean visit(TimestampType timestampType) {
return timestampType.getKind() == TimestampKind.REGULAR;
}
@Override
public Boolean visit(ZonedTimestampType zonedTimestampType) {
return zonedTimestampType.getKind() == TimestampKind.REGULAR;
}
@Override
public Boolean visit(LocalZonedTimestampType localZonedTimestampType) {
return localZonedTimestampType.getKind() == TimestampKind.REGULAR;
}
@Override
public Boolean visit(DistinctType distinctType) {
// A catalog-based distinct type is always string serializable if the children are
// serializable and the configuration allows it to be compact.
final boolean canBeCompact = distinctType.getSourceType().accept(this);
if (!canBeCompact) {
return false;
}
return !serializeCatalogObjects;
}
@Override
public Boolean visit(StructuredType structuredType) {
// Inline structured types are always string serializable.
// A catalog-based structured type is always string serializable if the children are
// serializable and the configuration allows it to be compact.
final boolean canBeCompact = defaultMethod(structuredType);
if (!canBeCompact) {
return false;
}
return structuredType.getObjectIdentifier().isEmpty() || !serializeCatalogObjects;
}
@Override
protected Boolean defaultMethod(LogicalType logicalType) {
if (!logicalType.getChildren().stream().allMatch(t -> t.accept(this))) {
return false;
}
switch (logicalType.getTypeRoot()) {
case RAW:
if (logicalType instanceof TypeInformationRawType) {
return false;
}
final RawType<?> rawType = (RawType<?>) logicalType;
final TypeSerializer<?> serializer = rawType.getTypeSerializer();
// external serializer will go through data type serialization
if (serializer instanceof ExternalSerializer) {
return false;
}
// null serializer will go through special serialization
if (serializer.equals(NullSerializer.INSTANCE)) {
return false;
}
// fall through
case BOOLEAN:
case DECIMAL:
case TINYINT:
case SMALLINT:
case INTEGER:
case BIGINT:
case FLOAT:
case DOUBLE:
case DATE:
case TIME_WITHOUT_TIME_ZONE:
case INTERVAL_YEAR_MONTH:
case INTERVAL_DAY_TIME:
case ARRAY:
case MULTISET:
case MAP:
case ROW:
case STRUCTURED_TYPE:
case NULL:
case DESCRIPTOR:
return true;
default:
// fall back to generic serialization
return false;
}
}
}
}
| CompactSerializationChecker |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/properties/VersionsProperties.java | {
"start": 1123,
"end": 2290
} | class ____ {
private Integer id1;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) {
scope.inTransaction( em -> {
PropertiesTestEntity pte = new PropertiesTestEntity( "x" );
em.persist( pte );
id1 = pte.getId();
} );
scope.inTransaction( em -> {
PropertiesTestEntity pte = em.find( PropertiesTestEntity.class, id1 );
pte.setStr( "y" );
} );
}
@Test
public void testRevisionsCounts(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
assertEquals( Arrays.asList( 1, 2 ), auditReader.getRevisions( PropertiesTestEntity.class, id1 ) );
} );
}
@Test
public void testHistoryOfId1(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
PropertiesTestEntity ver1 = new PropertiesTestEntity( id1, "x" );
PropertiesTestEntity ver2 = new PropertiesTestEntity( id1, "y" );
assertEquals( ver1, auditReader.find( PropertiesTestEntity.class, id1, 1 ) );
assertEquals( ver2, auditReader.find( PropertiesTestEntity.class, id1, 2 ) );
} );
}
}
| VersionsProperties |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.