language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/BZip2Codec.java | {
"start": 11213,
"end": 11857
} | class ____ starts here//
private CBZip2InputStream input;
boolean needsReset;
private BufferedInputStream bufferedIn;
private boolean isHeaderStripped = false;
private boolean isSubHeaderStripped = false;
private READ_MODE readMode = READ_MODE.CONTINUOUS;
private long startingPos = 0L;
private boolean didInitialRead;
// Following state machine handles different states of compressed stream
// position
// HOLD : Don't advertise compressed stream position
// ADVERTISE : Read 1 more character and advertise stream position
// See more comments about it before updatePos method.
private | data |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_instr.java | {
"start": 185,
"end": 393
} | class ____ extends TestCase {
public void test_method() throws Exception {
assertEquals(4, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "INSTR('foobarbar', 'bar')"));
}
}
| EvalMethodTest_instr |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java | {
"start": 1494,
"end": 4797
} | class ____ {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ClassLoaderResourceLoader.class);
private static SoftReference<Map<ClassLoader, Map<String, Set<URL>>>> classLoaderResourcesCache = null;
static {
// register resources destroy listener
GlobalResourcesRepository.registerGlobalDisposable(ClassLoaderResourceLoader::destroy);
}
public static Map<ClassLoader, Set<URL>> loadResources(String fileName, Collection<ClassLoader> classLoaders)
throws InterruptedException {
Map<ClassLoader, Set<URL>> resources = new ConcurrentHashMap<>();
CountDownLatch countDownLatch = new CountDownLatch(classLoaders.size());
for (ClassLoader classLoader : classLoaders) {
GlobalResourcesRepository.getGlobalExecutorService().submit(() -> {
resources.put(classLoader, loadResources(fileName, classLoader));
countDownLatch.countDown();
});
}
countDownLatch.await();
return Collections.unmodifiableMap(new LinkedHashMap<>(resources));
}
public static Set<URL> loadResources(String fileName, ClassLoader currentClassLoader) {
Map<ClassLoader, Map<String, Set<URL>>> classLoaderCache;
if (classLoaderResourcesCache == null || (classLoaderCache = classLoaderResourcesCache.get()) == null) {
synchronized (ClassLoaderResourceLoader.class) {
if (classLoaderResourcesCache == null || (classLoaderCache = classLoaderResourcesCache.get()) == null) {
classLoaderCache = new ConcurrentHashMap<>();
classLoaderResourcesCache = new SoftReference<>(classLoaderCache);
}
}
}
if (!classLoaderCache.containsKey(currentClassLoader)) {
classLoaderCache.putIfAbsent(currentClassLoader, new ConcurrentHashMap<>());
}
Map<String, Set<URL>> urlCache = classLoaderCache.get(currentClassLoader);
if (!urlCache.containsKey(fileName)) {
Set<URL> set = new LinkedHashSet<>();
Enumeration<URL> urls;
try {
urls = currentClassLoader.getResources(fileName);
if (urls != null) {
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
set.add(url);
}
}
} catch (IOException e) {
logger.error(
COMMON_IO_EXCEPTION,
"",
"",
"Exception occurred when reading SPI definitions. SPI path: " + fileName + " ClassLoader name: "
+ currentClassLoader,
e);
}
urlCache.put(fileName, set);
}
return urlCache.get(fileName);
}
public static void destroy() {
synchronized (ClassLoaderResourceLoader.class) {
classLoaderResourcesCache = null;
}
}
// for test
protected static SoftReference<Map<ClassLoader, Map<String, Set<URL>>>> getClassLoaderResourcesCache() {
return classLoaderResourcesCache;
}
}
| ClassLoaderResourceLoader |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableSkipWhile.java | {
"start": 935,
"end": 1386
} | class ____<T> extends AbstractObservableWithUpstream<T, T> {
final Predicate<? super T> predicate;
public ObservableSkipWhile(ObservableSource<T> source, Predicate<? super T> predicate) {
super(source);
this.predicate = predicate;
}
@Override
public void subscribeActual(Observer<? super T> observer) {
source.subscribe(new SkipWhileObserver<>(observer, predicate));
}
static final | ObservableSkipWhile |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/DynamicPropertySource.java | {
"start": 3977,
"end": 4805
} | class ____ {
*
* @Container
* static GenericContainer redis =
* new GenericContainer("redis:5.0.3-alpine").withExposedPorts(6379);
*
* // ...
*
* @DynamicPropertySource
* static void redisProperties(DynamicPropertyRegistry registry) {
* registry.add("redis.host", redis::getHost);
* registry.add("redis.port", redis::getFirstMappedPort);
* }
* }</pre>
*
* @author Phillip Webb
* @author Sam Brannen
* @since 5.2.5
* @see DynamicPropertyRegistry
* @see DynamicPropertyRegistrar
* @see ContextConfiguration
* @see TestPropertySource
* @see org.springframework.core.env.PropertySource
* @see org.springframework.test.annotation.DirtiesContext
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @ | ExampleIntegrationTests |
java | reactor__reactor-core | reactor-tools/src/buildPluginTest/resources/mock-gradle/src/test/java/demo/SomeClassTest.java | {
"start": 1008,
"end": 1532
} | class ____ {
@Test
public void shouldAddAssemblyInfo() {
//the first level is instantiated from the production code, which is instrumented
Flux<Integer> flux = new SomeClass().obtainFlux();
//the second level is instantiated here in test code, which isn't instrumented
flux = flux.map(i -> i);
Scannable scannable = Scannable.from(flux);
assertThat(scannable.steps())
.hasSize(2)
.endsWith("map")
.first(STRING).startsWith("Flux.just ⇢ at demo.SomeClass.obtainFlux(SomeClass.java:");
}
}
| SomeClassTest |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/DataFrameAnalyticsDest.java | {
"start": 844,
"end": 3523
} | class ____ implements Writeable, ToXContentObject {
public static final ParseField INDEX = new ParseField("index");
public static final ParseField RESULTS_FIELD = new ParseField("results_field");
private static final String DEFAULT_RESULTS_FIELD = "ml";
public static ConstructingObjectParser<DataFrameAnalyticsDest, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<DataFrameAnalyticsDest, Void> parser = new ConstructingObjectParser<>(
"data_frame_analytics_dest",
ignoreUnknownFields,
a -> new DataFrameAnalyticsDest((String) a[0], (String) a[1])
);
parser.declareString(ConstructingObjectParser.constructorArg(), INDEX);
parser.declareString(ConstructingObjectParser.optionalConstructorArg(), RESULTS_FIELD);
return parser;
}
private final String index;
private final String resultsField;
public DataFrameAnalyticsDest(String index, @Nullable String resultsField) {
this.index = ExceptionsHelper.requireNonNull(index, INDEX);
if (index.isEmpty()) {
throw ExceptionsHelper.badRequestException("[{}] must be non-empty", INDEX);
}
this.resultsField = resultsField == null ? DEFAULT_RESULTS_FIELD : resultsField;
}
public DataFrameAnalyticsDest(StreamInput in) throws IOException {
index = in.readString();
resultsField = in.readString();
}
public DataFrameAnalyticsDest(DataFrameAnalyticsDest other) {
this.index = other.index;
this.resultsField = other.resultsField;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(index);
out.writeString(resultsField);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(INDEX.getPreferredName(), index);
builder.field(RESULTS_FIELD.getPreferredName(), resultsField);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || getClass() != o.getClass()) return false;
DataFrameAnalyticsDest other = (DataFrameAnalyticsDest) o;
return Objects.equals(index, other.index) && Objects.equals(resultsField, other.resultsField);
}
@Override
public int hashCode() {
return Objects.hash(index, resultsField);
}
public String getIndex() {
return index;
}
public String getResultsField() {
return resultsField;
}
}
| DataFrameAnalyticsDest |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/WatsonDiscoveryEndpointBuilderFactory.java | {
"start": 1460,
"end": 1606
} | interface ____ {
/**
* Builder for endpoint for the IBM Watson Discovery component.
*/
public | WatsonDiscoveryEndpointBuilderFactory |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/internal/LimitedCollectionClassification.java | {
"start": 352,
"end": 417
} | enum ____ {
BAG,
LIST,
SET,
MAP
}
| LimitedCollectionClassification |
java | google__auto | value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java | {
"start": 75496,
"end": 77136
} | class ____<K extends Number, V extends Comparable<K>> {
public Builder<K, V> putAll(Map<String, V> map) {
mapBuilder().putAll(map);
return this;
}
public abstract ImmutableMap.Builder<String, V> mapBuilder();
public Builder<K, V> putAll(ImmutableTable<String, K, V> table) {
tableBuilder().putAll(table);
return this;
}
public abstract ImmutableTable.Builder<String, K, V> tableBuilder();
public abstract BuilderWithExoticPropertyBuilders<K, V> build();
}
}
@Test
public void testBuilderWithExoticPropertyBuilders() {
ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1);
ImmutableTable<String, Integer, Integer> table = ImmutableTable.of("one", 1, -1);
BuilderWithExoticPropertyBuilders<Integer, Integer> a =
BuilderWithExoticPropertyBuilders.<Integer, Integer>builder()
.putAll(map)
.putAll(table)
.build();
assertEquals(map, a.map());
assertEquals(table, a.table());
BuilderWithExoticPropertyBuilders.Builder<Integer, Integer> bBuilder =
BuilderWithExoticPropertyBuilders.builder();
bBuilder.mapBuilder().putAll(map);
bBuilder.tableBuilder().putAll(table);
BuilderWithExoticPropertyBuilders<Integer, Integer> b = bBuilder.build();
assertEquals(a, b);
BuilderWithExoticPropertyBuilders<Integer, Integer> empty =
BuilderWithExoticPropertyBuilders.<Integer, Integer>builder().build();
assertEquals(ImmutableMap.of(), empty.map());
assertEquals(ImmutableTable.of(), empty.table());
}
@AutoValue
public abstract static | Builder |
java | google__gson | gson/src/main/java/com/google/gson/Gson.java | {
"start": 6905,
"end": 28152
} | class ____ {
static final boolean DEFAULT_JSON_NON_EXECUTABLE = false;
// Strictness of `null` is the legacy mode where some Gson APIs are always lenient
static final Strictness DEFAULT_STRICTNESS = null;
static final FormattingStyle DEFAULT_FORMATTING_STYLE = FormattingStyle.COMPACT;
static final boolean DEFAULT_ESCAPE_HTML = true;
static final boolean DEFAULT_SERIALIZE_NULLS = false;
static final boolean DEFAULT_COMPLEX_MAP_KEYS = false;
static final boolean DEFAULT_SPECIALIZE_FLOAT_VALUES = false;
static final boolean DEFAULT_USE_JDK_UNSAFE = true;
static final String DEFAULT_DATE_PATTERN = null;
static final FieldNamingStrategy DEFAULT_FIELD_NAMING_STRATEGY = FieldNamingPolicy.IDENTITY;
static final ToNumberStrategy DEFAULT_OBJECT_TO_NUMBER_STRATEGY = ToNumberPolicy.DOUBLE;
static final ToNumberStrategy DEFAULT_NUMBER_TO_NUMBER_STRATEGY =
ToNumberPolicy.LAZILY_PARSED_NUMBER;
private static final String JSON_NON_EXECUTABLE_PREFIX = ")]}'\n";
/**
* This thread local guards against reentrant calls to {@link #getAdapter(TypeToken)}. In certain
* object graphs, creating an adapter for a type may recursively require an adapter for the same
* type! Without intervention, the recursive lookup would stack overflow. We cheat by returning a
* proxy type adapter, {@link FutureTypeAdapter}, which is wired up once the initial adapter has
* been created.
*
* <p>The map stores the type adapters for ongoing {@code getAdapter} calls, with the type token
* provided to {@code getAdapter} as key and either {@code FutureTypeAdapter} or a regular {@code
* TypeAdapter} as value.
*/
@SuppressWarnings("ThreadLocalUsage")
private final ThreadLocal<Map<TypeToken<?>, TypeAdapter<?>>> threadLocalAdapterResults =
new ThreadLocal<>();
private final ConcurrentMap<TypeToken<?>, TypeAdapter<?>> typeTokenCache =
new ConcurrentHashMap<>();
private final ConstructorConstructor constructorConstructor;
private final JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory;
final List<TypeAdapterFactory> factories;
final Excluder excluder;
final FieldNamingStrategy fieldNamingStrategy;
final Map<Type, InstanceCreator<?>> instanceCreators;
final boolean serializeNulls;
final boolean complexMapKeySerialization;
final boolean generateNonExecutableJson;
final boolean htmlSafe;
final FormattingStyle formattingStyle;
final Strictness strictness;
final boolean serializeSpecialFloatingPointValues;
final boolean useJdkUnsafe;
final String datePattern;
final int dateStyle;
final int timeStyle;
final LongSerializationPolicy longSerializationPolicy;
final List<TypeAdapterFactory> builderFactories;
final List<TypeAdapterFactory> builderHierarchyFactories;
final ToNumberStrategy objectToNumberStrategy;
final ToNumberStrategy numberToNumberStrategy;
final List<ReflectionAccessFilter> reflectionFilters;
/**
* Constructs a Gson object with default configuration. The default configuration has the
* following settings:
*
* <ul>
* <li>The JSON generated by {@code toJson} methods is in compact representation. This means
* that all the unneeded white-space is removed. You can change this behavior with {@link
* GsonBuilder#setPrettyPrinting()}.
* <li>When the JSON generated contains more than one line, the kind of newline and indent to
* use can be configured with {@link GsonBuilder#setFormattingStyle(FormattingStyle)}.
* <li>The generated JSON omits all the fields that are null. Note that nulls in arrays are kept
* as is since an array is an ordered list. Moreover, if a field is not null, but its
* generated JSON is empty, the field is kept. You can configure Gson to serialize null
* values by setting {@link GsonBuilder#serializeNulls()}.
* <li>Gson provides default serialization and deserialization for Enums, {@link Map}, {@link
* java.net.URL}, {@link java.net.URI}, {@link java.util.Locale}, {@link java.util.Date},
* {@link java.math.BigDecimal}, and {@link java.math.BigInteger} classes. If you would
* prefer to change the default representation, you can do so by registering a type adapter
* through {@link GsonBuilder#registerTypeAdapter(Type, Object)}.
* <li>The default Date format is same as {@link java.text.DateFormat#DEFAULT}. This format
* ignores the millisecond portion of the date during serialization. You can change this by
* invoking {@link GsonBuilder#setDateFormat(int, int)} or {@link
* GsonBuilder#setDateFormat(String)}.
* <li>By default, Gson ignores the {@link com.google.gson.annotations.Expose} annotation. You
* can enable Gson to serialize/deserialize only those fields marked with this annotation
* through {@link GsonBuilder#excludeFieldsWithoutExposeAnnotation()}.
* <li>By default, Gson ignores the {@link com.google.gson.annotations.Since} annotation. You
* can enable Gson to use this annotation through {@link GsonBuilder#setVersion(double)}.
* <li>The default field naming policy for the output JSON is same as in Java. So, a Java class
* field {@code versionNumber} will be output as {@code "versionNumber"} in JSON. The same
* rules are applied for mapping incoming JSON to the Java classes. You can change this
* policy through {@link GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)}.
* <li>By default, Gson excludes {@code transient} or {@code static} fields from consideration
* for serialization and deserialization. You can change this behavior through {@link
* GsonBuilder#excludeFieldsWithModifiers(int...)}.
* <li>No explicit strictness is set. You can change this by calling {@link
* GsonBuilder#setStrictness(Strictness)}.
* </ul>
*/
public Gson() {
this(
Excluder.DEFAULT,
DEFAULT_FIELD_NAMING_STRATEGY,
Collections.emptyMap(),
DEFAULT_SERIALIZE_NULLS,
DEFAULT_COMPLEX_MAP_KEYS,
DEFAULT_JSON_NON_EXECUTABLE,
DEFAULT_ESCAPE_HTML,
DEFAULT_FORMATTING_STYLE,
DEFAULT_STRICTNESS,
DEFAULT_SPECIALIZE_FLOAT_VALUES,
DEFAULT_USE_JDK_UNSAFE,
LongSerializationPolicy.DEFAULT,
DEFAULT_DATE_PATTERN,
DateFormat.DEFAULT,
DateFormat.DEFAULT,
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
DEFAULT_OBJECT_TO_NUMBER_STRATEGY,
DEFAULT_NUMBER_TO_NUMBER_STRATEGY,
Collections.emptyList());
}
Gson(
Excluder excluder,
FieldNamingStrategy fieldNamingStrategy,
Map<Type, InstanceCreator<?>> instanceCreators,
boolean serializeNulls,
boolean complexMapKeySerialization,
boolean generateNonExecutableGson,
boolean htmlSafe,
FormattingStyle formattingStyle,
Strictness strictness,
boolean serializeSpecialFloatingPointValues,
boolean useJdkUnsafe,
LongSerializationPolicy longSerializationPolicy,
String datePattern,
int dateStyle,
int timeStyle,
List<TypeAdapterFactory> builderFactories,
List<TypeAdapterFactory> builderHierarchyFactories,
List<TypeAdapterFactory> factoriesToBeAdded,
ToNumberStrategy objectToNumberStrategy,
ToNumberStrategy numberToNumberStrategy,
List<ReflectionAccessFilter> reflectionFilters) {
this.excluder = excluder;
this.fieldNamingStrategy = fieldNamingStrategy;
this.instanceCreators = instanceCreators;
this.constructorConstructor =
new ConstructorConstructor(instanceCreators, useJdkUnsafe, reflectionFilters);
this.serializeNulls = serializeNulls;
this.complexMapKeySerialization = complexMapKeySerialization;
this.generateNonExecutableJson = generateNonExecutableGson;
this.htmlSafe = htmlSafe;
this.formattingStyle = formattingStyle;
this.strictness = strictness;
this.serializeSpecialFloatingPointValues = serializeSpecialFloatingPointValues;
this.useJdkUnsafe = useJdkUnsafe;
this.longSerializationPolicy = longSerializationPolicy;
this.datePattern = datePattern;
this.dateStyle = dateStyle;
this.timeStyle = timeStyle;
this.builderFactories = builderFactories;
this.builderHierarchyFactories = builderHierarchyFactories;
this.objectToNumberStrategy = objectToNumberStrategy;
this.numberToNumberStrategy = numberToNumberStrategy;
this.reflectionFilters = reflectionFilters;
List<TypeAdapterFactory> factories = new ArrayList<>();
// built-in type adapters that cannot be overridden
factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
factories.add(ObjectTypeAdapter.getFactory(objectToNumberStrategy));
// the excluder must precede all adapters that handle user-defined types
factories.add(excluder);
// users' type adapters
factories.addAll(factoriesToBeAdded);
// type adapters for basic platform types
factories.add(TypeAdapters.STRING_FACTORY);
factories.add(TypeAdapters.INTEGER_FACTORY);
factories.add(TypeAdapters.BOOLEAN_FACTORY);
factories.add(TypeAdapters.BYTE_FACTORY);
factories.add(TypeAdapters.SHORT_FACTORY);
TypeAdapter<Number> longAdapter = longAdapter(longSerializationPolicy);
factories.add(TypeAdapters.newFactory(long.class, Long.class, longAdapter));
factories.add(
TypeAdapters.newFactory(
double.class, Double.class, doubleAdapter(serializeSpecialFloatingPointValues)));
factories.add(
TypeAdapters.newFactory(
float.class, Float.class, floatAdapter(serializeSpecialFloatingPointValues)));
factories.add(NumberTypeAdapter.getFactory(numberToNumberStrategy));
factories.add(TypeAdapters.ATOMIC_INTEGER_FACTORY);
factories.add(TypeAdapters.ATOMIC_BOOLEAN_FACTORY);
factories.add(TypeAdapters.newFactory(AtomicLong.class, atomicLongAdapter(longAdapter)));
factories.add(
TypeAdapters.newFactory(AtomicLongArray.class, atomicLongArrayAdapter(longAdapter)));
factories.add(TypeAdapters.ATOMIC_INTEGER_ARRAY_FACTORY);
factories.add(TypeAdapters.CHARACTER_FACTORY);
factories.add(TypeAdapters.STRING_BUILDER_FACTORY);
factories.add(TypeAdapters.STRING_BUFFER_FACTORY);
factories.add(TypeAdapters.newFactory(BigDecimal.class, TypeAdapters.BIG_DECIMAL));
factories.add(TypeAdapters.newFactory(BigInteger.class, TypeAdapters.BIG_INTEGER));
// Add adapter for LazilyParsedNumber because user can obtain it from Gson and then try to
// serialize it again
factories.add(
TypeAdapters.newFactory(LazilyParsedNumber.class, TypeAdapters.LAZILY_PARSED_NUMBER));
factories.add(TypeAdapters.URL_FACTORY);
factories.add(TypeAdapters.URI_FACTORY);
factories.add(TypeAdapters.UUID_FACTORY);
factories.add(TypeAdapters.CURRENCY_FACTORY);
factories.add(TypeAdapters.LOCALE_FACTORY);
factories.add(TypeAdapters.INET_ADDRESS_FACTORY);
factories.add(TypeAdapters.BIT_SET_FACTORY);
factories.add(DefaultDateTypeAdapter.DEFAULT_STYLE_FACTORY);
factories.add(TypeAdapters.CALENDAR_FACTORY);
if (SqlTypesSupport.SUPPORTS_SQL_TYPES) {
factories.add(SqlTypesSupport.TIME_FACTORY);
factories.add(SqlTypesSupport.DATE_FACTORY);
factories.add(SqlTypesSupport.TIMESTAMP_FACTORY);
}
factories.add(ArrayTypeAdapter.FACTORY);
factories.add(TypeAdapters.CLASS_FACTORY);
// type adapters for composite and user-defined types
factories.add(new CollectionTypeAdapterFactory(constructorConstructor));
factories.add(new MapTypeAdapterFactory(constructorConstructor, complexMapKeySerialization));
this.jsonAdapterFactory = new JsonAdapterAnnotationTypeAdapterFactory(constructorConstructor);
factories.add(jsonAdapterFactory);
factories.add(TypeAdapters.ENUM_FACTORY);
factories.add(
new ReflectiveTypeAdapterFactory(
constructorConstructor,
fieldNamingStrategy,
excluder,
jsonAdapterFactory,
reflectionFilters));
this.factories = Collections.unmodifiableList(factories);
}
/**
* Returns a new GsonBuilder containing all custom factories and configuration used by the current
* instance.
*
* @return a GsonBuilder instance.
* @since 2.8.3
*/
public GsonBuilder newBuilder() {
return new GsonBuilder(this);
}
/**
* @deprecated This method by accident exposes an internal Gson class; it might be removed in a
* future version.
*/
@Deprecated
public Excluder excluder() {
return excluder;
}
/**
* Returns the field naming strategy used by this Gson instance.
*
* @see GsonBuilder#setFieldNamingStrategy(FieldNamingStrategy)
*/
public FieldNamingStrategy fieldNamingStrategy() {
return fieldNamingStrategy;
}
/**
* Returns whether this Gson instance is serializing JSON object properties with {@code null}
* values, or just omits them.
*
* @see GsonBuilder#serializeNulls()
*/
public boolean serializeNulls() {
return serializeNulls;
}
/**
* Returns whether this Gson instance produces JSON output which is HTML-safe, that means all HTML
* characters are escaped.
*
* @see GsonBuilder#disableHtmlEscaping()
*/
public boolean htmlSafe() {
return htmlSafe;
}
private TypeAdapter<Number> doubleAdapter(boolean serializeSpecialFloatingPointValues) {
if (serializeSpecialFloatingPointValues) {
return TypeAdapters.DOUBLE;
}
return new TypeAdapter<Number>() {
@Override
public Double read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
return in.nextDouble();
}
@Override
public void write(JsonWriter out, Number value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
double doubleValue = value.doubleValue();
checkValidFloatingPoint(doubleValue);
out.value(doubleValue);
}
};
}
private TypeAdapter<Number> floatAdapter(boolean serializeSpecialFloatingPointValues) {
if (serializeSpecialFloatingPointValues) {
return TypeAdapters.FLOAT;
}
return new TypeAdapter<Number>() {
@Override
public Float read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
return (float) in.nextDouble();
}
@Override
public void write(JsonWriter out, Number value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
float floatValue = value.floatValue();
checkValidFloatingPoint(floatValue);
// For backward compatibility don't call `JsonWriter.value(float)` because that method has
// been newly added and not all custom JsonWriter implementations might override it yet
Number floatNumber = value instanceof Float ? value : floatValue;
out.value(floatNumber);
}
};
}
static void checkValidFloatingPoint(double value) {
if (Double.isNaN(value) || Double.isInfinite(value)) {
throw new IllegalArgumentException(
value
+ " is not a valid double value as per JSON specification. To override this"
+ " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method.");
}
}
private static TypeAdapter<Number> longAdapter(LongSerializationPolicy longSerializationPolicy) {
if (longSerializationPolicy == LongSerializationPolicy.DEFAULT) {
return TypeAdapters.LONG;
}
return new TypeAdapter<Number>() {
@Override
public Number read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
return in.nextLong();
}
@Override
public void write(JsonWriter out, Number value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
out.value(value.toString());
}
};
}
private static TypeAdapter<AtomicLong> atomicLongAdapter(TypeAdapter<Number> longAdapter) {
return new TypeAdapter<AtomicLong>() {
@Override
public void write(JsonWriter out, AtomicLong value) throws IOException {
longAdapter.write(out, value.get());
}
@Override
public AtomicLong read(JsonReader in) throws IOException {
Number value = longAdapter.read(in);
return new AtomicLong(value.longValue());
}
}.nullSafe();
}
private static TypeAdapter<AtomicLongArray> atomicLongArrayAdapter(
TypeAdapter<Number> longAdapter) {
return new TypeAdapter<AtomicLongArray>() {
@Override
public void write(JsonWriter out, AtomicLongArray value) throws IOException {
out.beginArray();
for (int i = 0, length = value.length(); i < length; i++) {
longAdapter.write(out, value.get(i));
}
out.endArray();
}
@Override
public AtomicLongArray read(JsonReader in) throws IOException {
List<Long> list = new ArrayList<>();
in.beginArray();
while (in.hasNext()) {
long value = longAdapter.read(in).longValue();
list.add(value);
}
in.endArray();
int length = list.size();
AtomicLongArray array = new AtomicLongArray(length);
for (int i = 0; i < length; ++i) {
array.set(i, list.get(i));
}
return array;
}
}.nullSafe();
}
/**
* Returns the type adapter for {@code type}.
*
* <p>When calling this method concurrently from multiple threads and requesting an adapter for
* the same type this method may return different {@code TypeAdapter} instances. However, that
* should normally not be an issue because {@code TypeAdapter} implementations are supposed to be
* stateless.
*
* @throws IllegalArgumentException if this Gson instance cannot serialize and deserialize {@code
* type}.
*/
public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) {
Objects.requireNonNull(type, "type must not be null");
TypeAdapter<?> cached = typeTokenCache.get(type);
if (cached != null) {
@SuppressWarnings("unchecked")
TypeAdapter<T> adapter = (TypeAdapter<T>) cached;
return adapter;
}
Map<TypeToken<?>, TypeAdapter<?>> threadCalls = threadLocalAdapterResults.get();
boolean isInitialAdapterRequest = false;
if (threadCalls == null) {
threadCalls = new HashMap<>();
threadLocalAdapterResults.set(threadCalls);
isInitialAdapterRequest = true;
} else {
// the key and value type parameters always agree
@SuppressWarnings("unchecked")
TypeAdapter<T> ongoingCall = (TypeAdapter<T>) threadCalls.get(type);
if (ongoingCall != null) {
return ongoingCall;
}
}
TypeAdapter<T> candidate = null;
try {
FutureTypeAdapter<T> call = new FutureTypeAdapter<>();
threadCalls.put(type, call);
for (TypeAdapterFactory factory : factories) {
candidate = factory.create(this, type);
if (candidate != null) {
call.setDelegate(candidate);
// Replace future adapter with actual adapter
threadCalls.put(type, candidate);
break;
}
}
} finally {
if (isInitialAdapterRequest) {
threadLocalAdapterResults.remove();
}
}
if (candidate == null) {
throw new IllegalArgumentException(
"GSON (" + GsonBuildConfig.VERSION + ") cannot handle " + type);
}
if (isInitialAdapterRequest) {
/*
* Publish resolved adapters to all threads
* Can only do this for the initial request because cyclic dependency TypeA -> TypeB -> TypeA
* would otherwise publish adapter for TypeB which uses not yet resolved adapter for TypeA
* See https://github.com/google/gson/issues/625
*/
typeTokenCache.putAll(threadCalls);
}
return candidate;
}
/**
* Returns the type adapter for {@code type}.
*
* @throws IllegalArgumentException if this Gson instance cannot serialize and deserialize {@code
* type}.
*/
public <T> TypeAdapter<T> getAdapter(Class<T> type) {
return getAdapter(TypeToken.get(type));
}
/**
* This method is used to get an alternate type adapter for the specified type. This is used to
* access a type adapter that is overridden by a {@link TypeAdapterFactory} that you may have
* registered. This feature is typically used when you want to register a type adapter that does a
* little bit of work but then delegates further processing to the Gson default type adapter. Here
* is an example:
*
* <p>Let's say we want to write a type adapter that counts the number of objects being read from
* or written to JSON. We can achieve this by writing a type adapter factory that uses the {@code
* getDelegateAdapter} method:
*
* <pre>{@code
* | Gson |
java | quarkusio__quarkus | extensions/security/spi/src/main/java/io/quarkus/security/spi/SecurityTransformerBuildItem.java | {
"start": 12467,
"end": 16303
} | interface ____-level annotations are transformed to individual methods instead
for (var implementationMethod : implementation.methods()) {
// for now, this will not consider meta-annotations on purpose, because ATM we handle them separately
if (hasSecurityAnnotationDetectedByIndex(implementationMethod)) {
// this annotation was indexed, therefore already collected
continue;
}
if (repeatable) {
var annotations = annotationOverlay
.annotationsWithRepeatable(implementationMethod, securityAnnotationName)
.stream()
.map(interfaceInstance -> AnnotationInstance.builder(interfaceInstance.name())
.addAll(interfaceInstance.values())
.buildWithTarget(implementationMethod))
.toList();
if (!annotations.isEmpty()) {
if (result == null) {
result = new HashSet<>();
}
result.addAll(annotations);
}
} else {
if (annotationOverlay.hasAnnotation(implementationMethod, securityAnnotationName)) {
if (result == null) {
result = new HashSet<>();
}
var interfaceInstance = annotationOverlay.annotation(implementationMethod, securityAnnotationName);
var implementationInstance = AnnotationInstance.builder(interfaceInstance.name())
.addAll(interfaceInstance.values())
.buildWithTarget(implementationMethod);
result.add(implementationInstance);
}
}
}
}
return result;
}
private Collection<AnnotationInstance> getAnnotations(DotName securityAnnotationName, boolean repeatable) {
final Collection<AnnotationInstance> indexedAnnotationInstances;
if (repeatable) {
indexedAnnotationInstances = annotationOverlay.index().getAnnotationsWithRepeatable(securityAnnotationName,
annotationOverlay.index());
} else {
indexedAnnotationInstances = annotationOverlay.index().getAnnotations(securityAnnotationName);
}
if (interfaceTransformations == null || indexedAnnotationInstances.isEmpty()) {
return indexedAnnotationInstances;
}
var checkedInterfaces = new HashSet<String>();
// add security annotation instances from interfaces direct implementors
var result = new HashSet<>(indexedAnnotationInstances);
for (var annotationInstance : indexedAnnotationInstances) {
final ClassInfo declaringClass;
if (annotationInstance.target().kind() == AnnotationTarget.Kind.METHOD) {
declaringClass = annotationInstance.target().asMethod().declaringClass();
} else if (annotationInstance.target().kind() == AnnotationTarget.Kind.CLASS) {
declaringClass = annotationInstance.target().asClass();
} else {
// illegal state - this shouldn't happen
continue;
}
if (shouldCheckForSecurityAnnotations(declaringClass, checkedInterfaces)) {
// test that secured | class |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/odps/OdpsFormatCommentTest26.java | {
"start": 121,
"end": 451
} | class ____ extends TestCase {
public void test_drop_function() throws Exception {
String sql = "create table t as select * from dual;";
assertEquals("CREATE TABLE t"
+ "\nAS"
+ "\nSELECT *"
+ "\nFROM dual;", SQLUtils.formatOdps(sql));
}
}
| OdpsFormatCommentTest26 |
java | elastic__elasticsearch | x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/tree/NodeInfo.java | {
"start": 4460,
"end": 5524
} | interface ____<P1, P2, T> {
T apply(Source l, P1 p1, P2 p2);
}
public static <T extends Node<?>, P1, P2, P3> NodeInfo<T> create(T n, NodeCtor3<P1, P2, P3, T> ctor, P1 p1, P2 p2, P3 p3) {
return new NodeInfo<T>(n) {
@Override
protected List<Object> innerProperties() {
return Arrays.asList(p1, p2, p3);
}
protected T innerTransform(Function<Object, Object> rule) {
boolean same = true;
@SuppressWarnings("unchecked")
P1 newP1 = (P1) rule.apply(p1);
same &= Objects.equals(p1, newP1);
@SuppressWarnings("unchecked")
P2 newP2 = (P2) rule.apply(p2);
same &= Objects.equals(p2, newP2);
@SuppressWarnings("unchecked")
P3 newP3 = (P3) rule.apply(p3);
same &= Objects.equals(p3, newP3);
return same ? node : ctor.apply(node.source(), newP1, newP2, newP3);
}
};
}
public | NodeCtor2 |
java | google__dagger | dagger-compiler/main/java/dagger/internal/codegen/DelegateComponentProcessor.java | {
"start": 8123,
"end": 9665
} | interface ____ {
@Provides
static SourceFileGenerator<ContributionBinding> factoryGenerator(
FactoryGenerator generator,
CompilerOptions compilerOptions,
XProcessingEnv processingEnv) {
return hjarWrapper(generator, compilerOptions, processingEnv);
}
@Provides
static SourceFileGenerator<ProductionBinding> producerFactoryGenerator(
ProducerFactoryGenerator generator,
CompilerOptions compilerOptions,
XProcessingEnv processingEnv) {
return hjarWrapper(generator, compilerOptions, processingEnv);
}
@Provides
static SourceFileGenerator<MembersInjectionBinding> membersInjectorGenerator(
MembersInjectorGenerator generator,
CompilerOptions compilerOptions,
XProcessingEnv processingEnv) {
return hjarWrapper(generator, compilerOptions, processingEnv);
}
@Provides
@ModuleGenerator
static SourceFileGenerator<XTypeElement> moduleConstructorProxyGenerator(
ModuleConstructorProxyGenerator generator,
CompilerOptions compilerOptions,
XProcessingEnv processingEnv) {
return hjarWrapper(generator, compilerOptions, processingEnv);
}
}
private static <T> SourceFileGenerator<T> hjarWrapper(
SourceFileGenerator<T> generator,
CompilerOptions compilerOptions,
XProcessingEnv processingEnv) {
return compilerOptions.headerCompilation()
? SourceFileHjarGenerator.wrap(generator, processingEnv)
: generator;
}
}
| SourceFileGeneratorsModule |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java | {
"start": 6384,
"end": 6838
} | class ____ the following {@link HandlerAdapter HandlerAdapters}:
* <ul>
* <li>{@link RequestMappingHandlerAdapter}
* for processing requests with annotated controller methods.
* <li>{@link HttpRequestHandlerAdapter}
* for processing requests with {@link HttpRequestHandler HttpRequestHandlers}.
* <li>{@link SimpleControllerHandlerAdapter}
* for processing requests with interface-based {@link Controller Controllers}.
* </ul>
*
* <p>This | registers |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/JUnit4SetUpNotRunTest.java | {
"start": 4023,
"end": 4284
} | interface ____ {}")
.expectUnchanged()
.addInputLines(
"in/Foo.java",
"""
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public | Before |
java | google__guava | android/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java | {
"start": 22240,
"end": 23441
} | class ____ extends ExampleStackTrace {
private final ExampleStackTrace conflictingStackTrace;
private PotentialDeadlockException(
LockGraphNode node1, LockGraphNode node2, ExampleStackTrace conflictingStackTrace) {
super(node1, node2);
this.conflictingStackTrace = conflictingStackTrace;
initCause(conflictingStackTrace);
}
public ExampleStackTrace getConflictingStackTrace() {
return conflictingStackTrace;
}
/**
* Appends the chain of messages from the {@code conflictingStackTrace} to the original {@code
* message}.
*/
@Override
public String getMessage() {
// requireNonNull is safe because ExampleStackTrace sets a non-null message.
StringBuilder message = new StringBuilder(requireNonNull(super.getMessage()));
for (Throwable t = conflictingStackTrace; t != null; t = t.getCause()) {
message.append(", ").append(t.getMessage());
}
return message.toString();
}
}
/**
* Internal Lock implementations implement the {@code CycleDetectingLock} interface, allowing the
* detection logic to treat all locks in the same manner.
*/
private | PotentialDeadlockException |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/matchers/method/MethodMatchers.java | {
"start": 1337,
"end": 2796
} | interface ____ extends MethodMatcher {
/** Match on types that satisfy the given predicate. */
MethodClassMatcher onClass(TypePredicate predicate);
/** Match on types with the given fully-qualified name. (e.g. {@code java.lang.String}) */
MethodClassMatcher onExactClass(String className);
/** Match on the given type exactly. */
MethodClassMatcher onExactClass(Supplier<Type> classType);
/** Match on types that are exactly the same as any of the given types. */
MethodClassMatcher onExactClassAny(Iterable<String> classTypes);
/** Match on types that are exactly the same as any of the given types. */
MethodClassMatcher onExactClassAny(String... classTypes);
/** Match on descendants of the given fully-qualified type name. */
MethodClassMatcher onDescendantOf(String className);
/** Match on descendants of the given type. */
MethodClassMatcher onDescendantOf(Supplier<Type> classType);
/** Match on types that are descendants of any of the given types. */
MethodClassMatcher onDescendantOfAny(String... classTypes);
/** Match on types that are descendants of any of the given types. */
MethodClassMatcher onDescendantOfAny(Iterable<String> classTypes);
/** Match on any class. */
MethodClassMatcher anyClass();
}
/**
* @deprecated use {@code Matcher<ExpressionTree>} instead of referring directly to this type.
*/
@Deprecated
public | InstanceMethodMatcher |
java | elastic__elasticsearch | x-pack/plugin/ilm/src/main/java/org/elasticsearch/xpack/ilm/IlmHealthIndicatorService.java | {
"start": 17210,
"end": 17841
} | interface ____ {
boolean test(Long now, IndexMetadata indexMetadata);
static TimeValue getElapsedTime(Long now, Long currentTime) {
return currentTime == null ? TimeValue.ZERO : TimeValue.timeValueMillis(now - currentTime);
}
default RuleConfig and(RuleConfig other) {
return (now, indexMetadata) -> test(now, indexMetadata) && other.test(now, indexMetadata);
}
default RuleConfig or(RuleConfig other) {
return (now, indexMetadata) -> test(now, indexMetadata) || other.test(now, indexMetadata);
}
/**
* Builder | RuleConfig |
java | quarkusio__quarkus | extensions/elasticsearch-rest-client/runtime/src/main/java/io/quarkus/elasticsearch/restclient/lowlevel/runtime/ElasticsearchRestClientProducer.java | {
"start": 496,
"end": 1351
} | class ____ {
@Inject
ElasticsearchConfig config;
private RestClient client;
private Sniffer sniffer;
@Produces
@Singleton
public RestClient restClient() {
RestClientBuilder builder = RestClientBuilderHelper.createRestClientBuilder(config);
this.client = builder.build();
if (config.discovery().enabled()) {
this.sniffer = RestClientBuilderHelper.createSniffer(client, config);
}
return this.client;
}
@PreDestroy
void destroy() {
try {
if (this.sniffer != null) {
this.sniffer.close();
}
if (this.client != null) {
this.client.close();
}
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
}
| ElasticsearchRestClientProducer |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java | {
"start": 4419,
"end": 14135
} | class ____ extends WebApplicationObjectSupport
implements ViewResolver, Ordered, InitializingBean {
private @Nullable ContentNegotiationManager contentNegotiationManager;
private final ContentNegotiationManagerFactoryBean cnmFactoryBean = new ContentNegotiationManagerFactoryBean();
private boolean useNotAcceptableStatusCode = false;
private @Nullable List<View> defaultViews;
private @Nullable List<ViewResolver> viewResolvers;
private int order = Ordered.HIGHEST_PRECEDENCE;
/**
* Set the {@link ContentNegotiationManager} to use to determine requested media types.
* <p>If not set, ContentNegotiationManager's default constructor will be used,
* applying a {@link org.springframework.web.accept.HeaderContentNegotiationStrategy}.
* @see ContentNegotiationManager#ContentNegotiationManager()
*/
public void setContentNegotiationManager(@Nullable ContentNegotiationManager contentNegotiationManager) {
this.contentNegotiationManager = contentNegotiationManager;
}
/**
* Return the {@link ContentNegotiationManager} to use to determine requested media types.
* @since 4.1.9
*/
public @Nullable ContentNegotiationManager getContentNegotiationManager() {
return this.contentNegotiationManager;
}
/**
* Indicate whether a {@link HttpServletResponse#SC_NOT_ACCEPTABLE 406 Not Acceptable}
* status code should be returned if no suitable view can be found.
* <p>Default is {@code false}, meaning that this view resolver returns {@code null} for
* {@link #resolveViewName(String, Locale)} when an acceptable view cannot be found.
* This will allow for view resolvers chaining. When this property is set to {@code true},
* {@link #resolveViewName(String, Locale)} will respond with a view that sets the
* response status to {@code 406 Not Acceptable} instead.
*/
public void setUseNotAcceptableStatusCode(boolean useNotAcceptableStatusCode) {
this.useNotAcceptableStatusCode = useNotAcceptableStatusCode;
}
/**
* Whether to return HTTP Status 406 if no suitable is found.
*/
public boolean isUseNotAcceptableStatusCode() {
return this.useNotAcceptableStatusCode;
}
/**
* Set the default views to use when a more specific view can not be obtained
* from the {@link ViewResolver} chain.
*/
public void setDefaultViews(List<View> defaultViews) {
this.defaultViews = defaultViews;
}
public List<View> getDefaultViews() {
return (this.defaultViews != null ? Collections.unmodifiableList(this.defaultViews) :
Collections.emptyList());
}
/**
* Sets the view resolvers to be wrapped by this view resolver.
* <p>If this property is not set, view resolvers will be detected automatically.
*/
public void setViewResolvers(List<ViewResolver> viewResolvers) {
this.viewResolvers = viewResolvers;
}
public List<ViewResolver> getViewResolvers() {
return (this.viewResolvers != null ? Collections.unmodifiableList(this.viewResolvers) :
Collections.emptyList());
}
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
@Override
protected void initServletContext(ServletContext servletContext) {
Collection<ViewResolver> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(obtainApplicationContext(), ViewResolver.class).values();
if (this.viewResolvers == null) {
this.viewResolvers = new ArrayList<>(matchingBeans.size());
for (ViewResolver viewResolver : matchingBeans) {
if (this != viewResolver) {
this.viewResolvers.add(viewResolver);
}
}
}
else {
for (int i = 0; i < this.viewResolvers.size(); i++) {
ViewResolver vr = this.viewResolvers.get(i);
if (matchingBeans.contains(vr)) {
continue;
}
String name = vr.getClass().getName() + i;
obtainApplicationContext().getAutowireCapableBeanFactory().initializeBean(vr, name);
}
}
AnnotationAwareOrderComparator.sort(this.viewResolvers);
}
@Override
public void afterPropertiesSet() {
if (this.contentNegotiationManager == null) {
this.contentNegotiationManager = this.cnmFactoryBean.build();
}
if (this.viewResolvers == null || this.viewResolvers.isEmpty()) {
logger.warn("No ViewResolvers configured");
}
}
@Override
public @Nullable View resolveViewName(String viewName, Locale locale) throws Exception {
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
List<MediaType> requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest());
if (requestedMediaTypes != null) {
List<View> candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes);
View bestView = getBestView(candidateViews, requestedMediaTypes, attrs);
if (bestView != null) {
return bestView;
}
}
String mediaTypeInfo = (logger.isDebugEnabled() && requestedMediaTypes != null ?
" given " + requestedMediaTypes.toString() : "");
if (this.useNotAcceptableStatusCode) {
if (logger.isDebugEnabled()) {
logger.debug("Using 406 NOT_ACCEPTABLE" + mediaTypeInfo);
}
return NOT_ACCEPTABLE_VIEW;
}
else {
logger.debug("View remains unresolved" + mediaTypeInfo);
return null;
}
}
/**
* Determines the list of {@link MediaType} for the given {@link HttpServletRequest}.
* @param request the current servlet request
* @return the list of media types requested, if any
*/
protected @Nullable List<MediaType> getMediaTypes(HttpServletRequest request) {
Assert.state(this.contentNegotiationManager != null, "No ContentNegotiationManager set");
try {
ServletWebRequest webRequest = new ServletWebRequest(request);
List<MediaType> acceptableMediaTypes = this.contentNegotiationManager.resolveMediaTypes(webRequest);
List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request);
Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>();
for (MediaType acceptable : acceptableMediaTypes) {
for (MediaType producible : producibleMediaTypes) {
if (acceptable.isCompatibleWith(producible)) {
compatibleMediaTypes.add(getMostSpecificMediaType(acceptable, producible));
}
}
}
List<MediaType> selectedMediaTypes = new ArrayList<>(compatibleMediaTypes);
MimeTypeUtils.sortBySpecificity(selectedMediaTypes);
return selectedMediaTypes;
}
catch (HttpMediaTypeNotAcceptableException ex) {
if (logger.isDebugEnabled()) {
logger.debug(ex.getMessage());
}
return null;
}
}
@SuppressWarnings("unchecked")
private List<MediaType> getProducibleMediaTypes(HttpServletRequest request) {
Set<MediaType> mediaTypes = (Set<MediaType>)
request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
if (!CollectionUtils.isEmpty(mediaTypes)) {
return new ArrayList<>(mediaTypes);
}
else {
return Collections.singletonList(MediaType.ALL);
}
}
/**
* Return the more specific of the acceptable and the producible media types
* with the q-value of the former.
*/
private MediaType getMostSpecificMediaType(MediaType acceptType, MediaType produceType) {
produceType = produceType.copyQualityValue(acceptType);
if (acceptType.isLessSpecific(produceType)) {
return produceType;
}
else {
return acceptType;
}
}
private List<View> getCandidateViews(String viewName, Locale locale, List<MediaType> requestedMediaTypes)
throws Exception {
List<View> candidateViews = new ArrayList<>();
if (this.viewResolvers != null) {
Assert.state(this.contentNegotiationManager != null, "No ContentNegotiationManager set");
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, locale);
if (view != null) {
candidateViews.add(view);
}
for (MediaType requestedMediaType : requestedMediaTypes) {
List<String> extensions = this.contentNegotiationManager.resolveFileExtensions(requestedMediaType);
for (String extension : extensions) {
String viewNameWithExtension = viewName + '.' + extension;
view = viewResolver.resolveViewName(viewNameWithExtension, locale);
if (view != null) {
candidateViews.add(view);
}
}
}
}
}
if (!CollectionUtils.isEmpty(this.defaultViews)) {
candidateViews.addAll(this.defaultViews);
}
return candidateViews;
}
private @Nullable View getBestView(List<View> candidateViews, List<MediaType> requestedMediaTypes, RequestAttributes attrs) {
for (View candidateView : candidateViews) {
if (candidateView instanceof SmartView smartView) {
if (smartView.isRedirectView()) {
return candidateView;
}
}
}
for (MediaType mediaType : requestedMediaTypes) {
for (View candidateView : candidateViews) {
if (StringUtils.hasText(candidateView.getContentType())) {
MediaType candidateContentType = MediaType.parseMediaType(candidateView.getContentType());
if (mediaType.isCompatibleWith(candidateContentType)) {
mediaType = mediaType.removeQualityValue();
if (logger.isDebugEnabled()) {
logger.debug("Selected '" + mediaType + "' given " + requestedMediaTypes);
}
attrs.setAttribute(View.SELECTED_CONTENT_TYPE, mediaType, RequestAttributes.SCOPE_REQUEST);
return candidateView;
}
}
}
}
return null;
}
private static final View NOT_ACCEPTABLE_VIEW = new View() {
@Override
public @Nullable String getContentType() {
return null;
}
@Override
public void render(@Nullable Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
}
};
}
| ContentNegotiatingViewResolver |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/junit4/statements/RunBeforeTestExecutionCallbacks.java | {
"start": 1180,
"end": 1522
} | class ____ JUnit 4.9 or higher.
*
* @author Sam Brannen
* @since 5.0
* @see #evaluate()
* @see RunAfterTestExecutionCallbacks
* @deprecated since Spring Framework 7.0 in favor of the
* {@link org.springframework.test.context.junit.jupiter.SpringExtension SpringExtension}
* and JUnit Jupiter
*/
@Deprecated(since = "7.0")
public | requires |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/DebeziumOracleComponentBuilderFactory.java | {
"start": 79164,
"end": 98149
} | class ____ should be used to store and
* recover database schema changes. The configuration properties for the
* history are prefixed with the 'schema.history.internal.' string.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: io.debezium.storage.kafka.history.KafkaSchemaHistory
* Group: oracle
*
* @param schemaHistoryInternal the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder schemaHistoryInternal(java.lang.String schemaHistoryInternal) {
doSetProperty("schemaHistoryInternal", schemaHistoryInternal);
return this;
}
/**
* The path to the file that will be used to record the database schema
* history.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: oracle
*
* @param schemaHistoryInternalFileFilename the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder schemaHistoryInternalFileFilename(java.lang.String schemaHistoryInternalFileFilename) {
doSetProperty("schemaHistoryInternalFileFilename", schemaHistoryInternalFileFilename);
return this;
}
/**
* Controls the action Debezium will take when it meets a DDL statement
* in binlog, that it cannot parse.By default the connector will stop
* operating but by changing the setting it can ignore the statements
* which it cannot parse. If skipping is enabled then Debezium can miss
* metadata changes.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: oracle
*
* @param schemaHistoryInternalSkipUnparseableDdl the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder schemaHistoryInternalSkipUnparseableDdl(boolean schemaHistoryInternalSkipUnparseableDdl) {
doSetProperty("schemaHistoryInternalSkipUnparseableDdl", schemaHistoryInternalSkipUnparseableDdl);
return this;
}
/**
* Controls what DDL will Debezium store in database schema history. By
* default (false) Debezium will store all incoming DDL statements. If
* set to true, then only DDL that manipulates a table from captured
* schema/database will be stored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: oracle
*
* @param schemaHistoryInternalStoreOnlyCapturedDatabasesDdl the value
* to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder schemaHistoryInternalStoreOnlyCapturedDatabasesDdl(boolean schemaHistoryInternalStoreOnlyCapturedDatabasesDdl) {
doSetProperty("schemaHistoryInternalStoreOnlyCapturedDatabasesDdl", schemaHistoryInternalStoreOnlyCapturedDatabasesDdl);
return this;
}
/**
* Controls what DDL will Debezium store in database schema history. By
* default (false) Debezium will store all incoming DDL statements. If
* set to true, then only DDL that manipulates a captured table will be
* stored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: oracle
*
* @param schemaHistoryInternalStoreOnlyCapturedTablesDdl the value to
* set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder schemaHistoryInternalStoreOnlyCapturedTablesDdl(boolean schemaHistoryInternalStoreOnlyCapturedTablesDdl) {
doSetProperty("schemaHistoryInternalStoreOnlyCapturedTablesDdl", schemaHistoryInternalStoreOnlyCapturedTablesDdl);
return this;
}
/**
* Specify how schema names should be adjusted for compatibility with
* the message converter used by the connector, including: 'avro'
* replaces the characters that cannot be used in the Avro type name
* with underscore; 'avro_unicode' replaces the underscore or characters
* that cannot be used in the Avro type name with corresponding unicode
* like _uxxxx. Note: _ is an escape sequence like backslash in
* Java;'none' does not apply any adjustment (default).
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: none
* Group: oracle
*
* @param schemaNameAdjustmentMode the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder schemaNameAdjustmentMode(java.lang.String schemaNameAdjustmentMode) {
doSetProperty("schemaNameAdjustmentMode", schemaNameAdjustmentMode);
return this;
}
/**
* The name of the data collection that is used to send signals/commands
* to Debezium. Signaling is disabled when not set.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: oracle
*
* @param signalDataCollection the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder signalDataCollection(java.lang.String signalDataCollection) {
doSetProperty("signalDataCollection", signalDataCollection);
return this;
}
/**
* List of channels names that are enabled. Source channel is enabled by
* default.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: source
* Group: oracle
*
* @param signalEnabledChannels the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder signalEnabledChannels(java.lang.String signalEnabledChannels) {
doSetProperty("signalEnabledChannels", signalEnabledChannels);
return this;
}
/**
* Interval for looking for new signals in registered channels, given in
* milliseconds. Defaults to 5 seconds.
*
* The option is a: <code>long</code> type.
*
* Default: 5s
* Group: oracle
*
* @param signalPollIntervalMs the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder signalPollIntervalMs(long signalPollIntervalMs) {
doSetProperty("signalPollIntervalMs", signalPollIntervalMs);
return this;
}
/**
* The comma-separated list of operations to skip during streaming,
* defined as: 'c' for inserts/create; 'u' for updates; 'd' for deletes,
* 't' for truncates, and 'none' to indicate nothing skipped. By
* default, only truncate operations will be skipped.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: t
* Group: oracle
*
* @param skippedOperations the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder skippedOperations(java.lang.String skippedOperations) {
doSetProperty("skippedOperations", skippedOperations);
return this;
}
/**
* The number of attempts to retry database errors during snapshots
* before failing.
*
* The option is a: <code>int</code> type.
*
* Group: oracle
*
* @param snapshotDatabaseErrorsMaxRetries the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotDatabaseErrorsMaxRetries(int snapshotDatabaseErrorsMaxRetries) {
doSetProperty("snapshotDatabaseErrorsMaxRetries", snapshotDatabaseErrorsMaxRetries);
return this;
}
/**
* A delay period before a snapshot will begin, given in milliseconds.
* Defaults to 0 ms.
*
* The option is a: <code>long</code> type.
*
* Default: 0ms
* Group: oracle
*
* @param snapshotDelayMs the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotDelayMs(long snapshotDelayMs) {
doSetProperty("snapshotDelayMs", snapshotDelayMs);
return this;
}
/**
* The maximum number of records that should be loaded into memory while
* performing a snapshot.
*
* The option is a: <code>int</code> type.
*
* Group: oracle
*
* @param snapshotFetchSize the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotFetchSize(int snapshotFetchSize) {
doSetProperty("snapshotFetchSize", snapshotFetchSize);
return this;
}
/**
* This setting must be set to specify a list of tables/collections
* whose snapshot must be taken on creating or restarting the connector.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: oracle
*
* @param snapshotIncludeCollectionList the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotIncludeCollectionList(java.lang.String snapshotIncludeCollectionList) {
doSetProperty("snapshotIncludeCollectionList", snapshotIncludeCollectionList);
return this;
}
/**
* Controls how the connector holds locks on tables while performing the
* schema snapshot. The default is 'shared', which means the connector
* will hold a table lock that prevents exclusive table access for just
* the initial portion of the snapshot while the database schemas and
* other metadata are being read. The remaining work in a snapshot
* involves selecting all rows from each table, and this is done using a
* flashback query that requires no locks. However, in some cases it may
* be desirable to avoid locks entirely which can be done by specifying
* 'none'. This mode is only safe to use if no schema changes are
* happening while the snapshot is taken.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: shared
* Group: oracle
*
* @param snapshotLockingMode the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotLockingMode(java.lang.String snapshotLockingMode) {
doSetProperty("snapshotLockingMode", snapshotLockingMode);
return this;
}
/**
* The maximum number of millis to wait for table locks at the beginning
* of a snapshot. If locks cannot be acquired in this time frame, the
* snapshot will be aborted. Defaults to 10 seconds.
*
* The option is a: <code>long</code> type.
*
* Default: 10s
* Group: oracle
*
* @param snapshotLockTimeoutMs the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotLockTimeoutMs(long snapshotLockTimeoutMs) {
doSetProperty("snapshotLockTimeoutMs", snapshotLockTimeoutMs);
return this;
}
/**
* The maximum number of threads used to perform the snapshot. Defaults
* to 1.
*
* The option is a: <code>int</code> type.
*
* Default: 1
* Group: oracle
*
* @param snapshotMaxThreads the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotMaxThreads(int snapshotMaxThreads) {
doSetProperty("snapshotMaxThreads", snapshotMaxThreads);
return this;
}
/**
* The criteria for running a snapshot upon startup of the connector.
* Select one of the following snapshot options: 'always': The connector
* runs a snapshot every time that it starts. After the snapshot
* completes, the connector begins to stream changes from the redo
* logs.; 'initial' (default): If the connector does not detect any
* offsets for the logical server name, it runs a snapshot that captures
* the current full state of the configured tables. After the snapshot
* completes, the connector begins to stream changes from the redo logs.
* 'initial_only': The connector performs a snapshot as it does for the
* 'initial' option, but after the connector completes the snapshot, it
* stops, and does not stream changes from the redo logs.;
* 'schema_only': If the connector does not detect any offsets for the
* logical server name, it runs a snapshot that captures only the schema
* (table structures), but not any table data. After the snapshot
* completes, the connector begins to stream changes from the redo
* logs.; 'schema_only_recovery': The connector performs a snapshot that
* captures only the database schema history. The connector then
* transitions to streaming from the redo logs. Use this setting to
* restore a corrupted or lost database schema history topic. Do not use
* if the database schema was modified after the connector stopped.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: initial
* Group: oracle
*
* @param snapshotMode the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotMode(java.lang.String snapshotMode) {
doSetProperty("snapshotMode", snapshotMode);
return this;
}
/**
* When 'snapshot.mode' is set as configuration_based, this setting
* permits to specify whenever the data should be snapshotted or not.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: oracle
*
* @param snapshotModeConfigurationBasedSnapshotData the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotModeConfigurationBasedSnapshotData(boolean snapshotModeConfigurationBasedSnapshotData) {
doSetProperty("snapshotModeConfigurationBasedSnapshotData", snapshotModeConfigurationBasedSnapshotData);
return this;
}
/**
* When 'snapshot.mode' is set as configuration_based, this setting
* permits to specify whenever the data should be snapshotted or not in
* case of error.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: oracle
*
* @param snapshotModeConfigurationBasedSnapshotOnDataError the value to
* set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotModeConfigurationBasedSnapshotOnDataError(boolean snapshotModeConfigurationBasedSnapshotOnDataError) {
doSetProperty("snapshotModeConfigurationBasedSnapshotOnDataError", snapshotModeConfigurationBasedSnapshotOnDataError);
return this;
}
/**
* When 'snapshot.mode' is set as configuration_based, this setting
* permits to specify whenever the schema should be snapshotted or not
* in case of error.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: oracle
*
* @param snapshotModeConfigurationBasedSnapshotOnSchemaError the value
* to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotModeConfigurationBasedSnapshotOnSchemaError(boolean snapshotModeConfigurationBasedSnapshotOnSchemaError) {
doSetProperty("snapshotModeConfigurationBasedSnapshotOnSchemaError", snapshotModeConfigurationBasedSnapshotOnSchemaError);
return this;
}
/**
* When 'snapshot.mode' is set as configuration_based, this setting
* permits to specify whenever the schema should be snapshotted or not.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: oracle
*
* @param snapshotModeConfigurationBasedSnapshotSchema the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotModeConfigurationBasedSnapshotSchema(boolean snapshotModeConfigurationBasedSnapshotSchema) {
doSetProperty("snapshotModeConfigurationBasedSnapshotSchema", snapshotModeConfigurationBasedSnapshotSchema);
return this;
}
/**
* When 'snapshot.mode' is set as configuration_based, this setting
* permits to specify whenever the stream should start or not after
* snapshot.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: oracle
*
* @param snapshotModeConfigurationBasedStartStream the value to set
* @return the dsl builder
*/
default DebeziumOracleComponentBuilder snapshotModeConfigurationBasedStartStream(boolean snapshotModeConfigurationBasedStartStream) {
doSetProperty("snapshotModeConfigurationBasedStartStream", snapshotModeConfigurationBasedStartStream);
return this;
}
/**
* When 'snapshot.mode' is set as custom, this setting must be set to
* specify a the name of the custom implementation provided in the
* 'name()' method. The implementations must implement the 'Snapshotter'
* | that |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleFormatTest.java | {
"start": 739,
"end": 953
} | class ____ extends TestCase {
public void test_formatOracle() {
String sql = SQLUtils.formatOracle("select substr('123''''a''''bc',0,3) FROM dual");
System.out.println(sql);
}
}
| OracleFormatTest |
java | apache__dubbo | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ReferenceBuilder.java | {
"start": 2124,
"end": 4670
} | interface ____
*
* @since 2.7.8
*/
private String services;
public static <T> ReferenceBuilder<T> newBuilder() {
return new ReferenceBuilder<>();
}
public ReferenceBuilder<T> id(String id) {
return super.id(id);
}
public ReferenceBuilder<T> interfaceName(String interfaceName) {
this.interfaceName = interfaceName;
return getThis();
}
public ReferenceBuilder<T> interfaceClass(Class<?> interfaceClass) {
this.interfaceClass = interfaceClass;
return getThis();
}
public ReferenceBuilder<T> client(String client) {
this.client = client;
return getThis();
}
public ReferenceBuilder<T> url(String url) {
this.url = url;
return getThis();
}
public ReferenceBuilder<T> addMethods(List<MethodConfig> methods) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.addAll(methods);
return getThis();
}
public ReferenceBuilder<T> addMethod(MethodConfig method) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.add(method);
return getThis();
}
public ReferenceBuilder<T> consumer(ConsumerConfig consumer) {
this.consumer = consumer;
return getThis();
}
public ReferenceBuilder<T> protocol(String protocol) {
this.protocol = protocol;
return getThis();
}
/**
* @param service one service name
* @param otherServices other service names
* @return {@link ReferenceBuilder}
* @since 2.7.8
*/
public ReferenceBuilder<T> services(String service, String... otherServices) {
this.services = toCommaDelimitedString(service, otherServices);
return getThis();
}
@Override
public ReferenceConfig<T> build() {
ReferenceConfig<T> reference = new ReferenceConfig<>();
super.build(reference);
reference.setInterface(interfaceName);
if (interfaceClass != null) {
reference.setInterface(interfaceClass);
}
reference.setClient(client);
reference.setUrl(url);
reference.setMethods(methods);
reference.setConsumer(consumer);
reference.setProtocol(protocol);
// @since 2.7.8
reference.setServices(services);
return reference;
}
@Override
protected ReferenceBuilder<T> getThis() {
return this;
}
}
| subscribed |
java | apache__camel | components/camel-telemetry/src/main/java/org/apache/camel/telemetry/Span.java | {
"start": 1026,
"end": 1212
} | interface ____ {
void log(Map<String, String> fields);
void setTag(String key, String value);
void setComponent(String component);
void setError(boolean isError);
}
| Span |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/server/header/PermissionsPolicyServerHttpHeadersWriter.java | {
"start": 1115,
"end": 2025
} | class ____ implements ServerHttpHeadersWriter {
public static final String PERMISSIONS_POLICY = "Permissions-Policy";
private @Nullable ServerHttpHeadersWriter delegate;
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty();
}
private static ServerHttpHeadersWriter createDelegate(String policyDirectives) {
Builder builder = StaticServerHttpHeadersWriter.builder();
builder.header(PERMISSIONS_POLICY, policyDirectives);
return builder.build();
}
/**
* Set the policy to be used in the response header.
* @param policy the policy
* @throws IllegalArgumentException if policy is {@code null}
*/
public void setPolicy(String policy) {
Assert.notNull(policy, "policy must not be null");
this.delegate = createDelegate(policy);
}
}
| PermissionsPolicyServerHttpHeadersWriter |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/metrics/AbstractReporterSetup.java | {
"start": 1483,
"end": 3614
} | class ____<REPORTER, REPORTED> {
protected static final Logger LOG = LoggerFactory.getLogger(AbstractReporterSetup.class);
protected final String name;
protected final MetricConfig configuration;
protected final REPORTER reporter;
protected final ReporterFilter<REPORTED> filter;
protected final Map<String, String> additionalVariables;
public AbstractReporterSetup(
final String name,
final MetricConfig configuration,
REPORTER reporter,
ReporterFilter<REPORTED> filter,
final Map<String, String> additionalVariables) {
this.name = name;
this.configuration = configuration;
this.reporter = reporter;
this.filter = filter;
this.additionalVariables = additionalVariables;
}
public Map<String, String> getAdditionalVariables() {
return additionalVariables;
}
public String getName() {
return name;
}
@VisibleForTesting
MetricConfig getConfiguration() {
return configuration;
}
public REPORTER getReporter() {
return reporter;
}
public ReporterFilter<REPORTED> getFilter() {
return filter;
}
public Optional<String> getDelimiter() {
return Optional.ofNullable(configuration.getString(getDelimiterConfigOption().key(), null));
}
public Set<String> getExcludedVariables() {
String excludedVariablesList =
configuration.getString(getExcludedVariablesConfigOption().key(), null);
if (excludedVariablesList == null) {
return Collections.emptySet();
} else {
final Set<String> excludedVariables = new HashSet<>();
for (String exclusion : excludedVariablesList.split(";")) {
excludedVariables.add(ScopeFormat.asVariable(exclusion));
}
return Collections.unmodifiableSet(excludedVariables);
}
}
protected abstract ConfigOption<String> getDelimiterConfigOption();
protected abstract ConfigOption<String> getExcludedVariablesConfigOption();
}
| AbstractReporterSetup |
java | alibaba__nacos | istio/src/main/java/com/alibaba/nacos/istio/model/DestinationRule.java | {
"start": 865,
"end": 1362
} | class ____ {
private String name;
private String namespace;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
}
public static | Metadata |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/testkit/engine/EngineDiscoveryResultsIntegrationTests.java | {
"start": 2456,
"end": 3506
} | enum ____ {
STATIC_METHOD {
@Override
EngineDiscoveryResults discover(String engineId, DiscoverySelector selector) {
return EngineTestKit.discover(engineId, newRequest().selectors(selector).build());
}
@Override
EngineDiscoveryResults discover(TestEngine testEngine) {
return EngineTestKit.discover(testEngine, newRequest().build());
}
private static LauncherDiscoveryRequestBuilder newRequest() {
return request().enableImplicitConfigurationParameters(false);
}
},
FLUENT_API {
@Override
EngineDiscoveryResults discover(String engineId, DiscoverySelector selector) {
return EngineTestKit.engine(engineId).selectors(selector).discover();
}
@Override
EngineDiscoveryResults discover(TestEngine testEngine) {
return EngineTestKit.engine(testEngine).discover();
}
};
@SuppressWarnings("SameParameterValue")
abstract EngineDiscoveryResults discover(String engineId, DiscoverySelector selector);
abstract EngineDiscoveryResults discover(TestEngine testEngine);
}
}
| TestKitApi |
java | apache__spark | sql/hive-thriftserver/src/main/java/org/apache/hive/service/auth/HiveAuthFactory.java | {
"start": 2369,
"end": 2498
} | class ____ {
private static final SparkLogger LOG = SparkLoggerFactory.getLogger(HiveAuthFactory.class);
public | HiveAuthFactory |
java | spring-projects__spring-security | webauthn/src/main/java/org/springframework/security/web/webauthn/jackson/PublicKeyCredentialTypeJackson2Deserializer.java | {
"start": 1341,
"end": 1823
} | class ____ extends StdDeserializer<PublicKeyCredentialType> {
/**
* Creates a new instance.
*/
PublicKeyCredentialTypeJackson2Deserializer() {
super(PublicKeyCredentialType.class);
}
@Override
public PublicKeyCredentialType deserialize(JsonParser parser, DeserializationContext ctxt)
throws IOException, JacksonException {
String type = parser.readValueAs(String.class);
return PublicKeyCredentialType.valueOf(type);
}
}
| PublicKeyCredentialTypeJackson2Deserializer |
java | google__guava | android/guava-tests/test/com/google/common/collect/ForwardingSetMultimapTest.java | {
"start": 974,
"end": 1994
} | class ____ extends TestCase {
@SuppressWarnings("rawtypes")
public void testForwarding() {
new ForwardingWrapperTester()
.testForwarding(
SetMultimap.class,
new Function<SetMultimap, SetMultimap<?, ?>>() {
@Override
public SetMultimap<?, ?> apply(SetMultimap delegate) {
return wrap((SetMultimap<?, ?>) delegate);
}
});
}
public void testEquals() {
SetMultimap<Integer, String> map1 = ImmutableSetMultimap.of(1, "one");
SetMultimap<Integer, String> map2 = ImmutableSetMultimap.of(2, "two");
new EqualsTester()
.addEqualityGroup(map1, wrap(map1), wrap(map1))
.addEqualityGroup(map2, wrap(map2))
.testEquals();
}
private static <K, V> SetMultimap<K, V> wrap(SetMultimap<K, V> delegate) {
return new ForwardingSetMultimap<K, V>() {
@Override
protected SetMultimap<K, V> delegate() {
return delegate;
}
};
}
}
| ForwardingSetMultimapTest |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java | {
"start": 11754,
"end": 12765
} | interface ____<C, A> {
/**
* Determine if the given callback matches and should be invoked.
* @param callbackType the callback type (the functional interface)
* @param callbackInstance the callback instance (the implementation)
* @param argument the primary argument
* @param additionalArguments any additional arguments
* @return if the callback matches and should be invoked
*/
boolean match(Class<C> callbackType, C callbackInstance, A argument,
@Nullable Object @Nullable [] additionalArguments);
/**
* Return a {@link Filter} that allows all callbacks to be invoked.
* @param <C> the callback type
* @param <A> the primary argument type
* @return an "allow all" filter
*/
static <C, A> Filter<C, A> allowAll() {
return (callbackType, callbackInstance, argument, additionalArguments) -> true;
}
}
/**
* {@link Filter} that matches when the callback has a single generic and primary
* argument is an instance of it.
*/
private static final | Filter |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/GzipCodec.java | {
"start": 4810,
"end": 4992
} | class ____ extends ZlibDecompressor {
public GzipZlibDecompressor() {
super(ZlibDecompressor.CompressionHeader.AUTODETECT_GZIP_ZLIB, 64*1024);
}
}
}
| GzipZlibDecompressor |
java | apache__camel | core/camel-base/src/main/java/org/apache/camel/impl/event/ExchangeFailedEvent.java | {
"start": 947,
"end": 1639
} | class ____ extends AbstractExchangeEvent implements CamelEvent.ExchangeFailedEvent {
private static final @Serial long serialVersionUID = -8484326904627268101L;
public ExchangeFailedEvent(Exchange source) {
super(source);
}
@Override
public Throwable getCause() {
return getExchange().getException();
}
@Override
public final String toString() {
Exception cause = getExchange().getException();
if (cause != null) {
return getExchange().getExchangeId() + " exchange failed due to: " + cause;
} else {
return getExchange().getExchangeId() + " exchange failed";
}
}
}
| ExchangeFailedEvent |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/acl/AccessControlEntryData.java | {
"start": 893,
"end": 997
} | class ____ contains the data stored in AccessControlEntry and
* AccessControlEntryFilter objects.
*/
| which |
java | spring-projects__spring-boot | loader/spring-boot-loader/src/test/java/org/springframework/boot/loader/zip/DataBlockInputStreamTests.java | {
"start": 1135,
"end": 4335
} | class ____ {
private ByteArrayDataBlock dataBlock;
private InputStream inputStream;
@BeforeEach
void setup() throws Exception {
this.dataBlock = new ByteArrayDataBlock(new byte[] { 0, 1, 2 });
this.inputStream = this.dataBlock.asInputStream();
}
@Test
void readSingleByteReadsByte() throws Exception {
assertThat(this.inputStream.read()).isEqualTo(0);
assertThat(this.inputStream.read()).isEqualTo(1);
assertThat(this.inputStream.read()).isEqualTo(2);
assertThat(this.inputStream.read()).isEqualTo(-1);
}
@Test
void readByteArrayWhenNotOpenThrowsException() throws Exception {
byte[] bytes = new byte[10];
this.inputStream.close();
assertThatIOException().isThrownBy(() -> this.inputStream.read(bytes)).withMessage("InputStream closed");
}
@Test
void readByteArrayWhenReadingMultipleTimesReadsBytes() throws Exception {
byte[] bytes = new byte[3];
assertThat(this.inputStream.read(bytes, 0, 2)).isEqualTo(2);
assertThat(this.inputStream.read(bytes, 2, 1)).isEqualTo(1);
assertThat(bytes).containsExactly(0, 1, 2);
}
@Test
void readByteArrayWhenReadingMoreThanAvailableReadsRemainingBytes() throws Exception {
byte[] bytes = new byte[5];
assertThat(this.inputStream.read(bytes, 0, 5)).isEqualTo(3);
assertThat(bytes).containsExactly(0, 1, 2, 0, 0);
}
@Test
void skipSkipsBytes() throws Exception {
assertThat(this.inputStream.skip(2)).isEqualTo(2);
assertThat(this.inputStream.read()).isEqualTo(2);
assertThat(this.inputStream.read()).isEqualTo(-1);
}
@Test
void skipWhenSkippingMoreThanRemainingSkipsBytes() throws Exception {
assertThat(this.inputStream.skip(100)).isEqualTo(3);
assertThat(this.inputStream.read()).isEqualTo(-1);
}
@Test
void skipBackwardsSkipsBytes() throws IOException {
assertThat(this.inputStream.skip(2)).isEqualTo(2);
assertThat(this.inputStream.skip(-1)).isEqualTo(-1);
assertThat(this.inputStream.read()).isEqualTo(1);
}
@Test
void skipBackwardsPastBeginningSkipsBytes() throws Exception {
assertThat(this.inputStream.skip(1)).isEqualTo(1);
assertThat(this.inputStream.skip(-100)).isEqualTo(-1);
assertThat(this.inputStream.read()).isEqualTo(0);
}
@Test
void availableReturnsRemainingBytes() throws IOException {
assertThat(this.inputStream.available()).isEqualTo(3);
this.inputStream.read();
assertThat(this.inputStream.available()).isEqualTo(2);
this.inputStream.skip(1);
assertThat(this.inputStream.available()).isEqualTo(1);
}
@Test
void availableWhenClosedReturnsZero() throws IOException {
this.inputStream.close();
assertThat(this.inputStream.available()).isZero();
}
@Test
void closeClosesDataBlock() throws Exception {
this.dataBlock = spy(new ByteArrayDataBlock(new byte[] { 0, 1, 2 }));
this.inputStream = this.dataBlock.asInputStream();
this.inputStream.close();
then(this.dataBlock).should().close();
}
@Test
void closeMultipleTimesClosesDataBlockOnce() throws Exception {
this.dataBlock = spy(new ByteArrayDataBlock(new byte[] { 0, 1, 2 }));
this.inputStream = this.dataBlock.asInputStream();
this.inputStream.close();
this.inputStream.close();
then(this.dataBlock).should(times(1)).close();
}
}
| DataBlockInputStreamTests |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/security/NMTokenSecretManagerInRM.java | {
"start": 6257,
"end": 9246
} | class ____ extends TimerTask {
@Override
public void run() {
// Activation will happen after an absolute time interval. It will be good
// if we can force activation after an NM updates and acknowledges a
// roll-over. But that is only possible when we move to per-NM keys. TODO:
activateNextMasterKey();
}
}
public NMToken createAndGetNMToken(String applicationSubmitter,
ApplicationAttemptId appAttemptId, Container container) {
this.writeLock.lock();
try {
HashSet<NodeId> nodeSet = this.appAttemptToNodeKeyMap.get(appAttemptId);
NMToken nmToken = null;
if (nodeSet != null) {
if (!nodeSet.contains(container.getNodeId())) {
LOG.debug("Sending NMToken for nodeId : {} for container : {}",
container.getNodeId(), container.getId());
Token token =
createNMToken(container.getId().getApplicationAttemptId(),
container.getNodeId(), applicationSubmitter);
nmToken = NMToken.newInstance(container.getNodeId(), token);
nodeSet.add(container.getNodeId());
}
}
return nmToken;
} finally {
this.writeLock.unlock();
}
}
public void registerApplicationAttempt(ApplicationAttemptId appAttemptId) {
this.writeLock.lock();
try {
this.appAttemptToNodeKeyMap.put(appAttemptId, new HashSet<NodeId>());
} finally {
this.writeLock.unlock();
}
}
@Private
@VisibleForTesting
public boolean isApplicationAttemptRegistered(
ApplicationAttemptId appAttemptId) {
this.readLock.lock();
try {
return this.appAttemptToNodeKeyMap.containsKey(appAttemptId);
} finally {
this.readLock.unlock();
}
}
@Private
@VisibleForTesting
public boolean isApplicationAttemptNMTokenPresent(
ApplicationAttemptId appAttemptId, NodeId nodeId) {
this.readLock.lock();
try {
HashSet<NodeId> nodes = this.appAttemptToNodeKeyMap.get(appAttemptId);
if (nodes != null && nodes.contains(nodeId)) {
return true;
} else {
return false;
}
} finally {
this.readLock.unlock();
}
}
public void unregisterApplicationAttempt(ApplicationAttemptId appAttemptId) {
this.writeLock.lock();
try {
this.appAttemptToNodeKeyMap.remove(appAttemptId);
} finally {
this.writeLock.unlock();
}
}
/**
* This is to be called when NodeManager reconnects or goes down. This will
* remove if NMTokens if present for any running application from cache.
* @param nodeId Node Id.
*/
public void removeNodeKey(NodeId nodeId) {
this.writeLock.lock();
try {
Iterator<HashSet<NodeId>> appNodeKeySetIterator =
this.appAttemptToNodeKeyMap.values().iterator();
while (appNodeKeySetIterator.hasNext()) {
appNodeKeySetIterator.next().remove(nodeId);
}
} finally {
this.writeLock.unlock();
}
}
}
| NextKeyActivator |
java | spring-projects__spring-boot | core/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java | {
"start": 4410,
"end": 4515
} | interface ____ {
}
@Configuration(proxyBeanMethods = false)
@AutoConfigurationPackage
static | Unrelated2 |
java | quarkusio__quarkus | extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/ReflectiveClassForValueSerializerPayloadTest.java | {
"start": 8762,
"end": 8974
} | class ____ extends JsonbSerializer<JsonbDto> {
@Override
public byte[] serialize(String topic, Headers headers, JsonbDto data) {
return null;
}
}
static | JsonbDtoSerializer |
java | dropwizard__dropwizard | dropwizard-hibernate/src/main/java/io/dropwizard/hibernate/UnitOfWork.java | {
"start": 740,
"end": 1854
} | interface ____ {
/**
* If {@code true}, the Hibernate session will default to loading read-only entities.
*
* @see org.hibernate.Session#setDefaultReadOnly(boolean)
*/
boolean readOnly() default false;
/**
* If {@code true}, a transaction will be automatically started before the resource method is
* invoked, committed if the method returned, and rolled back if an exception was thrown.
*/
boolean transactional() default true;
/**
* The {@link CacheMode} for the session.
*
* @see CacheMode
* @see org.hibernate.Session#setCacheMode(CacheMode)
*/
CacheMode cacheMode() default CacheMode.NORMAL;
/**
* The {@link FlushMode} for the session.
*
* @see FlushMode
* @see org.hibernate.Session#setFlushMode(org.hibernate.FlushMode)
*/
FlushMode flushMode() default FlushMode.AUTO;
/**
* The name of a hibernate bundle (session factory) that specifies
* a datasource against which a transaction will be opened.
*/
String value() default HibernateBundle.DEFAULT_NAME;
}
| UnitOfWork |
java | apache__maven | api/maven-api-core/src/main/java/org/apache/maven/api/services/ArtifactResolverResult.java | {
"start": 2983,
"end": 4822
} | interface ____ {
/**
* Returns the coordinates of the resolved artifact.
*
* @return The {@link ArtifactCoordinates} of the artifact.
*/
ArtifactCoordinates getCoordinates();
/**
* Returns the resolved artifact.
*
* @return The {@link DownloadedArtifact} instance.
*/
DownloadedArtifact getArtifact();
/**
* Returns a mapping of repositories to the exceptions encountered while resolving the artifact.
*
* @return A {@link Map} where keys are {@link Repository} instances and values are {@link Exception} instances.
*/
Map<Repository, List<Exception>> getExceptions();
/**
* Returns the repository from which the artifact was resolved.
*
* @return The {@link Repository} instance.
*/
Repository getRepository();
/**
* Returns the file system path to the resolved artifact.
*
* @return The {@link Path} to the artifact.
*/
Path getPath();
/**
* Indicates whether the requested artifact was resolved. Note that the artifact might have been successfully
* resolved despite {@link #getExceptions()} indicating transfer errors while trying to fetch the artifact from some
* of the specified remote repositories.
*
* @return {@code true} if the artifact was resolved, {@code false} otherwise.
*/
boolean isResolved();
/**
* Indicates whether the requested artifact is not present in any of the specified repositories.
*
* @return {@code true} if the artifact is not present in any repository, {@code false} otherwise.
*/
boolean isMissing();
}
}
| ResultItem |
java | apache__flink | flink-clients/src/main/java/org/apache/flink/client/deployment/application/EntryClassInformationProvider.java | {
"start": 1518,
"end": 1598
} | class ____ cannot
* be provided.
*
* @return The name of the job | name |
java | apache__kafka | connect/api/src/main/java/org/apache/kafka/connect/errors/SchemaProjectorException.java | {
"start": 962,
"end": 1288
} | class ____ extends DataException {
public SchemaProjectorException(String s) {
super(s);
}
public SchemaProjectorException(String s, Throwable throwable) {
super(s, throwable);
}
public SchemaProjectorException(Throwable throwable) {
super(throwable);
}
}
| SchemaProjectorException |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/BasicTypeSerializerUpgradeTestSpecifications.java | {
"start": 18205,
"end": 18623
} | class ____
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Float> {
@Override
public TypeSerializer<Float> createPriorSerializer() {
return FloatSerializer.INSTANCE;
}
@Override
public Float createTestData() {
return new Float("123.456");
}
}
/** FloatSerializerVerifier. */
public static final | FloatSerializerSetup |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/schemafilter/CatalogFilterTest.java | {
"start": 5334,
"end": 5588
} | class ____ {
@Id
private long id;
public long getId() {
return id;
}
public void setId( long id ) {
this.id = id;
}
}
@Entity
@jakarta.persistence.Table(name = "the_entity_2", catalog = "the_catalog_1")
public static | Catalog1Entity1 |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedStructEmbeddableTest.java | {
"start": 3406,
"end": 23674
} | class ____ implements AdditionalMappingContributor {
@Override
public void contribute(
AdditionalMappingContributions contributions,
InFlightMetadataCollector metadata,
ResourceStreamLocator resourceStreamLocator,
MetadataBuildingContext buildingContext) {
final Namespace namespace = new Namespace(
PhysicalNamingStrategyStandardImpl.INSTANCE,
null,
new Namespace.Name( null, null )
);
//---------------------------------------------------------
// PostgreSQL
//---------------------------------------------------------
contributions.contributeAuxiliaryDatabaseObject(
new NamedAuxiliaryDatabaseObject(
"PostgreSQL structFunction",
namespace,
"create function structFunction() returns theStruct as $$ declare result theStruct; struct structType; begin struct.theBinary = bytea '\\x01'; struct.theString = 'ABC'; struct.theDouble = 0; struct.theInt = 0; struct.theLocalDateTime = timestamp '2022-12-01 01:00:00'; struct.theUuid = '53886a8a-7082-4879-b430-25cb94415be8'::uuid; result.nested = struct; return result; end $$ language plpgsql",
"drop function structFunction",
Set.of( PostgreSQLDialect.class.getName() )
)
);
contributions.contributeAuxiliaryDatabaseObject(
new NamedAuxiliaryDatabaseObject(
"PostgreSQL structProcedure",
namespace,
"create procedure structProcedure(INOUT result theStruct) AS $$ declare nested structType; begin nested.theBinary = bytea '\\x01'; nested.theString = 'ABC'; nested.theDouble = 0; nested.theInt = 0; nested.theLocalDateTime = timestamp '2022-12-01 01:00:00'; nested.theUuid = '53886a8a-7082-4879-b430-25cb94415be8'::uuid; result.nested = nested; end $$ language plpgsql",
"drop procedure structProcedure",
Set.of( PostgreSQLDialect.class.getName() )
)
);
//---------------------------------------------------------
// PostgresPlus
//---------------------------------------------------------
contributions.contributeAuxiliaryDatabaseObject(
new NamedAuxiliaryDatabaseObject(
"PostgrePlus structFunction",
namespace,
"create function structFunction() returns theStruct as $$ declare result theStruct; struct structType; begin struct.theBinary = bytea '\\x01'; struct.theString = 'ABC'; struct.theDouble = 0; struct.theInt = 0; struct.theLocalDateTime = timestamp '2022-12-01 01:00:00'; struct.theUuid = '53886a8a-7082-4879-b430-25cb94415be8'::uuid; result.nested = struct; return result; end $$ language plpgsql",
"drop function structFunction",
Set.of( PostgresPlusDialect.class.getName() )
)
);
contributions.contributeAuxiliaryDatabaseObject(
new NamedAuxiliaryDatabaseObject(
"PostgrePlus structProcedure",
namespace,
"create procedure structProcedure(result INOUT theStruct) AS $$ declare nested structType; begin nested.theBinary = bytea '\\x01'; nested.theString = 'ABC'; nested.theDouble = 0; nested.theInt = 0; nested.theLocalDateTime = timestamp '2022-12-01 01:00:00'; nested.theUuid = '53886a8a-7082-4879-b430-25cb94415be8'::uuid; result.nested = nested; end $$ language plpgsql",
"drop procedure structProcedure",
Set.of( PostgresPlusDialect.class.getName() )
)
);
//---------------------------------------------------------
// DB2
//---------------------------------------------------------
final String binaryType;
final String binaryLiteralPrefix;
if ( metadata.getDatabase().getDialect().getVersion().isBefore( 11 ) ) {
binaryType = "char(16) for bit data";
binaryLiteralPrefix = "x";
}
else {
binaryType = "binary(16)";
binaryLiteralPrefix = "bx";
}
contributions.contributeAuxiliaryDatabaseObject(
new NamedAuxiliaryDatabaseObject(
"DB2 structFunction",
namespace,
"create function structFunction() returns theStruct language sql RETURN select theStruct()..nested(structType()..theBinary(" + binaryLiteralPrefix + "'01')..theString('ABC')..theDouble(0)..theInt(0)..theLocalDateTime(timestamp '2022-12-01 01:00:00')..theUuid(cast(" + binaryLiteralPrefix + "'" +
// UUID is already in HEX encoding, but we have to remove the dashes
"53886a8a-7082-4879-b430-25cb94415be8".replace( "-", "" )
+ "' as " + binaryType + "))) from (values (1)) t",
"drop function structFunction",
Set.of( DB2Dialect.class.getName() )
)
);
//---------------------------------------------------------
// Oracle
//---------------------------------------------------------
contributions.contributeAuxiliaryDatabaseObject(
new NamedAuxiliaryDatabaseObject(
"Oracle structFunction",
namespace,
"create function structFunction return theStruct is result theStruct; begin " +
"result := theStruct(" +
"stringField => null," +
"integerField => null," +
"doubleNested => null," +
"nested => structType(" +
"theBinary => hextoraw('01')," +
"theString => 'ABC'," +
"theDouble => 0," +
"theInt => 0," +
"theLocalDateTime => timestamp '2022-12-01 01:00:00'," +
"theUuid => hextoraw('53886a8a70824879b43025cb94415be8')," +
"converted_gender => null," +
"gender => null," +
"mutableValue => null," +
"ordinal_gender => null," +
"theBoolean => null," +
"theClob => null," +
"theDate => null," +
"theDuration => null," +
"theInstant => null," +
"theInteger => null," +
"theLocalDate => null," +
"theLocalTime => null," +
"theNumericBoolean => null," +
"theOffsetDateTime => null," +
"theStringBoolean => null," +
"theTime => null," +
"theTimestamp => null," +
"theUrl => null," +
"theZonedDateTime => null" +
")); return result; end;",
"drop function structFunction",
Set.of( OracleDialect.class.getName() )
)
);
contributions.contributeAuxiliaryDatabaseObject(
new NamedAuxiliaryDatabaseObject(
"Oracle structProcedure",
namespace,
"create procedure structProcedure(result OUT theStruct) AS begin " +
"result := theStruct(" +
"stringField => null," +
"integerField => null," +
"doubleNested => null," +
"nested => structType(" +
"theBinary => hextoraw('01')," +
"theString => 'ABC'," +
"theDouble => 0," +
"theInt => 0," +
"theLocalDateTime => timestamp '2022-12-01 01:00:00'," +
"theUuid => hextoraw('53886a8a70824879b43025cb94415be8')," +
"converted_gender => null," +
"gender => null," +
"mutableValue => null," +
"ordinal_gender => null," +
"theBoolean => null," +
"theClob => null," +
"theDate => null," +
"theDuration => null," +
"theInstant => null," +
"theInteger => null," +
"theLocalDate => null," +
"theLocalTime => null," +
"theNumericBoolean => null," +
"theOffsetDateTime => null," +
"theStringBoolean => null," +
"theTime => null," +
"theTimestamp => null," +
"theUrl => null," +
"theZonedDateTime => null" +
")); end;",
"drop procedure structProcedure",
Set.of( OracleDialect.class.getName() )
)
);
}
@BeforeEach
public void setUp(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.persist( new StructHolder( 1L, "XYZ", 10, "String \"<abc>A&B</abc>\"", EmbeddableAggregate.createAggregate1() ) );
session.persist( new StructHolder( 2L, null, 20, "String 'abc'", EmbeddableAggregate.createAggregate2() ) );
}
);
}
@AfterEach
protected void cleanupTest(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
public void testUpdate(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
StructHolder structHolder = session.find( StructHolder.class, 1L );
structHolder.setAggregate( EmbeddableAggregate.createAggregate2() );
session.flush();
session.clear();
structHolder = session.find( StructHolder.class, 1L );
assertEquals( "XYZ", structHolder.struct.stringField );
assertEquals( 10, structHolder.struct.simpleEmbeddable.integerField );
assertStructEquals( EmbeddableAggregate.createAggregate2(), structHolder.getAggregate() );
}
);
}
@Test
public void testFetch(SessionFactoryScope scope) {
scope.inSession(
session -> {
List<StructHolder> structHolders = session.createQuery( "from StructHolder b where b.id = 1", StructHolder.class ).getResultList();
assertEquals( 1, structHolders.size() );
StructHolder structHolder = structHolders.get( 0 );
assertEquals( 1L, structHolder.getId() );
assertEquals( "XYZ", structHolder.struct.stringField );
assertEquals( 10, structHolder.struct.simpleEmbeddable.integerField );
assertEquals( "String \"<abc>A&B</abc>\"", structHolder.struct.simpleEmbeddable.doubleNested.theNested.theLeaf.stringField );
assertStructEquals( EmbeddableAggregate.createAggregate1(), structHolder.getAggregate() );
}
);
}
@Test
public void testFetchNull(SessionFactoryScope scope) {
scope.inSession(
session -> {
List<StructHolder> structHolders = session.createQuery( "from StructHolder b where b.id = 2", StructHolder.class ).getResultList();
assertEquals( 1, structHolders.size() );
StructHolder structHolder = structHolders.get( 0 );
assertEquals( 2L, structHolder.getId() );
assertNull( structHolder.struct.stringField );
assertEquals( 20, structHolder.struct.simpleEmbeddable.integerField );
assertStructEquals( EmbeddableAggregate.createAggregate2(), structHolder.getAggregate() );
}
);
}
@Test
public void testDomainResult(SessionFactoryScope scope) {
scope.inSession(
session -> {
List<TheStruct> structs = session.createQuery( "select b.struct from StructHolder b where b.id = 1", TheStruct.class ).getResultList();
assertEquals( 1, structs.size() );
TheStruct theStruct = structs.get( 0 );
assertEquals( "XYZ", theStruct.stringField );
assertEquals( 10, theStruct.simpleEmbeddable.integerField );
assertEquals( "String \"<abc>A&B</abc>\"", theStruct.simpleEmbeddable.doubleNested.theNested.theLeaf.stringField );
assertStructEquals( EmbeddableAggregate.createAggregate1(), theStruct.nested );
}
);
}
@Test
public void testSelectionItems(SessionFactoryScope scope) {
scope.inSession(
session -> {
List<Tuple> tuples = session.createQuery(
"select " +
"b.struct.nested.theInt," +
"b.struct.nested.theDouble," +
"b.struct.nested.theBoolean," +
"b.struct.nested.theNumericBoolean," +
"b.struct.nested.theStringBoolean," +
"b.struct.nested.theString," +
"b.struct.nested.theInteger," +
"b.struct.nested.theUrl," +
"b.struct.nested.theClob," +
"b.struct.nested.theBinary," +
"b.struct.nested.theDate," +
"b.struct.nested.theTime," +
"b.struct.nested.theTimestamp," +
"b.struct.nested.theInstant," +
"b.struct.nested.theUuid," +
"b.struct.nested.gender," +
"b.struct.nested.convertedGender," +
"b.struct.nested.ordinalGender," +
"b.struct.nested.theDuration," +
"b.struct.nested.theLocalDateTime," +
"b.struct.nested.theLocalDate," +
"b.struct.nested.theLocalTime," +
"b.struct.nested.theZonedDateTime," +
"b.struct.nested.theOffsetDateTime," +
"b.struct.nested.mutableValue," +
"b.struct.simpleEmbeddable," +
"b.struct.simpleEmbeddable.doubleNested," +
"b.struct.simpleEmbeddable.doubleNested.theNested," +
"b.struct.simpleEmbeddable.doubleNested.theNested.theLeaf " +
"from StructHolder b where b.id = 1",
Tuple.class
).getResultList();
assertEquals( 1, tuples.size() );
final Tuple tuple = tuples.get( 0 );
final EmbeddableAggregate struct = new EmbeddableAggregate();
struct.setTheInt( tuple.get( 0, int.class ) );
struct.setTheDouble( tuple.get( 1, Double.class ) );
struct.setTheBoolean( tuple.get( 2, Boolean.class ) );
struct.setTheNumericBoolean( tuple.get( 3, Boolean.class ) );
struct.setTheStringBoolean( tuple.get( 4, Boolean.class ) );
struct.setTheString( tuple.get( 5, String.class ) );
struct.setTheInteger( tuple.get( 6, Integer.class ) );
struct.setTheUrl( tuple.get( 7, URL.class ) );
struct.setTheClob( tuple.get( 8, String.class ) );
struct.setTheBinary( tuple.get( 9, byte[].class ) );
struct.setTheDate( tuple.get( 10, Date.class ) );
struct.setTheTime( tuple.get( 11, Time.class ) );
struct.setTheTimestamp( tuple.get( 12, Timestamp.class ) );
struct.setTheInstant( tuple.get( 13, Instant.class ) );
struct.setTheUuid( tuple.get( 14, UUID.class ) );
struct.setGender( tuple.get( 15, EntityOfBasics.Gender.class ) );
struct.setConvertedGender( tuple.get( 16, EntityOfBasics.Gender.class ) );
struct.setOrdinalGender( tuple.get( 17, EntityOfBasics.Gender.class ) );
struct.setTheDuration( tuple.get( 18, Duration.class ) );
struct.setTheLocalDateTime( tuple.get( 19, LocalDateTime.class ) );
struct.setTheLocalDate( tuple.get( 20, LocalDate.class ) );
struct.setTheLocalTime( tuple.get( 21, LocalTime.class ) );
struct.setTheZonedDateTime( tuple.get( 22, ZonedDateTime.class ) );
struct.setTheOffsetDateTime( tuple.get( 23, OffsetDateTime.class ) );
struct.setMutableValue( tuple.get( 24, MutableValue.class ) );
EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate1(), struct );
SimpleEmbeddable simpleEmbeddable = tuple.get( 25, SimpleEmbeddable.class );
assertEquals( simpleEmbeddable.doubleNested, tuple.get( 26, DoubleNested.class ) );
assertEquals( simpleEmbeddable.doubleNested.theNested, tuple.get( 27, Nested.class ) );
assertEquals( simpleEmbeddable.doubleNested.theNested.theLeaf, tuple.get( 28, Leaf.class ) );
assertEquals( 10, simpleEmbeddable.integerField );
assertEquals( "String \"<abc>A&B</abc>\"", simpleEmbeddable.doubleNested.theNested.theLeaf.stringField );
}
);
}
@Test
public void testDeleteWhere(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.createMutationQuery( "delete StructHolder b where b.struct is not null" ).executeUpdate();
assertNull( session.find( StructHolder.class, 1L ) );
}
);
}
@Test
public void testUpdateAggregate(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.createMutationQuery( "update StructHolder b set b.struct = null" ).executeUpdate();
assertNull( session.find( StructHolder.class, 1L ).getAggregate() );
}
);
}
@Test
public void testUpdateAggregateMember(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.createMutationQuery( "update StructHolder b set b.struct.nested.theString = null" ).executeUpdate();
EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1();
struct.setTheString( null );
assertStructEquals( struct, session.find( StructHolder.class, 1L ).getAggregate() );
}
);
}
@Test
public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.createMutationQuery( "update StructHolder b set b.struct.nested.theString = null, b.struct.nested.theUuid = null" ).executeUpdate();
EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1();
struct.setTheString( null );
struct.setTheUuid( null );
assertStructEquals( struct, session.find( StructHolder.class, 1L ).getAggregate() );
}
);
}
@Test
public void testUpdateAllAggregateMembers(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1();
session.createMutationQuery(
"update StructHolder b set " +
"b.struct.nested.theInt = :theInt," +
"b.struct.nested.theDouble = :theDouble," +
"b.struct.nested.theBoolean = :theBoolean," +
"b.struct.nested.theNumericBoolean = :theNumericBoolean," +
"b.struct.nested.theStringBoolean = :theStringBoolean," +
"b.struct.nested.theString = :theString," +
"b.struct.nested.theInteger = :theInteger," +
"b.struct.nested.theUrl = :theUrl," +
"b.struct.nested.theClob = :theClob," +
"b.struct.nested.theBinary = :theBinary," +
"b.struct.nested.theDate = :theDate," +
"b.struct.nested.theTime = :theTime," +
"b.struct.nested.theTimestamp = :theTimestamp," +
"b.struct.nested.theInstant = :theInstant," +
"b.struct.nested.theUuid = :theUuid," +
"b.struct.nested.gender = :gender," +
"b.struct.nested.convertedGender = :convertedGender," +
"b.struct.nested.ordinalGender = :ordinalGender," +
"b.struct.nested.theDuration = :theDuration," +
"b.struct.nested.theLocalDateTime = :theLocalDateTime," +
"b.struct.nested.theLocalDate = :theLocalDate," +
"b.struct.nested.theLocalTime = :theLocalTime," +
"b.struct.nested.theZonedDateTime = :theZonedDateTime," +
"b.struct.nested.theOffsetDateTime = :theOffsetDateTime," +
"b.struct.nested.mutableValue = :mutableValue," +
"b.struct.simpleEmbeddable.integerField = :integerField " +
"where b.id = 2"
)
.setParameter( "theInt", struct.getTheInt() )
.setParameter( "theDouble", struct.getTheDouble() )
.setParameter( "theBoolean", struct.isTheBoolean() )
.setParameter( "theNumericBoolean", struct.isTheNumericBoolean() )
.setParameter( "theStringBoolean", struct.isTheStringBoolean() )
.setParameter( "theString", struct.getTheString() )
.setParameter( "theInteger", struct.getTheInteger() )
.setParameter( "theUrl", struct.getTheUrl() )
.setParameter( "theClob", struct.getTheClob() )
.setParameter( "theBinary", struct.getTheBinary() )
.setParameter( "theDate", struct.getTheDate() )
.setParameter( "theTime", struct.getTheTime() )
.setParameter( "theTimestamp", struct.getTheTimestamp() )
.setParameter( "theInstant", struct.getTheInstant() )
.setParameter( "theUuid", struct.getTheUuid() )
.setParameter( "gender", struct.getGender() )
.setParameter( "convertedGender", struct.getConvertedGender() )
.setParameter( "ordinalGender", struct.getOrdinalGender() )
.setParameter( "theDuration", struct.getTheDuration() )
.setParameter( "theLocalDateTime", struct.getTheLocalDateTime() )
.setParameter( "theLocalDate", struct.getTheLocalDate() )
.setParameter( "theLocalTime", struct.getTheLocalTime() )
.setParameter( "theZonedDateTime", struct.getTheZonedDateTime() )
.setParameter( "theOffsetDateTime", struct.getTheOffsetDateTime() )
.setParameter( "mutableValue", struct.getMutableValue() )
.setParameter( "integerField", 5 )
.executeUpdate();
StructHolder structHolder = session.find( StructHolder.class, 2L );
assertEquals( 5, structHolder.struct.simpleEmbeddable.integerField );
assertStructEquals( EmbeddableAggregate.createAggregate1(), structHolder.getAggregate() );
}
);
}
@Test
public void testNativeQuery(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
//noinspection unchecked
List<Object> resultList = session.createNativeQuery(
"select b.struct from StructHolder b where b.id = 1",
// DB2 does not support structs on the driver level, and we instead do a XML serialization/deserialization
// So in order to receive the correct value, we have to specify the actual type that we expect
scope.getSessionFactory().getJdbcServices().getDialect() instanceof DB2Dialect
? (Class<Object>) (Class<?>) TheStruct.class
// Using Object. | NestedStructEmbeddableTest |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/BasicAnnotationsTest.java | {
"start": 2131,
"end": 2317
} | class ____
{
int _x = 0, _y = 0;
public void setX(int value) { _x = value; }
@JsonProperty("y") void foobar(int value) { _y = value; }
}
static | BaseBean |
java | apache__camel | core/camel-management/src/test/java/org/apache/camel/management/CustomEndpoint.java | {
"start": 1280,
"end": 1467
} | class ____ the mbean server connection cannot access its methods.
*/
// START SNIPPET: e1
@ManagedResource(description = "Our custom managed endpoint")
@DisabledOnOs(OS.AIX)
public | otherwise |
java | elastic__elasticsearch | x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/type/MultiTypeEsField.java | {
"start": 1256,
"end": 1434
} | class ____ be communicated to the data nodes and used during physical planning to influence field extraction so that
* type conversion is done at the data node level.
*/
public | can |
java | alibaba__nacos | api/src/test/java/com/alibaba/nacos/api/ai/model/mcp/McpServerImportRequestTest.java | {
"start": 1062,
"end": 8096
} | class ____ extends BasicRequestTest {
@Test
void testSerializeJsonImport() throws JsonProcessingException {
McpServerImportRequest request = new McpServerImportRequest();
request.setImportType("json");
request.setData("{\"servers\":[{\"name\":\"test-server\"}]}");
request.setOverrideExisting(true);
request.setValidateOnly(false);
request.setSelectedServers(new String[]{"server1", "server2"});
request.setCursor("cursor123");
request.setLimit(10);
request.setSearch("test");
request.setSkipInvalid(true);
String json = mapper.writeValueAsString(request);
assertTrue(json.contains("\"importType\":\"json\""));
assertTrue(json.contains("\"data\":\"{\\\"servers\\\":[{\\\"name\\\":\\\"test-server\\\"}]}\""));
assertTrue(json.contains("\"overrideExisting\":true"));
assertTrue(json.contains("\"validateOnly\":false"));
assertTrue(json.contains("\"selectedServers\":[\"server1\",\"server2\"]"));
assertTrue(json.contains("\"cursor\":\"cursor123\""));
assertTrue(json.contains("\"limit\":10"));
assertTrue(json.contains("\"search\":\"test\""));
assertTrue(json.contains("\"skipInvalid\":true"));
}
@Test
void testSerializeFileImport() throws JsonProcessingException {
McpServerImportRequest request = new McpServerImportRequest();
request.setImportType("file");
request.setData("/path/to/import/file.json");
request.setOverrideExisting(false);
request.setValidateOnly(true);
request.setCursor("cursor456");
request.setLimit(20);
request.setSearch("demo");
request.setSkipInvalid(false);
String json = mapper.writeValueAsString(request);
assertTrue(json.contains("\"importType\":\"file\""));
assertTrue(json.contains("\"data\":\"/path/to/import/file.json\""));
assertTrue(json.contains("\"overrideExisting\":false"));
assertTrue(json.contains("\"validateOnly\":true"));
assertTrue(json.contains("\"cursor\":\"cursor456\""));
assertTrue(json.contains("\"limit\":20"));
assertTrue(json.contains("\"search\":\"demo\""));
assertTrue(json.contains("\"skipInvalid\":false"));
}
@Test
void testSerializeUrlImport() throws JsonProcessingException {
McpServerImportRequest request = new McpServerImportRequest();
request.setImportType("url");
request.setData("https://example.com/mcp-servers.json");
request.setOverrideExisting(false);
request.setValidateOnly(false);
request.setCursor("cursor789");
request.setLimit(30);
request.setSearch("prod");
request.setSkipInvalid(true);
String json = mapper.writeValueAsString(request);
assertTrue(json.contains("\"importType\":\"url\""));
assertTrue(json.contains("\"data\":\"https://example.com/mcp-servers.json\""));
assertTrue(json.contains("\"overrideExisting\":false"));
assertTrue(json.contains("\"validateOnly\":false"));
assertTrue(json.contains("\"cursor\":\"cursor789\""));
assertTrue(json.contains("\"limit\":30"));
assertTrue(json.contains("\"search\":\"prod\""));
assertTrue(json.contains("\"skipInvalid\":true"));
}
@Test
void testDeserializeJsonImport() throws JsonProcessingException {
String json = "{\"importType\":\"json\",\"data\":\"{\\\"servers\\\":[{\\\"name\\\":\\\"test-server\\\"}]}\","
+ "\"overrideExisting\":true,\"validateOnly\":false,\"selectedServers\":[\"server1\",\"server2\"],"
+ "\"cursor\":\"cursor123\",\"limit\":10,\"search\":\"test\",\"skipInvalid\":true}";
McpServerImportRequest result = mapper.readValue(json, McpServerImportRequest.class);
assertNotNull(result);
assertEquals("json", result.getImportType());
assertEquals("{\"servers\":[{\"name\":\"test-server\"}]}", result.getData());
assertTrue(result.isOverrideExisting());
assertFalse(result.isValidateOnly());
assertNotNull(result.getSelectedServers());
assertEquals(2, result.getSelectedServers().length);
assertEquals("server1", result.getSelectedServers()[0]);
assertEquals("server2", result.getSelectedServers()[1]);
assertEquals("cursor123", result.getCursor());
assertEquals(Integer.valueOf(10), result.getLimit());
assertEquals("test", result.getSearch());
assertTrue(result.isSkipInvalid());
}
@Test
void testDeserializeFileImport() throws JsonProcessingException {
String json = "{\"importType\":\"file\",\"data\":\"/path/to/import/file.json\","
+ "\"overrideExisting\":false,\"validateOnly\":true,"
+ "\"cursor\":\"cursor456\",\"limit\":20,\"search\":\"demo\",\"skipInvalid\":false}";
McpServerImportRequest result = mapper.readValue(json, McpServerImportRequest.class);
assertNotNull(result);
assertEquals("file", result.getImportType());
assertEquals("/path/to/import/file.json", result.getData());
assertFalse(result.isOverrideExisting());
assertTrue(result.isValidateOnly());
assertEquals("cursor456", result.getCursor());
assertEquals(Integer.valueOf(20), result.getLimit());
assertEquals("demo", result.getSearch());
assertFalse(result.isSkipInvalid());
}
@Test
void testDeserializeUrlImport() throws JsonProcessingException {
String json = "{\"importType\":\"url\",\"data\":\"https://example.com/mcp-servers.json\","
+ "\"overrideExisting\":false,\"validateOnly\":false,"
+ "\"cursor\":\"cursor789\",\"limit\":30,\"search\":\"prod\",\"skipInvalid\":true}";
McpServerImportRequest result = mapper.readValue(json, McpServerImportRequest.class);
assertNotNull(result);
assertEquals("url", result.getImportType());
assertEquals("https://example.com/mcp-servers.json", result.getData());
assertFalse(result.isOverrideExisting());
assertFalse(result.isValidateOnly());
assertEquals("cursor789", result.getCursor());
assertEquals(Integer.valueOf(30), result.getLimit());
assertEquals("prod", result.getSearch());
assertTrue(result.isSkipInvalid());
}
@Test
void testDefaultValues() throws JsonProcessingException {
String json = "{\"importType\":\"json\",\"data\":\"{}\"}";
McpServerImportRequest result = mapper.readValue(json, McpServerImportRequest.class);
assertNotNull(result);
assertEquals("json", result.getImportType());
assertEquals("{}", result.getData());
assertFalse(result.isOverrideExisting());
assertFalse(result.isValidateOnly());
assertFalse(result.isSkipInvalid());
}
} | McpServerImportRequestTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/VarifierTest.java | {
"start": 7086,
"end": 7422
} | class ____ {
public void trim(String string) {
var unused = string.trim();
}
}
""")
.doTest();
}
@Test
public void assertThrows() {
refactoringHelper
.addInputLines(
"Test.java",
"""
import static org.junit.Assert.assertThrows;
| Test |
java | elastic__elasticsearch | x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/UnresolvedFunction.java | {
"start": 992,
"end": 5573
} | class ____ extends Function implements Unresolvable {
private final String name;
private final String unresolvedMsg;
private final FunctionResolutionStrategy resolution;
/**
* Flag to indicate analysis has been applied and there's no point in
* doing it again this is an optimization to prevent searching for a
* better unresolved message over and over again.
*/
private final boolean analyzed;
public UnresolvedFunction(Source source, String name, FunctionResolutionStrategy resolutionStrategy, List<Expression> children) {
this(source, name, resolutionStrategy, children, false, null);
}
/**
* Constructor used for specifying a more descriptive message (typically
* 'did you mean') instead of the default one.
*
* @see #withMessage(String)
*/
UnresolvedFunction(
Source source,
String name,
FunctionResolutionStrategy resolutionStrategy,
List<Expression> children,
boolean analyzed,
String unresolvedMessage
) {
super(source, children);
this.name = name;
this.resolution = resolutionStrategy;
this.analyzed = analyzed;
this.unresolvedMsg = unresolvedMessage == null ? "Unknown " + resolutionStrategy.kind() + " [" + name + "]" : unresolvedMessage;
}
@Override
protected NodeInfo<UnresolvedFunction> info() {
return NodeInfo.create(this, UnresolvedFunction::new, name, resolution, children(), analyzed, unresolvedMsg);
}
@Override
public Expression replaceChildren(List<Expression> newChildren) {
return new UnresolvedFunction(source(), name, resolution, newChildren, analyzed, unresolvedMsg);
}
public UnresolvedFunction withMessage(String message) {
return new UnresolvedFunction(source(), name(), resolution, children(), true, message);
}
/**
* Build a function to replace this one after resolving the function.
*/
public Function buildResolved(Configuration configuration, FunctionDefinition def) {
return resolution.buildResolved(this, configuration, def);
}
/**
* Build a marker {@link UnresolvedFunction} with an error message
* about the function being missing.
*/
public UnresolvedFunction missing(String normalizedName, Iterable<FunctionDefinition> alternatives) {
// try to find alternatives
Set<String> names = new LinkedHashSet<>();
for (FunctionDefinition def : alternatives) {
if (resolution.isValidAlternative(def)) {
names.add(def.name());
names.addAll(def.aliases());
}
}
List<String> matches = StringUtils.findSimilar(normalizedName, names);
if (matches.isEmpty()) {
return this;
}
String matchesMessage = matches.size() == 1 ? "[" + matches.get(0) + "]" : "any of " + matches;
return withMessage("Unknown " + resolution.kind() + " [" + name + "], did you mean " + matchesMessage + "?");
}
@Override
public boolean resolved() {
return false;
}
public String name() {
return name;
}
public FunctionResolutionStrategy resolutionStrategy() {
return resolution;
}
public boolean analyzed() {
return analyzed;
}
@Override
public DataType dataType() {
throw new UnresolvedException("dataType", this);
}
@Override
public Nullability nullable() {
throw new UnresolvedException("nullable", this);
}
@Override
public ScriptTemplate asScript() {
throw new UnresolvedException("script", this);
}
@Override
public String unresolvedMessage() {
return unresolvedMsg;
}
@Override
public String toString() {
return UNRESOLVED_PREFIX + name + children();
}
@Override
public String nodeString() {
return toString();
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) {
return false;
}
UnresolvedFunction other = (UnresolvedFunction) obj;
return name.equals(other.name)
&& resolution.equals(other.resolution)
&& children().equals(other.children())
&& analyzed == other.analyzed
&& Objects.equals(unresolvedMsg, other.unresolvedMsg);
}
@Override
public int hashCode() {
return Objects.hash(name, resolution, children(), analyzed, unresolvedMsg);
}
}
| UnresolvedFunction |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/annotations/ListIndexJavaType.java | {
"start": 750,
"end": 909
} | interface ____ {
/**
* The descriptor to use for the list-index
*
* @see JavaType#value
*/
Class<? extends BasicJavaType<?>> value();
}
| ListIndexJavaType |
java | quarkusio__quarkus | extensions/redis-client/runtime/src/main/java/io/quarkus/redis/runtime/datasource/ReactivePubSubCommandsImpl.java | {
"start": 13983,
"end": 15400
} | class ____ extends AbstractRedisSubscriber implements ReactiveRedisSubscriber {
private final List<String> channels;
public ReactiveAbstractRedisSubscriberImpl(RedisConnection connection, RedisAPI api, List<String> channels,
BiConsumer<String, V> onMessage, Runnable onEnd,
Consumer<Throwable> onException) {
super(connection, api, onMessage, onEnd, onException);
this.channels = new ArrayList<>(channels);
}
@Override
Uni<Void> subscribeToRedis() {
return api.subscribe(channels).replaceWithVoid();
}
@Override
public Uni<Void> unsubscribe(String... channels) {
notNullOrEmpty(channels, "channels");
doesNotContainNull(channels, "channels");
List<String> list = List.of(channels);
return api.unsubscribe(list)
.chain(() -> {
this.channels.removeAll(list);
return closeAndUnregister(this.channels);
});
}
@Override
public Uni<Void> unsubscribe() {
return api.unsubscribe(channels)
.chain(() -> {
this.channels.clear();
return closeAndUnregister(channels);
});
}
}
private | ReactiveAbstractRedisSubscriberImpl |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/EncryptionS3ClientFactory.java | {
"start": 12586,
"end": 12645
} | class ____.
*
* @param className The fully qualified | name |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java | {
"start": 123893,
"end": 128168
} | class ____ via reflection
* since JUnit creates a new instance per test and that is also
* the reason why INSTANCE is static since this entire method
* must be executed in a static context.
*/
assert INSTANCE == null;
if (isSuiteScopedTest(targetClass)) {
// note we need to do this this way to make sure this is reproducible
INSTANCE = (ESIntegTestCase) targetClass.getConstructor().newInstance();
boolean success = false;
try {
INSTANCE.printTestMessage("setup");
INSTANCE.beforeInternal();
INSTANCE.setupSuiteScopeCluster();
success = true;
} finally {
if (success == false) {
afterClass();
}
}
} else {
INSTANCE = null;
}
}
/**
* Compute a routing key that will route documents to the <code>shard</code>-th shard
* of the provided index.
*/
protected String routingKeyForShard(String index, int shard) {
return internalCluster().routingKeyForShard(resolveIndex(index), shard, random());
}
@Override
protected NamedXContentRegistry xContentRegistry() {
if (isInternalCluster() && cluster().size() > 0) {
// If it's internal cluster - using existing registry in case plugin registered custom data
return internalCluster().getInstance(NamedXContentRegistry.class);
} else {
// If it's external cluster - fall back to the standard set
return new NamedXContentRegistry(ClusterModule.getNamedXWriteables());
}
}
protected boolean forbidPrivateIndexSettings() {
return true;
}
/**
* Override to return true in tests that cannot handle multiple data paths.
*/
protected boolean forceSingleDataPath() {
return false;
}
/**
* Returns an instance of {@link RestClient} pointing to the current test cluster.
* Creates a new client if the method is invoked for the first time in the context of the current test scope.
* The returned client gets automatically closed when needed, it shouldn't be closed as part of tests otherwise
* it cannot be reused by other tests anymore.
*/
protected static synchronized RestClient getRestClient() {
if (restClient == null) {
restClient = createRestClient();
}
return restClient;
}
protected static RestClient createRestClient() {
return createRestClient(null, "http");
}
protected static RestClient createRestClient(String node) {
return createRestClient(client(node).admin().cluster().prepareNodesInfo("_local").get().getNodes(), null, "http");
}
protected static RestClient createRestClient(RestClientBuilder.HttpClientConfigCallback httpClientConfigCallback, String protocol) {
NodesInfoResponse nodesInfoResponse = clusterAdmin().prepareNodesInfo().get();
assertFalse(nodesInfoResponse.hasFailures());
return createRestClient(nodesInfoResponse.getNodes(), httpClientConfigCallback, protocol);
}
protected static RestClient createRestClient(
final List<NodeInfo> nodes,
RestClientBuilder.HttpClientConfigCallback httpClientConfigCallback,
String protocol
) {
List<HttpHost> hosts = new ArrayList<>();
for (NodeInfo node : nodes) {
if (node.getInfo(HttpInfo.class) != null) {
TransportAddress publishAddress = node.getInfo(HttpInfo.class).address().publishAddress();
InetSocketAddress address = publishAddress.address();
hosts.add(new HttpHost(NetworkAddress.format(address.getAddress()), address.getPort(), protocol));
}
}
RestClientBuilder builder = RestClient.builder(hosts.toArray(new HttpHost[hosts.size()]));
if (httpClientConfigCallback != null) {
builder.setHttpClientConfigCallback(httpClientConfigCallback);
}
return builder.build();
}
/**
* This method is executed iff the test is annotated with {@link SuiteScopeTestCase}
* before the first test of this | instance |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/locking/options/Book.java | {
"start": 898,
"end": 2778
} | class ____ {
@Id
private Integer id;
@Version
private int revision;
private String title;
private String synopsis;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "publisher_fk")
private Publisher publisher;
@ManyToMany
@JoinTable(name = "book_authors",
joinColumns = @JoinColumn(name = "book_fk"),
inverseJoinColumns = @JoinColumn(name = "author_fk"))
private Set<Person> authors;
@ElementCollection
@CollectionTable(name = "book_genres", joinColumns = @JoinColumn(name = "book_fk"))
@Column(name = "genre")
private Set<String> genres;
protected Book() {
// for Hibernate use
}
public Book(Integer id, String title, String synopsis) {
this( id, title, synopsis, null );
}
public Book(Integer id, String title, String synopsis, Publisher publisher) {
this.id = id;
this.title = title;
this.synopsis = synopsis;
this.publisher = publisher;
}
public Integer getId() {
return id;
}
public int getRevision() {
return revision;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
public Set<Person> getAuthors() {
return authors;
}
public void setAuthors(Set<Person> authors) {
this.authors = authors;
}
public void addAuthor(Person author) {
if ( authors == null ) {
authors = new HashSet<>();
}
authors.add( author );
}
public Set<String> getGenres() {
return genres;
}
public void setGenres(Set<String> genres) {
this.genres = genres;
}
public void addTag(String tag) {
if ( genres == null ) {
genres = new HashSet<>();
}
genres.add( tag );
}
}
| Book |
java | quarkusio__quarkus | extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/telemetry/endpoints/ontextmessage/MultiDtoReceived_SingleDtoResponse_Endpoint.java | {
"start": 272,
"end": 457
} | class ____ {
@OnTextMessage
public String onMessage(Multi<String> message) {
return "ut labore et dolore magna aliqua";
}
}
| MultiDtoReceived_SingleDtoResponse_Endpoint |
java | apache__camel | core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultSupervisingRouteController.java | {
"start": 23742,
"end": 30546
} | class ____ {
private final Logger logger;
private final ConcurrentMap<RouteHolder, BackOffTimer.Task> routes;
private final ConcurrentMap<RouteHolder, BackOffTimer.Task> exhausted;
private final ConcurrentMap<String, Throwable> exceptions;
RouteManager() {
this.logger = LoggerFactory.getLogger(RouteManager.class);
this.routes = new ConcurrentHashMap<>();
this.exhausted = new ConcurrentHashMap<>();
this.exceptions = new ConcurrentHashMap<>();
}
void start(RouteHolder route) {
route.get().setRouteController(DefaultSupervisingRouteController.this);
routes.computeIfAbsent(
route,
r -> {
BackOff backOff = getBackOff(r.getId());
logger.debug("Supervising route: {} with back-off: {}", r.getId(), backOff);
BackOffTimer.Task task = timer.schedule(backOff, context -> {
final BackOffTimer.Task state = getBackOffContext(r.getId()).orElse(null);
long attempt = state != null ? state.getCurrentAttempts() : 0;
if (!getCamelContext().isRunAllowed()) {
// Camel is shutting down so do not attempt to start route
logger.info("Restarting route: {} attempt: {} is cancelled due CamelContext is shutting down",
r.getId(), attempt);
return true;
}
try {
logger.info("Restarting route: {} attempt: {}", r.getId(), attempt);
EventHelper.notifyRouteRestarting(getCamelContext(), r.get(), attempt);
doStartRoute(r, false, rx -> DefaultSupervisingRouteController.super.startRoute(rx.getId()));
logger.info("Route: {} started after {} attempts", r.getId(), attempt);
return false;
} catch (Exception e) {
exceptions.put(r.getId(), e);
String cause = e.getClass().getName() + ": " + e.getMessage();
logger.info("Failed restarting route: {} attempt: {} due: {} (stacktrace in debug log level)",
r.getId(), attempt, cause);
logger.debug(" Error restarting route caused by: {}", e.getMessage(), e);
EventHelper.notifyRouteRestartingFailure(getCamelContext(), r.get(), attempt, e, false);
return true;
}
});
task.whenComplete((backOffTask, throwable) -> {
if (backOffTask == null || backOffTask.getStatus() != BackOffTimer.Task.Status.Active) {
// This indicates that the task has been cancelled
// or that back-off retry is exhausted thus if the
// route is not started it is moved out of the
// supervisor control.
lock.lock();
try {
final ServiceStatus status = route.getStatus();
final boolean stopped = status.isStopped() || status.isStopping();
if (backOffTask != null && backOffTask.getStatus() == BackOffTimer.Task.Status.Exhausted
&& stopped) {
long attempts = backOffTask.getCurrentAttempts() - 1;
LOG.warn(
"Restarting route: {} is exhausted after {} attempts. No more attempts will be made"
+ " and the route is no longer supervised by this route controller and remains as stopped.",
route.getId(), attempts);
r.get().setRouteController(null);
// remember exhausted routes
routeManager.exhausted.put(r, task);
// store as last error on route as it was exhausted
Throwable t = getRestartException(route.getId());
EventHelper.notifyRouteRestartingFailure(getCamelContext(), r.get(), attempts, t, true);
if (unhealthyOnExhausted) {
// store as last error on route as it was exhausted
if (t != null) {
DefaultRouteError.set(getCamelContext(), r.getId(), RouteError.Phase.START, t,
true);
}
}
}
} finally {
lock.unlock();
}
}
routes.remove(r);
});
return task;
});
}
boolean release(RouteHolder route) {
exceptions.remove(route.getId());
BackOffTimer.Task task = routes.remove(route);
if (task != null) {
LOG.debug("Cancelling restart task for route: {}", route.getId());
task.cancel();
}
return task != null;
}
public Optional<BackOffTimer.Task> getBackOffContext(String id) {
Optional<BackOffTimer.Task> answer = routes.entrySet().stream()
.filter(e -> ObjectHelper.equal(e.getKey().getId(), id))
.findFirst()
.map(Map.Entry::getValue);
if (!answer.isPresent()) {
answer = exhausted.entrySet().stream()
.filter(e -> ObjectHelper.equal(e.getKey().getId(), id))
.findFirst()
.map(Map.Entry::getValue);
}
return answer;
}
}
// *********************************
//
// *********************************
private static | RouteManager |
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/docs/server/uris/UriTemplateTest.java | {
"start": 877,
"end": 1272
} | class ____ {
@Test
void testUriTemplate() {
// tag::match[]
UriMatchTemplate template = UriMatchTemplate.of("/hello/{name}");
assertTrue(template.match("/hello/John").isPresent()); // <1>
assertEquals("/hello/John", template.expand( // <2>
Collections.singletonMap("name", "John")
));
// end::match[]
}
}
| UriTemplateTest |
java | spring-projects__spring-boot | module/spring-boot-cache/src/main/java/org/springframework/boot/cache/autoconfigure/Cache2kCacheConfiguration.java | {
"start": 1619,
"end": 2521
} | class ____ {
@Bean
SpringCache2kCacheManager cacheManager(CacheProperties cacheProperties, CacheManagerCustomizers customizers,
ObjectProvider<Cache2kBuilderCustomizer> cache2kBuilderCustomizers) {
SpringCache2kCacheManager cacheManager = new SpringCache2kCacheManager();
cacheManager.defaultSetup(configureDefaults(cache2kBuilderCustomizers));
Collection<String> cacheNames = cacheProperties.getCacheNames();
if (!CollectionUtils.isEmpty(cacheNames)) {
cacheManager.setDefaultCacheNames(cacheNames);
}
return customizers.customize(cacheManager);
}
private Function<Cache2kBuilder<?, ?>, Cache2kBuilder<?, ?>> configureDefaults(
ObjectProvider<Cache2kBuilderCustomizer> cache2kBuilderCustomizers) {
return (builder) -> {
cache2kBuilderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
return builder;
};
}
}
| Cache2kCacheConfiguration |
java | apache__flink | flink-core/src/test/java/org/apache/flink/util/concurrent/ConjunctFutureTest.java | {
"start": 10180,
"end": 10461
} | class ____ implements FutureFactory {
@Override
public ConjunctFuture<?> createFuture(
Collection<? extends java.util.concurrent.CompletableFuture<?>> futures) {
return FutureUtils.waitForAll(futures);
}
}
}
| WaitingFutureFactory |
java | apache__dubbo | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmIntegrationTest.java | {
"start": 1901,
"end": 8347
} | class ____ implements IntegrationTest {
private static final Logger logger = LoggerFactory.getLogger(MultipleRegistryCenterInjvmIntegrationTest.class);
/**
* Define the provider application name.
*/
private static String PROVIDER_APPLICATION_NAME = "multiple-registry-center-provider-for-injvm-protocol";
/**
* The name for getting the specified instance, which is loaded using SPI.
*/
private static String SPI_NAME = "multipleConfigCenterInjvm";
/**
* Define the {@link ServiceConfig} instance.
*/
private ServiceConfig<MultipleRegistryCenterInjvmService> serviceConfig;
/**
* The listener to record exported services
*/
private MultipleRegistryCenterInjvmServiceListener serviceListener;
/**
* The listener to record exported exporters.
*/
private MultipleRegistryCenterInjvmExporterListener exporterListener;
/**
* The filter for checking filter chain.
*/
private MultipleRegistryCenterInjvmFilter filter;
@BeforeEach
public void setUp() throws Exception {
logger.info(getClass().getSimpleName() + " testcase is beginning...");
DubboBootstrap.reset();
// initialize service config
serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(MultipleRegistryCenterInjvmService.class);
serviceConfig.setRef(new MultipleRegistryCenterInjvmServiceImpl());
serviceConfig.setAsync(false);
serviceConfig.setScope(SCOPE_LOCAL);
DubboBootstrap.getInstance()
.application(new ApplicationConfig(PROVIDER_APPLICATION_NAME))
.protocol(new ProtocolConfig("injvm"))
.service(serviceConfig)
.registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1()))
.registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2()));
}
/**
* Define {@link ServiceListener}, {@link ExporterListener} and {@link Filter} for helping check.
* <p>Use SPI to load them before exporting.
* <p>After that, there are some checkpoints need to verify as follow:
* <ul>
* <li>There is nothing in ServiceListener or not</li>
* <li>There is nothing in ExporterListener or not</li>
* <li>ServiceConfig is exported or not</li>
* </ul>
*/
private void beforeExport() {
// ---------------initialize--------------- //
serviceListener = (MultipleRegistryCenterInjvmServiceListener)
ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME);
exporterListener = (MultipleRegistryCenterInjvmExporterListener)
ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME);
filter = (MultipleRegistryCenterInjvmFilter)
ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SPI_NAME);
// ---------------checkpoints--------------- //
// There is nothing in ServiceListener
Assertions.assertTrue(serviceListener.getExportedServices().isEmpty());
// There is nothing in ExporterListener
Assertions.assertTrue(exporterListener.getExportedExporters().isEmpty());
// ServiceConfig isn't exported
Assertions.assertFalse(serviceConfig.isExported());
}
/**
* {@inheritDoc}
*/
@Test
@Override
public void integrate() {
beforeExport();
DubboBootstrap.getInstance().start();
afterExport();
ReferenceConfig<MultipleRegistryCenterInjvmService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(MultipleRegistryCenterInjvmService.class);
referenceConfig.setScope(SCOPE_LOCAL);
referenceConfig.get().hello("Dubbo in multiple registry center");
afterInvoke();
}
/**
* There are some checkpoints need to check after exported as follow:
* <ul>
* <li>The exported service is only one or not</li>
* <li>The exported service is MultipleRegistryCenterInjvmService or not</li>
* <li>The MultipleRegistryCenterInjvmService is exported or not</li>
* <li>The exported exporter is only one or not</li>
* <li>The exported exporter contains MultipleRegistryCenterInjvmFilter or not</li>
* </ul>
*/
private void afterExport() {
// The exported service is only one
Assertions.assertEquals(serviceListener.getExportedServices().size(), 1);
// The exported service is MultipleRegistryCenterInjvmService
Assertions.assertEquals(
serviceListener.getExportedServices().get(0).getInterfaceClass(),
MultipleRegistryCenterInjvmService.class);
// The MultipleRegistryCenterInjvmService is exported
Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported());
// The exported exporter is only one
Assertions.assertEquals(exporterListener.getExportedExporters().size(), 3);
// The exported exporter contains MultipleRegistryCenterInjvmFilter
Assertions.assertTrue(exporterListener.getFilters().contains(filter));
}
/**
* There are some checkpoints need to check after invoked as follow:
* <ul>
* <li>The MultipleRegistryCenterInjvmFilter has called or not</li>
* <li>The MultipleRegistryCenterInjvmFilter exists error after invoked</li>
* <li>The MultipleRegistryCenterInjvmFilter's response is right or not</li>
* </ul>
*/
private void afterInvoke() {
// The MultipleRegistryCenterInjvmFilter has called
Assertions.assertTrue(filter.hasCalled());
// The MultipleRegistryCenterInjvmFilter doesn't exist error
Assertions.assertFalse(filter.hasError());
// Check the MultipleRegistryCenterInjvmFilter's response
Assertions.assertEquals("Hello Dubbo in multiple registry center", filter.getResponse());
}
@AfterEach
public void tearDown() throws IOException {
DubboBootstrap.reset();
serviceConfig = null;
// The exported service has been unexported
Assertions.assertTrue(serviceListener.getExportedServices().isEmpty());
serviceListener = null;
logger.info(getClass().getSimpleName() + " testcase is ending...");
}
}
| MultipleRegistryCenterInjvmIntegrationTest |
java | elastic__elasticsearch | qa/packaging/src/test/java/org/elasticsearch/packaging/util/FileUtils.java | {
"start": 2178,
"end": 15172
} | class ____ {
public static List<Path> lsGlob(Path directory, String glob) {
List<Path> paths = new ArrayList<>();
if (Files.exists(directory) == false) {
return List.of();
}
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory, glob)) {
for (Path path : stream) {
paths.add(path);
}
return paths;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void rm(Path... paths) {
if (Platforms.WINDOWS) {
rmWithRetries(paths);
} else {
try {
IOUtils.rm(paths);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
// windows needs leniency due to asinine releasing of file locking async from a process exiting
private static void rmWithRetries(Path... paths) {
int tries = 10;
IOException exception = null;
while (tries-- > 0) {
try {
IOUtils.rm(paths);
return;
} catch (IOException e) {
if (exception == null) {
exception = e;
} else {
exception.addSuppressed(e);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
return;
}
}
throw new UncheckedIOException(exception);
}
public static Path mktempDir(Path path) {
try {
return Files.createTempDirectory(path, "tmp");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Path mkdir(Path path) {
try {
return Files.createDirectories(path);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Path cp(Path source, Path target) {
try {
return Files.copy(source, target);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Path mv(Path source, Path target) {
try {
return Files.move(source, target);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Creates or appends to the specified file, and writes the supplied string to it.
* No newline is written - if a trailing newline is required, it should be present
* in <code>text</code>, or use {@link Files#write(Path, Iterable, OpenOption...)}.
* @param file the file to create or append
* @param text the string to write
*/
public static void append(Path file, String text) {
try (
BufferedWriter writer = Files.newBufferedWriter(
file,
StandardCharsets.UTF_8,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND
)
) {
writer.write(text);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String slurp(Path file) {
try {
return String.join(System.lineSeparator(), Files.readAllLines(file, StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Returns the content a {@link java.nio.file.Path} file. The file can be in plain text or GZIP format.
* @param file The {@link java.nio.file.Path} to the file.
* @return The content of {@code file}.
*/
public static String slurpTxtorGz(Path file) {
ByteArrayOutputStream fileBuffer = new ByteArrayOutputStream();
try (GZIPInputStream in = new GZIPInputStream(Channels.newInputStream(FileChannel.open(file)))) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
fileBuffer.write(buffer, 0, len);
}
return (new String(fileBuffer.toByteArray(), StandardCharsets.UTF_8));
} catch (ZipException e) {
if (e.toString().contains("Not in GZIP format")) {
return slurp(file);
}
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Returns combined content of a text log file and rotated log files matching a pattern. Order of rotated log files is
* not guaranteed.
* @param logPath Base directory where log files reside.
* @param activeLogFile The currently active log file. This file needs to be plain text under {@code logPath}.
* @param rotatedLogFilesGlob A glob pattern to match rotated log files under {@code logPath}.
* See {@link java.nio.file.FileSystem#getPathMatcher(String)} for glob examples.
* @return Merges contents of {@code activeLogFile} and contents of filenames matching {@code rotatedLogFilesGlob}.
* File contents are separated by a newline. The order of rotated log files matched by {@code rotatedLogFilesGlob} is not guaranteed.
*/
public static String slurpAllLogs(Path logPath, String activeLogFile, String rotatedLogFilesGlob) {
StringJoiner logFileJoiner = new StringJoiner("\n");
try {
logFileJoiner.add(Files.readString(logPath.resolve(activeLogFile)));
for (Path rotatedLogFile : FileUtils.lsGlob(logPath, rotatedLogFilesGlob)) {
logFileJoiner.add(FileUtils.slurpTxtorGz(rotatedLogFile));
}
return (logFileJoiner.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void logAllLogs(Path logsDir, Logger logger) {
if (Files.exists(logsDir) == false) {
logger.warn("Can't show logs from directory {} as it doesn't exists", logsDir);
return;
}
logger.info("Showing contents of directory: {} ({})", logsDir, logsDir.toAbsolutePath());
try (Stream<Path> fileStream = Files.list(logsDir)) {
fileStream
// gc logs are verbose and not useful in this context
.filter(file -> file.getFileName().toString().startsWith("gc.log") == false)
.forEach(file -> {
logger.info("=== Contents of `{}` ({}) ===", file, file.toAbsolutePath());
try (Stream<String> stream = Files.lines(file)) {
stream.forEach(logger::info);
} catch (IOException e) {
logger.error("Can't show contents", e);
}
logger.info("=== End of contents of `{}`===", file);
});
} catch (IOException e) {
logger.error("Can't list log files", e);
}
}
/**
* Gets the owner of a file in a way that should be supported by all filesystems that have a concept of file owner
*/
public static String getFileOwner(Path path) {
try {
FileOwnerAttributeView view = Files.getFileAttributeView(path, FileOwnerAttributeView.class);
return view.getOwner().getName();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Gets attributes that are supported by all filesystems
*/
public static BasicFileAttributes getBasicFileAttributes(Path path) {
try {
return Files.readAttributes(path, BasicFileAttributes.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Gets attributes that are supported by posix filesystems
*/
public static PosixFileAttributes getPosixFileAttributes(Path path) {
try {
return Files.readAttributes(path, PosixFileAttributes.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Gets numeric ownership attributes that are supported by Unix filesystems
* @return a Map of the uid/gid integer values
*/
public static Map<String, Integer> getNumericUnixPathOwnership(Path path) {
Map<String, Integer> numericPathOwnership = new HashMap<>();
try {
numericPathOwnership.put("uid", (int) Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS));
numericPathOwnership.put("gid", (int) Files.getAttribute(path, "unix:gid", LinkOption.NOFOLLOW_LINKS));
} catch (IOException e) {
throw new RuntimeException(e);
}
return numericPathOwnership;
}
public static Path getDefaultArchiveInstallPath() {
return getRootTempDir().resolve("elasticsearch");
}
private static final Pattern VERSION_REGEX = Pattern.compile("(\\d+\\.\\d+\\.\\d+(-SNAPSHOT)?)");
public static String getCurrentVersion() {
// TODO: just load this once
String distroFile = System.getProperty("tests.distribution");
java.util.regex.Matcher matcher = VERSION_REGEX.matcher(distroFile);
if (matcher.find()) {
return matcher.group(1);
}
throw new IllegalStateException("Could not find version in filename: " + distroFile);
}
public static Path getDistributionFile(Distribution distribution) {
return distribution.path;
}
public static void assertPathsExist(final Path... paths) {
Arrays.stream(paths).forEach(path -> assertThat(path, fileExists()));
}
public static Matcher<Path> fileWithGlobExist(String glob) throws IOException {
return new FeatureMatcher<Path, Iterable<Path>>(not(emptyIterable()), "File with pattern exist", "file with pattern") {
@Override
protected Iterable<Path> featureValueOf(Path actual) {
try {
return Files.newDirectoryStream(actual, glob);
} catch (IOException e) {
return Collections.emptyList();
}
}
};
}
public static void assertPathsDoNotExist(final Path... paths) {
Arrays.stream(paths).forEach(path -> assertThat(path, fileDoesNotExist()));
}
public static void deleteIfExists(Path path) {
if (Files.exists(path)) {
try {
Files.delete(path);
} catch (IOException e) {
if (Platforms.WINDOWS) {
// Windows has race conditions with processes exiting and releasing
// files that were opened (eg as redirects of stdout/stderr). Even though
// the process as exited, Windows may still think the files are open.
// Here we give a small delay before retrying.
try {
Thread.sleep(3000);
Files.delete(path);
} catch (InterruptedException ie) {
throw new AssertionError(ie);
} catch (IOException e2) {
e.addSuppressed(e2);
throw new UncheckedIOException("could not delete file on windows after waiting", e);
}
} else {
throw new UncheckedIOException(e);
}
}
}
}
/**
* Return the given path a string suitable for using on the host system.
*/
public static String escapePath(Path path) {
if (Platforms.WINDOWS) {
// replace single backslash with forward slash, to avoid unintended escapes in scripts
return path.toString().replace('\\', '/');
}
return path.toString();
}
/**
* Recursively copy the source directory to the target directory, preserving permissions.
*/
public static void copyDirectory(Path source, Path target) throws IOException {
Files.walkFileTree(source, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
// this won't copy the directory contents, only the directory itself, but we use
// copy to allow copying attributes
Files.copy(dir, target.resolve(source.relativize(dir)), StandardCopyOption.COPY_ATTRIBUTES);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.copy(file, target.resolve(source.relativize(file)), StandardCopyOption.COPY_ATTRIBUTES);
return FileVisitResult.CONTINUE;
}
});
}
}
| FileUtils |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/testkit/BooleanArrays.java | {
"start": 694,
"end": 936
} | class ____ {
private static final boolean[] EMPTY = {};
public static boolean[] arrayOf(boolean... values) {
return values;
}
public static boolean[] emptyArray() {
return EMPTY;
}
private BooleanArrays() {}
}
| BooleanArrays |
java | google__error-prone | refaster/src/main/java/com/google/errorprone/refaster/RefasterRuleCompilerAnalyzer.java | {
"start": 1383,
"end": 2704
} | class ____ implements TaskListener {
private final Context context;
private final Path destinationPath;
RefasterRuleCompilerAnalyzer(Context context, Path destinationPath) {
this.context = context;
this.destinationPath = destinationPath;
}
@Override
public void finished(TaskEvent taskEvent) {
if (taskEvent.getKind() != Kind.ANALYZE) {
return;
}
if (JavaCompiler.instance(context).errorCount() > 0) {
return;
}
ClassTree tree = JavacTrees.instance(context).getTree(taskEvent.getTypeElement());
if (tree == null) {
return;
}
List<CodeTransformer> rules = new ArrayList<>();
new TreeScanner<Void, Context>() {
@Override
public Void visitClass(ClassTree node, Context context) {
rules.addAll(RefasterRuleBuilderScanner.extractRules(node, context));
return super.visitClass(node, context);
}
}.scan(tree, context);
if (rules.isEmpty()) {
throw new IllegalArgumentException("Did not find any Refaster templates");
}
try (ObjectOutputStream output =
new ObjectOutputStream(Files.newOutputStream(destinationPath))) {
output.writeObject(CompositeCodeTransformer.compose(rules));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| RefasterRuleCompilerAnalyzer |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/collection/defaultimplementation/NoSetterSource.java | {
"start": 303,
"end": 772
} | class ____ {
private List<String> listValues;
private Map<String, String> mapValues;
public List<String> getListValues() {
return listValues;
}
public void setListValues(List<String> listValues) {
this.listValues = listValues;
}
public Map<String, String> getMapValues() {
return mapValues;
}
public void setMapValues(Map<String, String> mapValues) {
this.mapValues = mapValues;
}
}
| NoSetterSource |
java | apache__hadoop | hadoop-tools/hadoop-datajoin/src/main/java/org/apache/hadoop/contrib/utils/join/ResetableIterator.java | {
"start": 943,
"end": 1146
} | interface ____ will help the reducer class
* re-group its input by source tags. Once the values are re-grouped,
* the reducer will receive the cross product of values from different groups.
*/
public | that |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/IrateFloatGroupingAggregatorFunction.java | {
"start": 1171,
"end": 15951
} | class ____ implements GroupingAggregatorFunction {
private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of(
new IntermediateStateDesc("timestamps", ElementType.LONG),
new IntermediateStateDesc("values", ElementType.FLOAT) );
private final IrateFloatAggregator.FloatIrateGroupingState state;
private final List<Integer> channels;
private final DriverContext driverContext;
private final boolean isDelta;
public IrateFloatGroupingAggregatorFunction(List<Integer> channels,
IrateFloatAggregator.FloatIrateGroupingState state, DriverContext driverContext,
boolean isDelta) {
this.channels = channels;
this.state = state;
this.driverContext = driverContext;
this.isDelta = isDelta;
}
public static IrateFloatGroupingAggregatorFunction create(List<Integer> channels,
DriverContext driverContext, boolean isDelta) {
return new IrateFloatGroupingAggregatorFunction(channels, IrateFloatAggregator.initGrouping(driverContext, isDelta), driverContext, isDelta);
}
public static List<IntermediateStateDesc> intermediateStateDesc() {
return INTERMEDIATE_STATE_DESC;
}
@Override
public int intermediateBlockCount() {
return INTERMEDIATE_STATE_DESC.size();
}
@Override
public GroupingAggregatorFunction.AddInput prepareProcessRawInputPage(SeenGroupIds seenGroupIds,
Page page) {
FloatBlock valueBlock = page.getBlock(channels.get(0));
LongBlock timestampBlock = page.getBlock(channels.get(1));
FloatVector valueVector = valueBlock.asVector();
if (valueVector == null) {
maybeEnableGroupIdTracking(seenGroupIds, valueBlock, timestampBlock);
return new GroupingAggregatorFunction.AddInput() {
@Override
public void add(int positionOffset, IntArrayBlock groupIds) {
addRawInput(positionOffset, groupIds, valueBlock, timestampBlock);
}
@Override
public void add(int positionOffset, IntBigArrayBlock groupIds) {
addRawInput(positionOffset, groupIds, valueBlock, timestampBlock);
}
@Override
public void add(int positionOffset, IntVector groupIds) {
addRawInput(positionOffset, groupIds, valueBlock, timestampBlock);
}
@Override
public void close() {
}
};
}
LongVector timestampVector = timestampBlock.asVector();
if (timestampVector == null) {
maybeEnableGroupIdTracking(seenGroupIds, valueBlock, timestampBlock);
return new GroupingAggregatorFunction.AddInput() {
@Override
public void add(int positionOffset, IntArrayBlock groupIds) {
addRawInput(positionOffset, groupIds, valueBlock, timestampBlock);
}
@Override
public void add(int positionOffset, IntBigArrayBlock groupIds) {
addRawInput(positionOffset, groupIds, valueBlock, timestampBlock);
}
@Override
public void add(int positionOffset, IntVector groupIds) {
addRawInput(positionOffset, groupIds, valueBlock, timestampBlock);
}
@Override
public void close() {
}
};
}
return new GroupingAggregatorFunction.AddInput() {
@Override
public void add(int positionOffset, IntArrayBlock groupIds) {
addRawInput(positionOffset, groupIds, valueVector, timestampVector);
}
@Override
public void add(int positionOffset, IntBigArrayBlock groupIds) {
addRawInput(positionOffset, groupIds, valueVector, timestampVector);
}
@Override
public void add(int positionOffset, IntVector groupIds) {
addRawInput(positionOffset, groupIds, valueVector, timestampVector);
}
@Override
public void close() {
}
};
}
private void addRawInput(int positionOffset, IntArrayBlock groups, FloatBlock valueBlock,
LongBlock timestampBlock) {
for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) {
if (groups.isNull(groupPosition)) {
continue;
}
int valuesPosition = groupPosition + positionOffset;
if (valueBlock.isNull(valuesPosition)) {
continue;
}
if (timestampBlock.isNull(valuesPosition)) {
continue;
}
int groupStart = groups.getFirstValueIndex(groupPosition);
int groupEnd = groupStart + groups.getValueCount(groupPosition);
for (int g = groupStart; g < groupEnd; g++) {
int groupId = groups.getInt(g);
int valueStart = valueBlock.getFirstValueIndex(valuesPosition);
int valueEnd = valueStart + valueBlock.getValueCount(valuesPosition);
for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) {
float valueValue = valueBlock.getFloat(valueOffset);
int timestampStart = timestampBlock.getFirstValueIndex(valuesPosition);
int timestampEnd = timestampStart + timestampBlock.getValueCount(valuesPosition);
for (int timestampOffset = timestampStart; timestampOffset < timestampEnd; timestampOffset++) {
long timestampValue = timestampBlock.getLong(timestampOffset);
IrateFloatAggregator.combine(state, groupId, valueValue, timestampValue);
}
}
}
}
}
private void addRawInput(int positionOffset, IntArrayBlock groups, FloatVector valueVector,
LongVector timestampVector) {
for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) {
if (groups.isNull(groupPosition)) {
continue;
}
int valuesPosition = groupPosition + positionOffset;
int groupStart = groups.getFirstValueIndex(groupPosition);
int groupEnd = groupStart + groups.getValueCount(groupPosition);
for (int g = groupStart; g < groupEnd; g++) {
int groupId = groups.getInt(g);
float valueValue = valueVector.getFloat(valuesPosition);
long timestampValue = timestampVector.getLong(valuesPosition);
IrateFloatAggregator.combine(state, groupId, valueValue, timestampValue);
}
}
}
@Override
public void addIntermediateInput(int positionOffset, IntArrayBlock groups, Page page) {
state.enableGroupIdTracking(new SeenGroupIds.Empty());
assert channels.size() == intermediateBlockCount();
Block timestampsUncast = page.getBlock(channels.get(0));
if (timestampsUncast.areAllValuesNull()) {
return;
}
LongBlock timestamps = (LongBlock) timestampsUncast;
Block valuesUncast = page.getBlock(channels.get(1));
if (valuesUncast.areAllValuesNull()) {
return;
}
FloatBlock values = (FloatBlock) valuesUncast;
assert timestamps.getPositionCount() == values.getPositionCount();
for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) {
if (groups.isNull(groupPosition)) {
continue;
}
int groupStart = groups.getFirstValueIndex(groupPosition);
int groupEnd = groupStart + groups.getValueCount(groupPosition);
for (int g = groupStart; g < groupEnd; g++) {
int groupId = groups.getInt(g);
int valuesPosition = groupPosition + positionOffset;
IrateFloatAggregator.combineIntermediate(state, groupId, timestamps, values, valuesPosition);
}
}
}
private void addRawInput(int positionOffset, IntBigArrayBlock groups, FloatBlock valueBlock,
LongBlock timestampBlock) {
for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) {
if (groups.isNull(groupPosition)) {
continue;
}
int valuesPosition = groupPosition + positionOffset;
if (valueBlock.isNull(valuesPosition)) {
continue;
}
if (timestampBlock.isNull(valuesPosition)) {
continue;
}
int groupStart = groups.getFirstValueIndex(groupPosition);
int groupEnd = groupStart + groups.getValueCount(groupPosition);
for (int g = groupStart; g < groupEnd; g++) {
int groupId = groups.getInt(g);
int valueStart = valueBlock.getFirstValueIndex(valuesPosition);
int valueEnd = valueStart + valueBlock.getValueCount(valuesPosition);
for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) {
float valueValue = valueBlock.getFloat(valueOffset);
int timestampStart = timestampBlock.getFirstValueIndex(valuesPosition);
int timestampEnd = timestampStart + timestampBlock.getValueCount(valuesPosition);
for (int timestampOffset = timestampStart; timestampOffset < timestampEnd; timestampOffset++) {
long timestampValue = timestampBlock.getLong(timestampOffset);
IrateFloatAggregator.combine(state, groupId, valueValue, timestampValue);
}
}
}
}
}
private void addRawInput(int positionOffset, IntBigArrayBlock groups, FloatVector valueVector,
LongVector timestampVector) {
for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) {
if (groups.isNull(groupPosition)) {
continue;
}
int valuesPosition = groupPosition + positionOffset;
int groupStart = groups.getFirstValueIndex(groupPosition);
int groupEnd = groupStart + groups.getValueCount(groupPosition);
for (int g = groupStart; g < groupEnd; g++) {
int groupId = groups.getInt(g);
float valueValue = valueVector.getFloat(valuesPosition);
long timestampValue = timestampVector.getLong(valuesPosition);
IrateFloatAggregator.combine(state, groupId, valueValue, timestampValue);
}
}
}
@Override
public void addIntermediateInput(int positionOffset, IntBigArrayBlock groups, Page page) {
state.enableGroupIdTracking(new SeenGroupIds.Empty());
assert channels.size() == intermediateBlockCount();
Block timestampsUncast = page.getBlock(channels.get(0));
if (timestampsUncast.areAllValuesNull()) {
return;
}
LongBlock timestamps = (LongBlock) timestampsUncast;
Block valuesUncast = page.getBlock(channels.get(1));
if (valuesUncast.areAllValuesNull()) {
return;
}
FloatBlock values = (FloatBlock) valuesUncast;
assert timestamps.getPositionCount() == values.getPositionCount();
for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) {
if (groups.isNull(groupPosition)) {
continue;
}
int groupStart = groups.getFirstValueIndex(groupPosition);
int groupEnd = groupStart + groups.getValueCount(groupPosition);
for (int g = groupStart; g < groupEnd; g++) {
int groupId = groups.getInt(g);
int valuesPosition = groupPosition + positionOffset;
IrateFloatAggregator.combineIntermediate(state, groupId, timestamps, values, valuesPosition);
}
}
}
private void addRawInput(int positionOffset, IntVector groups, FloatBlock valueBlock,
LongBlock timestampBlock) {
for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) {
int valuesPosition = groupPosition + positionOffset;
if (valueBlock.isNull(valuesPosition)) {
continue;
}
if (timestampBlock.isNull(valuesPosition)) {
continue;
}
int groupId = groups.getInt(groupPosition);
int valueStart = valueBlock.getFirstValueIndex(valuesPosition);
int valueEnd = valueStart + valueBlock.getValueCount(valuesPosition);
for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) {
float valueValue = valueBlock.getFloat(valueOffset);
int timestampStart = timestampBlock.getFirstValueIndex(valuesPosition);
int timestampEnd = timestampStart + timestampBlock.getValueCount(valuesPosition);
for (int timestampOffset = timestampStart; timestampOffset < timestampEnd; timestampOffset++) {
long timestampValue = timestampBlock.getLong(timestampOffset);
IrateFloatAggregator.combine(state, groupId, valueValue, timestampValue);
}
}
}
}
private void addRawInput(int positionOffset, IntVector groups, FloatVector valueVector,
LongVector timestampVector) {
for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) {
int valuesPosition = groupPosition + positionOffset;
int groupId = groups.getInt(groupPosition);
float valueValue = valueVector.getFloat(valuesPosition);
long timestampValue = timestampVector.getLong(valuesPosition);
IrateFloatAggregator.combine(state, groupId, valueValue, timestampValue);
}
}
@Override
public void addIntermediateInput(int positionOffset, IntVector groups, Page page) {
state.enableGroupIdTracking(new SeenGroupIds.Empty());
assert channels.size() == intermediateBlockCount();
Block timestampsUncast = page.getBlock(channels.get(0));
if (timestampsUncast.areAllValuesNull()) {
return;
}
LongBlock timestamps = (LongBlock) timestampsUncast;
Block valuesUncast = page.getBlock(channels.get(1));
if (valuesUncast.areAllValuesNull()) {
return;
}
FloatBlock values = (FloatBlock) valuesUncast;
assert timestamps.getPositionCount() == values.getPositionCount();
for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) {
int groupId = groups.getInt(groupPosition);
int valuesPosition = groupPosition + positionOffset;
IrateFloatAggregator.combineIntermediate(state, groupId, timestamps, values, valuesPosition);
}
}
private void maybeEnableGroupIdTracking(SeenGroupIds seenGroupIds, FloatBlock valueBlock,
LongBlock timestampBlock) {
if (valueBlock.mayHaveNulls()) {
state.enableGroupIdTracking(seenGroupIds);
}
if (timestampBlock.mayHaveNulls()) {
state.enableGroupIdTracking(seenGroupIds);
}
}
@Override
public void selectedMayContainUnseenGroups(SeenGroupIds seenGroupIds) {
state.enableGroupIdTracking(seenGroupIds);
}
@Override
public void evaluateIntermediate(Block[] blocks, int offset, IntVector selected) {
state.toIntermediate(blocks, offset, selected, driverContext);
}
@Override
public void evaluateFinal(Block[] blocks, int offset, IntVector selected,
GroupingAggregatorEvaluationContext ctx) {
blocks[offset] = IrateFloatAggregator.evaluateFinal(state, selected, ctx);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append("[");
sb.append("channels=").append(channels);
sb.append("]");
return sb.toString();
}
@Override
public void close() {
state.close();
}
}
| IrateFloatGroupingAggregatorFunction |
java | apache__camel | core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/LimitedPollingConsumerPollStrategy.java | {
"start": 1554,
"end": 4377
} | class ____ extends DefaultPollingConsumerPollStrategy {
private static final Logger LOG = LoggerFactory.getLogger(LimitedPollingConsumerPollStrategy.class);
private final Map<Consumer, Integer> state = new HashMap<>();
private int limit = 3;
public int getLimit() {
return limit;
}
/**
* Sets the limit for how many straight rollbacks causes this strategy to suspend the fault consumer.
* <p/>
* When the consumer has been suspended, it has to be manually resumed/started to be active again. The limit is by
* default 3.
*
* @param limit the limit
*/
public void setLimit(int limit) {
this.limit = limit;
}
@Override
public void commit(Consumer consumer, Endpoint endpoint, int polledMessages) {
// we could commit so clear state
state.remove(consumer);
}
@Override
public boolean rollback(Consumer consumer, Endpoint endpoint, int retryCounter, Exception cause) throws Exception {
// keep track how many times in a row we have rolled back
Integer times = state.get(consumer);
if (times == null) {
times = 1;
} else {
times += 1;
}
LOG.debug("Rollback occurred after {} times when consuming {}", times, endpoint);
boolean retry = false;
if (times >= limit) {
// clear state when we suspend so if its restarted manually we start all over again
state.remove(consumer);
onSuspend(consumer, endpoint);
} else {
// error occurred
state.put(consumer, times);
retry = onRollback(consumer, endpoint);
}
return retry;
}
/**
* The consumer is to be suspended because it exceeded the limit
*
* @param consumer the consumer
* @param endpoint the endpoint
* @throws Exception is thrown if error suspending the consumer
*/
protected void onSuspend(Consumer consumer, Endpoint endpoint) throws Exception {
LOG.warn("Suspending consumer {} after {} attempts to consume from {}. You have to manually resume the consumer!",
consumer, limit, endpoint);
ServiceHelper.suspendService(consumer);
}
/**
* Rollback occurred.
*
* @param consumer the consumer
* @param endpoint the endpoint
* @return whether to retry immediately, is default <tt>false</tt>
* @throws Exception can be thrown in case something goes wrong
*/
protected boolean onRollback(Consumer consumer, Endpoint endpoint) throws Exception {
// do not retry by default
return false;
}
@Override
protected void doStop() throws Exception {
state.clear();
}
}
| LimitedPollingConsumerPollStrategy |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvtVO/IncomingDataPoint.java | {
"start": 572,
"end": 4773
} | class ____ {
/** The incoming metric name */
private String metric;
/** The incoming timestamp in Unix epoch seconds or milliseconds */
private long timestamp;
/** The incoming value as a string, we'll parse it to float or int later */
private String value;
/** A hash map of tag name/values */
private Map<String, String> tags;
/** TSUID for the data point */
private String tsuid;
private String granularity;
private String aggregator;
/**
* Empty constructor necessary for some de/serializers
*/
public IncomingDataPoint() {
}
/**
* Constructor used when working with a metric and tags
* @param metric The metric name
* @param timestamp The Unix epoch timestamp
* @param value The value as a string
* @param tags The tag name/value map
*/
public IncomingDataPoint(final String metric,
final long timestamp,
final String value,
final HashMap<String, String> tags,
final String granularity,
final String aggregator) {
this.metric = metric;
this.granularity = granularity;
this.timestamp = timestamp;
this.value = value;
this.tags = tags;
this.aggregator = aggregator;
}
/**
* Constructor used when working with tsuids
* @param tsuid The TSUID
* @param timestamp The Unix epoch timestamp
* @param value The value as a string
*/
public IncomingDataPoint(final String tsuid,
final String granularity,
final long timestamp,
final String value) {
this.tsuid = tsuid;
this.granularity = granularity;
this.timestamp = timestamp;
this.value = value;
}
/**
* @return information about this object
*/
@Override
public String toString() {
final StringBuilder buf = new StringBuilder();
buf.append(" metric=").append(this.metric);
buf.append(" granularity=").append(this.granularity);
buf.append(" aggregator=").append(this.aggregator);
buf.append(" ts=").append(this.timestamp);
buf.append(" value=").append(this.value);
if (this.tags != null) {
for (Map.Entry<String, String> entry : this.tags.entrySet()) {
buf.append(" ").append(entry.getKey()).append("=").append(entry.getValue());
}
}
return buf.toString();
}
/** @return the metric */
public final String getMetric() {
return metric;
}
/** @return the timestamp */
public final long getTimestamp() {
return timestamp;
}
/** @return the value */
public final String getValue() {
return value;
}
/** @return the tags */
public final Map<String, String> getTags() {
return tags;
}
/** @return the TSUID */
@JSONField(name = "tsuid")
public final String getTSUID() {
return tsuid;
}
public final String getGranularity() {
return granularity;
}
public final String getAggregator() {
return aggregator;
}
public final void setGranularity(String granularity) {
this.granularity = granularity;
}
public final void setAggregator(String aggregator) {
this.aggregator = aggregator;
}
/** @param metric the metric to set */
public final void setMetric(String metric) {
this.metric = metric;
}
/** @param timestamp the timestamp to set */
public final void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
/** @param value the value to set */
public final void setValue(String value) {
this.value = value;
}
/** @param tags the tags to set */
public final void setTags(Map<String, String> tags) {
this.tags = tags;
}
/** @param tsuid the TSUID to set */
@JSONField(name = "tsuid")
public final void setTSUID(String tsuid) {
this.tsuid = tsuid;
}
} | IncomingDataPoint |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase/hadoop-yarn-server-timelineservice-hbase-common/src/main/java/org/apache/hadoop/yarn/server/timelineservice/storage/flow/Attribute.java | {
"start": 972,
"end": 1268
} | class ____ {
private final String name;
private final byte[] value;
public Attribute(String name, byte[] value) {
this.name = name;
this.value = value.clone();
}
public String getName() {
return name;
}
public byte[] getValue() {
return value.clone();
}
}
| Attribute |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/ValidityAuditStrategyManyToManyTest.java | {
"start": 1332,
"end": 5728
} | class ____ {
private Integer ing_id;
private Integer ed_id;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) {
final SetOwningEntity setOwningEntity = new SetOwningEntity(1, "parent");
final SetOwnedEntity setOwnedEntity = new SetOwnedEntity(2, "child");
// Revision 1: Initial persist
scope.inTransaction(em -> {
em.persist(setOwningEntity);
em.persist(setOwnedEntity);
});
ing_id = setOwningEntity.getId();
ed_id = setOwnedEntity.getId();
// Revision 2: add child for first time
scope.inTransaction(em -> {
SetOwningEntity owningEntity = em.find(SetOwningEntity.class, ing_id);
SetOwnedEntity ownedEntity = em.find(SetOwnedEntity.class, ed_id);
owningEntity.setReferences(new HashSet<SetOwnedEntity>());
owningEntity.getReferences().add(ownedEntity);
});
// Revision 3: remove child
scope.inTransaction(em -> {
SetOwningEntity owningEntity = em.find(SetOwningEntity.class, ing_id);
SetOwnedEntity ownedEntity = em.find(SetOwnedEntity.class, ed_id);
owningEntity.getReferences().remove(ownedEntity);
});
// Revision 4: add child again
scope.inTransaction(em -> {
SetOwningEntity owningEntity = em.find(SetOwningEntity.class, ing_id);
SetOwnedEntity ownedEntity = em.find(SetOwnedEntity.class, ed_id);
owningEntity.getReferences().add(ownedEntity);
});
// Revision 5: remove child again
scope.inTransaction(em -> {
SetOwningEntity owningEntity = em.find(SetOwningEntity.class, ing_id);
SetOwnedEntity ownedEntity = em.find(SetOwnedEntity.class, ed_id);
owningEntity.getReferences().remove(ownedEntity);
});
}
@Test
public void testMultipleAddAndRemove(EntityManagerFactoryScope scope) {
// now the set owning entity list should be empty again
scope.inEntityManager(em -> {
SetOwningEntity owningEntity = em.find(SetOwningEntity.class, ing_id);
assertEquals(0, owningEntity.getReferences().size());
});
}
@Test
public void testRevisionsCounts(EntityManagerFactoryScope scope) {
scope.inEntityManager(em -> {
final var auditReader = AuditReaderFactory.get(em);
assertEquals(Arrays.asList(1, 2, 3, 4, 5), auditReader.getRevisions(SetOwningEntity.class, ing_id));
assertEquals(Arrays.asList(1, 2, 3, 4, 5), auditReader.getRevisions(SetOwnedEntity.class, ed_id));
});
}
@Test
public void testHistoryOfIng1(EntityManagerFactoryScope scope) {
scope.inEntityManager(em -> {
final var auditReader = AuditReaderFactory.get(em);
SetOwningEntity ver_empty = createOwningEntity();
SetOwningEntity ver_child = createOwningEntity(new SetOwnedEntity(ed_id, "child"));
assertEquals(ver_empty, auditReader.find(SetOwningEntity.class, ing_id, 1));
assertEquals(ver_child, auditReader.find(SetOwningEntity.class, ing_id, 2));
assertEquals(ver_empty, auditReader.find(SetOwningEntity.class, ing_id, 3));
assertEquals(ver_child, auditReader.find(SetOwningEntity.class, ing_id, 4));
assertEquals(ver_empty, auditReader.find(SetOwningEntity.class, ing_id, 5));
});
}
@Test
public void testHistoryOfEd1(EntityManagerFactoryScope scope) {
scope.inEntityManager(em -> {
final var auditReader = AuditReaderFactory.get(em);
SetOwnedEntity ver_empty = createOwnedEntity();
SetOwnedEntity ver_child = createOwnedEntity(new SetOwningEntity(ing_id, "parent"));
assertEquals(ver_empty, auditReader.find(SetOwnedEntity.class, ed_id, 1));
assertEquals(ver_child, auditReader.find(SetOwnedEntity.class, ed_id, 2));
assertEquals(ver_empty, auditReader.find(SetOwnedEntity.class, ed_id, 3));
assertEquals(ver_child, auditReader.find(SetOwnedEntity.class, ed_id, 4));
assertEquals(ver_empty, auditReader.find(SetOwnedEntity.class, ed_id, 5));
});
}
private SetOwningEntity createOwningEntity(SetOwnedEntity... owned) {
SetOwningEntity result = new SetOwningEntity(ing_id, "parent");
result.setReferences(new HashSet<SetOwnedEntity>());
for (SetOwnedEntity setOwnedEntity : owned) {
result.getReferences().add(setOwnedEntity);
}
return result;
}
private SetOwnedEntity createOwnedEntity(SetOwningEntity... owning) {
SetOwnedEntity result = new SetOwnedEntity(ed_id, "child");
result.setReferencing(new HashSet<SetOwningEntity>());
for (SetOwningEntity setOwningEntity : owning) {
result.getReferencing().add(setOwningEntity);
}
return result;
}
}
| ValidityAuditStrategyManyToManyTest |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/internal/configuration/plugins/PluginLoaderTest.java | {
"start": 3278,
"end": 7650
} | interface ____.mockito.internal.configuration.plugins.PluginLoaderTest$Foo (alternate: null)")
.hasCause(cause);
}
@Test
public void loads_preferred_plugin_inheritance() {
FooChildPlugin expected = new FooChildPlugin();
willReturn(expected).given(initializer).loadImpl(Foo.class);
// when
Foo plugin = loader.loadPlugin(Foo.class, FooChildPlugin.class);
// then
assertSame(expected, plugin);
verify(initializer, never()).loadImpl(FooChildPlugin.class);
}
@Test
public void loads_alternative_plugin_inheritance() {
willReturn(null).given(initializer).loadImpl(Bar.class);
BarChildPlugin expected = new BarChildPlugin();
willReturn(expected).given(initializer).loadImpl(BarChildPlugin.class);
// when
Bar plugin = loader.loadPlugin(Bar.class, BarChildPlugin.class);
// then
assertSame(expected, plugin);
}
@Test
public void loads_default_plugin_inheritance() {
willReturn(null).given(initializer).loadImpl(Foo.class);
willReturn(null).given(initializer).loadImpl(FooChildPlugin.class);
FooChildPlugin expected = new FooChildPlugin();
willReturn(expected).given(plugins).getDefaultPlugin(Foo.class);
// when
Foo plugin = loader.loadPlugin(Foo.class, FooChildPlugin.class);
// then
assertSame(expected, plugin);
}
@Test
public void loads_preferred_plugin_inheritance_reversed() {
FooChildPlugin expected = new FooChildPlugin();
willReturn(expected).given(initializer).loadImpl(FooChildPlugin.class);
// when
Foo plugin = loader.loadPlugin(FooChildPlugin.class, Foo.class);
// then
assertSame(expected, plugin);
verify(initializer, never()).loadImpl(Foo.class);
}
@Test
public void loads_alternative_plugin_inheritance_reversed() {
willReturn(null).given(initializer).loadImpl(BarChildPlugin.class);
BarChildPlugin expected = new BarChildPlugin();
willReturn(expected).given(initializer).loadImpl(Bar.class);
// when
Bar plugin = loader.loadPlugin(BarChildPlugin.class, Bar.class);
// then
assertSame(expected, plugin);
}
@Test
public void loads_default_plugin_inheritance_reversed() {
willReturn(null).given(initializer).loadImpl(Foo.class);
willReturn(null).given(initializer).loadImpl(FooChildPlugin.class);
FooChildPlugin expected = new FooChildPlugin();
willReturn(expected).given(plugins).getDefaultPlugin(FooChildPlugin.class);
// when
Foo plugin = loader.loadPlugin(FooChildPlugin.class, Foo.class);
// then
assertSame(expected, plugin);
}
@Test
public void loads_preferred_plugin_inheritance_lowest_common_denominator() {
FooBarChildPlugin1 expected = new FooBarChildPlugin1();
willReturn(expected).given(initializer).loadImpl(FooBarChildPlugin1.class);
// when
FooBar plugin = loader.loadPlugin(FooBarChildPlugin1.class, FooBarChildPlugin2.class);
// then
assertSame(expected, plugin);
verify(initializer, never()).loadImpl(FooBarChildPlugin2.class);
}
@Test
public void loads_alternative_plugin_inheritance_lowest_common_denominator() {
willReturn(null).given(initializer).loadImpl(FooBarChildPlugin1.class);
FooBarChildPlugin2 expected = new FooBarChildPlugin2();
willReturn(expected).given(initializer).loadImpl(FooBarChildPlugin2.class);
// when
FooBar plugin = loader.loadPlugin(FooBarChildPlugin1.class, FooBarChildPlugin2.class);
// then
assertSame(expected, plugin);
}
@Test
public void loads_default_plugin_inheritance_lowest_common_denominator() {
willReturn(null).given(initializer).loadImpl(FooBarChildPlugin1.class);
willReturn(null).given(initializer).loadImpl(FooBarChildPlugin2.class);
FooBarChildPlugin1 expected = new FooBarChildPlugin1();
willReturn(expected).given(plugins).getDefaultPlugin(FooBarChildPlugin1.class);
// when
FooBar plugin = loader.loadPlugin(FooBarChildPlugin1.class, FooBarChildPlugin2.class);
// then
assertSame(expected, plugin);
}
static | org |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryMethodReference.java | {
"start": 2390,
"end": 4297
} | class ____ extends BugChecker
implements MemberReferenceTreeMatcher {
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
if (!tree.getMode().equals(ReferenceMode.INVOKE)) {
return NO_MATCH;
}
TargetType targetType = targetType(state);
if (targetType == null) {
return NO_MATCH;
}
ExpressionTree receiver = getReceiver(tree);
if (receiver == null) {
return NO_MATCH;
}
if (receiver instanceof IdentifierTree identifierTree
&& identifierTree.getName().contentEquals("super")) {
return NO_MATCH;
}
if (!state.getTypes().isSubtype(getType(receiver), targetType.type())) {
return NO_MATCH;
}
MethodSymbol symbol = getSymbol(tree);
Scope members = targetType.type().tsym.members();
if (!members.anyMatch(
sym -> isFunctionalInterfaceInvocation(symbol, targetType.type(), sym, state))
&& !isKnownAlias(tree, targetType.type(), state)) {
return NO_MATCH;
}
return describeMatch(
tree, replace(state.getEndPosition(receiver), state.getEndPosition(tree), ""));
}
private static boolean isFunctionalInterfaceInvocation(
MethodSymbol memberReferenceTarget, Type type, Symbol symbol, VisitorState state) {
return (memberReferenceTarget.equals(symbol)
|| findSuperMethodInType(memberReferenceTarget, type, state.getTypes()) != null)
&& symbol.getModifiers().contains(ABSTRACT);
}
private static boolean isKnownAlias(MemberReferenceTree tree, Type type, VisitorState state) {
return KNOWN_ALIASES.stream()
.anyMatch(
k ->
k.matcher().matches(tree, state)
&& isSubtype(k.targetType().get(state), type, state));
}
/**
* Methods that we know delegate directly to the abstract method on a functional | UnnecessaryMethodReference |
java | junit-team__junit5 | junit-jupiter-params/src/main/java/org/junit/jupiter/params/ArgumentCountValidationMode.java | {
"start": 1186,
"end": 1647
} | enum ____ {
/**
* Use the default validation mode.
*
* <p>The default validation mode may be changed via the
* {@value ArgumentCountValidator#ARGUMENT_COUNT_VALIDATION_KEY}
* configuration parameter (see the User Guide for details on configuration
* parameters).
*/
DEFAULT,
/**
* Use the "none" argument count validation mode.
*
* <p>When there are more arguments provided than declared by the
* parameterized | ArgumentCountValidationMode |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableTakeUntil.java | {
"start": 3375,
"end": 4085
} | class ____ extends AtomicReference<Disposable>
implements Observer<U> {
private static final long serialVersionUID = -8693423678067375039L;
@Override
public void onSubscribe(Disposable d) {
DisposableHelper.setOnce(this, d);
}
@Override
public void onNext(U t) {
DisposableHelper.dispose(this);
otherComplete();
}
@Override
public void onError(Throwable e) {
otherError(e);
}
@Override
public void onComplete() {
otherComplete();
}
}
}
}
| OtherObserver |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/SysInfoWindows.java | {
"start": 1299,
"end": 6735
} | class ____ extends SysInfo {
private static final Logger LOG =
LoggerFactory.getLogger(SysInfoWindows.class);
private long vmemSize;
private long memSize;
private long vmemAvailable;
private long memAvailable;
private int numProcessors;
private long cpuFrequencyKhz;
private long cumulativeCpuTimeMs;
private float cpuUsage;
private long storageBytesRead;
private long storageBytesWritten;
private long netBytesRead;
private long netBytesWritten;
private long lastRefreshTime;
static final int REFRESH_INTERVAL_MS = 1000;
public SysInfoWindows() {
lastRefreshTime = 0;
reset();
}
@VisibleForTesting
long now() {
return Time.monotonicNow();
}
void reset() {
vmemSize = -1;
memSize = -1;
vmemAvailable = -1;
memAvailable = -1;
numProcessors = -1;
cpuFrequencyKhz = -1;
cumulativeCpuTimeMs = -1;
cpuUsage = -1;
storageBytesRead = -1;
storageBytesWritten = -1;
netBytesRead = -1;
netBytesWritten = -1;
}
String getSystemInfoInfoFromShell() {
try {
ShellCommandExecutor shellExecutor = new ShellCommandExecutor(
new String[] {Shell.getWinUtilsFile().getCanonicalPath(),
"systeminfo" });
shellExecutor.execute();
return shellExecutor.getOutput();
} catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
}
return null;
}
synchronized void refreshIfNeeded() {
long now = now();
if (now - lastRefreshTime > REFRESH_INTERVAL_MS) {
long refreshInterval = now - lastRefreshTime;
lastRefreshTime = now;
long lastCumCpuTimeMs = cumulativeCpuTimeMs;
reset();
String sysInfoStr = getSystemInfoInfoFromShell();
if (sysInfoStr != null) {
final int sysInfoSplitCount = 11;
int index = sysInfoStr.indexOf("\r\n");
if (index >= 0) {
String[] sysInfo = sysInfoStr.substring(0, index).split(",");
if (sysInfo.length == sysInfoSplitCount) {
try {
vmemSize = Long.parseLong(sysInfo[0]);
memSize = Long.parseLong(sysInfo[1]);
vmemAvailable = Long.parseLong(sysInfo[2]);
memAvailable = Long.parseLong(sysInfo[3]);
numProcessors = Integer.parseInt(sysInfo[4]);
cpuFrequencyKhz = Long.parseLong(sysInfo[5]);
cumulativeCpuTimeMs = Long.parseLong(sysInfo[6]);
storageBytesRead = Long.parseLong(sysInfo[7]);
storageBytesWritten = Long.parseLong(sysInfo[8]);
netBytesRead = Long.parseLong(sysInfo[9]);
netBytesWritten = Long.parseLong(sysInfo[10]);
if (lastCumCpuTimeMs != -1) {
/**
* This number will be the aggregated usage across all cores in
* [0.0, 100.0]. For example, it will be 400.0 if there are 8
* cores and each of them is running at 50% utilization.
*/
cpuUsage = (cumulativeCpuTimeMs - lastCumCpuTimeMs)
* 100F / refreshInterval;
}
} catch (NumberFormatException nfe) {
LOG.warn("Error parsing sysInfo", nfe);
}
} else {
LOG.warn("Expected split length of sysInfo to be "
+ sysInfoSplitCount + ". Got " + sysInfo.length);
}
} else {
LOG.warn("Wrong output from sysInfo: " + sysInfoStr);
}
}
}
}
/** {@inheritDoc} */
@Override
public long getVirtualMemorySize() {
refreshIfNeeded();
return vmemSize;
}
/** {@inheritDoc} */
@Override
public long getPhysicalMemorySize() {
refreshIfNeeded();
return memSize;
}
/** {@inheritDoc} */
@Override
public long getAvailableVirtualMemorySize() {
refreshIfNeeded();
return vmemAvailable;
}
/** {@inheritDoc} */
@Override
public long getAvailablePhysicalMemorySize() {
refreshIfNeeded();
return memAvailable;
}
/** {@inheritDoc} */
@Override
public synchronized int getNumProcessors() {
refreshIfNeeded();
return numProcessors;
}
/** {@inheritDoc} */
@Override
public int getNumCores() {
return getNumProcessors();
}
/** {@inheritDoc} */
@Override
public long getCpuFrequency() {
refreshIfNeeded();
return cpuFrequencyKhz;
}
/** {@inheritDoc} */
@Override
public long getCumulativeCpuTime() {
refreshIfNeeded();
return cumulativeCpuTimeMs;
}
/** {@inheritDoc} */
@Override
public synchronized float getCpuUsagePercentage() {
refreshIfNeeded();
float ret = cpuUsage;
if (ret != -1) {
ret = ret / numProcessors;
}
return ret;
}
/** {@inheritDoc} */
@Override
public synchronized float getNumVCoresUsed() {
refreshIfNeeded();
float ret = cpuUsage;
if (ret != -1) {
ret = ret / 100F;
}
return ret;
}
/** {@inheritDoc} */
@Override
public long getNetworkBytesRead() {
refreshIfNeeded();
return netBytesRead;
}
/** {@inheritDoc} */
@Override
public long getNetworkBytesWritten() {
refreshIfNeeded();
return netBytesWritten;
}
@Override
public long getStorageBytesRead() {
refreshIfNeeded();
return storageBytesRead;
}
@Override
public long getStorageBytesWritten() {
refreshIfNeeded();
return storageBytesWritten;
}
}
| SysInfoWindows |
java | apache__hadoop | hadoop-tools/hadoop-federation-balance/src/test/java/org/apache/hadoop/tools/fedbalance/procedure/TestBalanceProcedureScheduler.java | {
"start": 2622,
"end": 16288
} | class ____ {
private static MiniDFSCluster cluster;
private static final Configuration CONF = new Configuration();
private static DistributedFileSystem fs;
private static final int DEFAULT_BLOCK_SIZE = 512;
@BeforeAll
public static void setup() throws IOException {
CONF.setBoolean(DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_KEY,
true);
CONF.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, "hdfs:///");
CONF.setBoolean(DFS_NAMENODE_ACLS_ENABLED_KEY, true);
CONF.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, DEFAULT_BLOCK_SIZE);
CONF.setLong(DFSConfigKeys.DFS_NAMENODE_MIN_BLOCK_SIZE_KEY, 0);
CONF.setInt(WORK_THREAD_NUM, 1);
cluster = new MiniDFSCluster.Builder(CONF).numDataNodes(3).build();
cluster.waitClusterUp();
cluster.waitActive();
fs = cluster.getFileSystem();
String workPath =
"hdfs://" + cluster.getNameNode().getHostAndPort() + "/procedure";
CONF.set(SCHEDULER_JOURNAL_URI, workPath);
fs.mkdirs(new Path(workPath));
}
@AfterAll
public static void close() {
if (cluster != null) {
cluster.shutdown();
}
}
/**
* Test the scheduler could be shutdown correctly.
*/
@Test
@Timeout(value = 60)
public void testShutdownScheduler() throws Exception {
BalanceProcedureScheduler scheduler = new BalanceProcedureScheduler(CONF);
scheduler.init(true);
// construct job
BalanceJob.Builder builder = new BalanceJob.Builder<>();
builder.nextProcedure(new WaitProcedure("wait", 1000, 5 * 1000));
BalanceJob job = builder.build();
scheduler.submit(job);
Thread.sleep(1000); // wait job to be scheduled.
scheduler.shutDownAndWait(30 * 1000);
BalanceJournal journal =
ReflectionUtils.newInstance(BalanceJournalInfoHDFS.class, CONF);
journal.clear(job);
}
/**
* Test a successful job.
*/
@Test
@Timeout(value = 60)
public void testSuccessfulJob() throws Exception {
BalanceProcedureScheduler scheduler = new BalanceProcedureScheduler(CONF);
scheduler.init(true);
try {
// construct job
List<RecordProcedure> procedures = new ArrayList<>();
BalanceJob.Builder builder = new BalanceJob.Builder<RecordProcedure>();
for (int i = 0; i < 5; i++) {
RecordProcedure r = new RecordProcedure("record-" + i, 1000L);
builder.nextProcedure(r);
procedures.add(r);
}
BalanceJob<RecordProcedure> job = builder.build();
scheduler.submit(job);
scheduler.waitUntilDone(job);
assertNull(job.getError());
// verify finish list.
assertEquals(5, RecordProcedure.getFinishList().size());
for (int i = 0; i < RecordProcedure.getFinishList().size(); i++) {
assertEquals(procedures.get(i), RecordProcedure.getFinishList().get(i));
}
} finally {
scheduler.shutDownAndWait(2);
}
}
/**
* Test a job fails and the error can be got.
*/
@Test
@Timeout(value = 60)
public void testFailedJob() throws Exception {
BalanceProcedureScheduler scheduler = new BalanceProcedureScheduler(CONF);
scheduler.init(true);
try {
// Mock bad procedure.
BalanceProcedure badProcedure = mock(BalanceProcedure.class);
doThrow(new IOException("Job failed exception."))
.when(badProcedure).execute();
doReturn("bad-procedure").when(badProcedure).name();
BalanceJob.Builder builder = new BalanceJob.Builder<>();
builder.nextProcedure(badProcedure);
BalanceJob job = builder.build();
scheduler.submit(job);
scheduler.waitUntilDone(job);
GenericTestUtils
.assertExceptionContains("Job failed exception", job.getError());
} finally {
scheduler.shutDownAndWait(2);
}
}
/**
* Test recover a job. After the job is recovered, the job should start from
* the last unfinished procedure, which is the first procedure without
* journal.
*/
@Test
@Timeout(value = 60)
public void testGetJobAfterRecover() throws Exception {
BalanceProcedureScheduler scheduler = new BalanceProcedureScheduler(CONF);
scheduler.init(true);
try {
// Construct job.
BalanceJob.Builder builder = new BalanceJob.Builder<>();
String firstProcedure = "wait0";
WaitProcedure[] procedures = new WaitProcedure[5];
for (int i = 0; i < 5; i++) {
WaitProcedure procedure = new WaitProcedure("wait" + i, 1000, 1000);
builder.nextProcedure(procedure).removeAfterDone(false);
procedures[i] = procedure;
}
BalanceJob job = builder.build();
scheduler.submit(job);
// Sleep a random time then shut down.
long randomSleepTime = Math.abs(new Random().nextInt()) % 5 * 1000 + 1000;
Thread.sleep(randomSleepTime);
scheduler.shutDownAndWait(2);
// Current procedure is the last unfinished procedure. It is also the
// first procedure without journal.
WaitProcedure recoverProcedure = (WaitProcedure) job.getCurProcedure();
int recoverIndex = -1;
for (int i = 0; i < procedures.length; i++) {
if (procedures[i].name().equals(recoverProcedure.name())) {
recoverIndex = i;
break;
}
}
// Restart scheduler and recover the job.
scheduler = new BalanceProcedureScheduler(CONF);
scheduler.init(true);
scheduler.waitUntilDone(job);
// The job should be done successfully and the recoverJob should be equal
// to the original job.
BalanceJob recoverJob = scheduler.findJob(job);
assertNull(recoverJob.getError());
assertNotSame(job, recoverJob);
assertEquals(job, recoverJob);
// Verify whether the recovered job starts from the recoverProcedure.
Map<String, WaitProcedure> pTable = recoverJob.getProcedureTable();
List<WaitProcedure> recoveredProcedures =
procedureTableToList(pTable, firstProcedure);
for (int i = 0; i < recoverIndex; i++) {
// All procedures before recoverProcedure shouldn't be executed.
assertFalse(recoveredProcedures.get(i).getExecuted());
}
for (int i = recoverIndex; i < procedures.length; i++) {
// All procedures start from recoverProcedure should be executed.
assertTrue(recoveredProcedures.get(i).getExecuted());
}
} finally {
scheduler.shutDownAndWait(2);
}
}
/**
* Test RetryException is handled correctly.
*/
@Test
@Timeout(value = 60)
public void testRetry() throws Exception {
BalanceProcedureScheduler scheduler = new BalanceProcedureScheduler(CONF);
scheduler.init(true);
try {
// construct job
BalanceJob.Builder builder = new BalanceJob.Builder<>();
RetryProcedure retryProcedure = new RetryProcedure("retry", 1000, 3);
builder.nextProcedure(retryProcedure);
BalanceJob job = builder.build();
long start = Time.monotonicNow();
scheduler.submit(job);
scheduler.waitUntilDone(job);
assertNull(job.getError());
long duration = Time.monotonicNow() - start;
assertEquals(true, duration > 1000 * 3);
assertEquals(3, retryProcedure.getTotalRetry());
} finally {
scheduler.shutDownAndWait(2);
}
}
/**
* Test schedule an empty job.
*/
@Test
@Timeout(value = 60)
public void testEmptyJob() throws Exception {
BalanceProcedureScheduler scheduler = new BalanceProcedureScheduler(CONF);
scheduler.init(true);
try {
BalanceJob job = new BalanceJob.Builder<>().build();
scheduler.submit(job);
scheduler.waitUntilDone(job);
} finally {
scheduler.shutDownAndWait(2);
}
}
/**
* Test serialization and deserialization of Job.
*/
@Test
@Timeout(value = 60)
public void testJobSerializeAndDeserialize() throws Exception {
BalanceJob.Builder builder = new BalanceJob.Builder<RecordProcedure>();
for (int i = 0; i < 5; i++) {
RecordProcedure r = new RecordProcedure("record-" + i, 1000L);
builder.nextProcedure(r);
}
builder.nextProcedure(new RetryProcedure("retry", 1000, 3));
BalanceJob<RecordProcedure> job = builder.build();
job.setId(BalanceProcedureScheduler.allocateJobId());
// Serialize.
ByteArrayOutputStream bao = new ByteArrayOutputStream();
job.write(new DataOutputStream(bao));
bao.flush();
ByteArrayInputStream bai = new ByteArrayInputStream(bao.toByteArray());
// Deserialize.
BalanceJob newJob = new BalanceJob.Builder<>().build();
newJob.readFields(new DataInputStream(bai));
assertEquals(job, newJob);
}
/**
* Test scheduler crashes and recovers.
*/
@Test
@Timeout(value = 180)
public void testSchedulerDownAndRecoverJob() throws Exception {
BalanceProcedureScheduler scheduler = new BalanceProcedureScheduler(CONF);
scheduler.init(true);
Path parent = new Path("/testSchedulerDownAndRecoverJob");
try {
// construct job
BalanceJob.Builder builder = new BalanceJob.Builder<>();
MultiPhaseProcedure multiPhaseProcedure =
new MultiPhaseProcedure("retry", 1000, 10, CONF, parent.toString());
builder.nextProcedure(multiPhaseProcedure);
BalanceJob job = builder.build();
scheduler.submit(job);
Thread.sleep(500); // wait procedure to be scheduled.
scheduler.shutDownAndWait(2);
assertFalse(job.isJobDone());
int len = fs.listStatus(parent).length;
assertTrue(len > 0 && len < 10);
// restart scheduler, test recovering the job.
scheduler = new BalanceProcedureScheduler(CONF);
scheduler.init(true);
scheduler.waitUntilDone(job);
assertEquals(10, fs.listStatus(parent).length);
for (int i = 0; i < 10; i++) {
assertTrue(fs.exists(new Path(parent, "phase-" + i)));
}
BalanceJob recoverJob = scheduler.findJob(job);
assertNull(recoverJob.getError());
assertNotSame(job, recoverJob);
assertEquals(job, recoverJob);
} finally {
if (fs.exists(parent)) {
fs.delete(parent, true);
}
scheduler.shutDownAndWait(2);
}
}
@Test
@Timeout(value = 60)
public void testRecoverJobFromJournal() throws Exception {
BalanceJournal journal =
ReflectionUtils.newInstance(BalanceJournalInfoHDFS.class, CONF);
BalanceJob.Builder builder = new BalanceJob.Builder<RecordProcedure>();
BalanceProcedure wait0 = new WaitProcedure("wait0", 1000, 5000);
BalanceProcedure wait1 = new WaitProcedure("wait1", 1000, 1000);
builder.nextProcedure(wait0).nextProcedure(wait1);
BalanceJob job = builder.build();
job.setId(BalanceProcedureScheduler.allocateJobId());
job.setCurrentProcedure(wait1);
job.setLastProcedure(null);
journal.saveJob(job);
long start = Time.monotonicNow();
BalanceProcedureScheduler scheduler = new BalanceProcedureScheduler(CONF);
scheduler.init(true);
try {
scheduler.waitUntilDone(job);
long duration = Time.monotonicNow() - start;
assertTrue(duration >= 1000 && duration < 5000);
} finally {
scheduler.shutDownAndWait(2);
}
}
@Test
@Timeout(value = 60)
public void testClearJournalFail() throws Exception {
BalanceProcedureScheduler scheduler = new BalanceProcedureScheduler(CONF);
scheduler.init(true);
BalanceJournal journal = mock(BalanceJournal.class);
AtomicInteger count = new AtomicInteger(0);
doAnswer(invocation -> {
if (count.incrementAndGet() == 1) {
throw new IOException("Mock clear failure");
}
return null;
}).when(journal).clear(any(BalanceJob.class));
scheduler.setJournal(journal);
try {
BalanceJob.Builder builder = new BalanceJob.Builder<>();
builder.nextProcedure(new WaitProcedure("wait", 1000, 1000));
BalanceJob job = builder.build();
scheduler.submit(job);
scheduler.waitUntilDone(job);
assertEquals(2, count.get());
} finally {
scheduler.shutDownAndWait(2);
}
}
/**
* Test the job will be recovered if writing journal fails.
*/
@Test
@Timeout(value = 60)
public void testJobRecoveryWhenWriteJournalFail() throws Exception {
BalanceProcedureScheduler scheduler = new BalanceProcedureScheduler(CONF);
scheduler.init(true);
try {
// construct job
AtomicBoolean recoverFlag = new AtomicBoolean(true);
BalanceJob.Builder builder = new BalanceJob.Builder<>();
builder.nextProcedure(new WaitProcedure("wait", 1000, 1000))
.nextProcedure(
new UnrecoverableProcedure("shutdown", 1000, () -> {
cluster.restartNameNode(false);
return true;
})).nextProcedure(
new UnrecoverableProcedure("recoverFlag", 1000, () -> {
recoverFlag.set(false);
return true;
})).nextProcedure(new WaitProcedure("wait", 1000, 1000));
BalanceJob job = builder.build();
scheduler.submit(job);
scheduler.waitUntilDone(job);
assertTrue(job.isJobDone());
assertNull(job.getError());
assertTrue(recoverFlag.get());
} finally {
scheduler.shutDownAndWait(2);
}
}
/**
* Transform the procedure map into an ordered list based on the relations
* specified by the map.
*/
<T extends BalanceProcedure> List<T> procedureTableToList(
Map<String, T> pTable, String first) {
List<T> procedures = new ArrayList<>();
T cur = pTable.get(first);
while (cur != null) {
procedures.add(cur);
cur = pTable.get(cur.nextProcedure());
}
return procedures;
}
} | TestBalanceProcedureScheduler |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plugin/ComputeSearchContextByShardId.java | {
"start": 4066,
"end": 5393
} | class ____<T, S> implements IndexedByShardId<S> {
private final IndexedByShardId<T> original;
private final S[] cache;
private final int offset;
private final Function<T, S> mapper;
@SuppressWarnings("unchecked")
Mapped(IndexedByShardId<T> original, int size, int offset, Function<T, S> mapper) {
this.original = original;
this.mapper = mapper;
this.cache = (S[]) new Object[size];
this.offset = offset;
}
@Override
public S get(int shardId) {
var fixedShardId = shardId - offset;
if (cache[fixedShardId] == null) {
synchronized (this) {
if (cache[fixedShardId] == null) {
cache[fixedShardId] = mapper.apply(original.get(shardId));
}
}
}
return cache[fixedShardId];
}
@Override
public Collection<? extends S> collection() {
return IntStream.range(offset, original.collection().size() + offset).mapToObj(this::get).toList();
}
@Override
public <U> IndexedByShardId<U> map(Function<S, U> anotherMapper) {
return new Mapped<>(this, cache.length, offset, anotherMapper);
}
}
}
| Mapped |
java | google__guava | guava-tests/test/com/google/common/util/concurrent/AtomicDoubleTest.java | {
"start": 645,
"end": 10617
} | class ____ extends JSR166TestCase {
private static final double[] VALUES = {
Double.NEGATIVE_INFINITY,
-Double.MAX_VALUE,
(double) Long.MIN_VALUE,
(double) Integer.MIN_VALUE,
-Math.PI,
-1.0,
-Double.MIN_VALUE,
-0.0,
+0.0,
Double.MIN_VALUE,
1.0,
Math.PI,
(double) Integer.MAX_VALUE,
(double) Long.MAX_VALUE,
Double.MAX_VALUE,
Double.POSITIVE_INFINITY,
Double.NaN,
Float.MAX_VALUE,
};
/** The notion of equality used by AtomicDouble */
static boolean bitEquals(double x, double y) {
return Double.doubleToRawLongBits(x) == Double.doubleToRawLongBits(y);
}
static void assertBitEquals(double x, double y) {
assertEquals(Double.doubleToRawLongBits(x), Double.doubleToRawLongBits(y));
}
/** constructor initializes to given value */
public void testConstructor() {
for (double x : VALUES) {
AtomicDouble a = new AtomicDouble(x);
assertBitEquals(x, a.get());
}
}
/** default constructed initializes to zero */
public void testConstructor2() {
AtomicDouble a = new AtomicDouble();
assertBitEquals(0.0, a.get());
}
/** get returns the last value set */
public void testGetSet() {
AtomicDouble at = new AtomicDouble(1.0);
assertBitEquals(1.0, at.get());
for (double x : VALUES) {
at.set(x);
assertBitEquals(x, at.get());
}
}
/** get returns the last value lazySet in same thread */
public void testGetLazySet() {
AtomicDouble at = new AtomicDouble(1.0);
assertBitEquals(1.0, at.get());
for (double x : VALUES) {
at.lazySet(x);
assertBitEquals(x, at.get());
}
}
/** compareAndSet succeeds in changing value if equal to expected else fails */
public void testCompareAndSet() {
double prev = Math.E;
double unused = Math.E + Math.PI;
AtomicDouble at = new AtomicDouble(prev);
for (double x : VALUES) {
assertBitEquals(prev, at.get());
assertFalse(at.compareAndSet(unused, x));
assertBitEquals(prev, at.get());
assertTrue(at.compareAndSet(prev, x));
assertBitEquals(x, at.get());
prev = x;
}
}
/** compareAndSet in one thread enables another waiting for value to succeed */
public void testCompareAndSetInMultipleThreads() throws Exception {
AtomicDouble at = new AtomicDouble(1.0);
Thread t =
newStartedThread(
new CheckedRunnable() {
@Override
@SuppressWarnings("ThreadPriorityCheck") // doing our best to test for races
public void realRun() {
while (!at.compareAndSet(2.0, 3.0)) {
Thread.yield();
}
}
});
assertTrue(at.compareAndSet(1.0, 2.0));
awaitTermination(t);
assertBitEquals(3.0, at.get());
}
/** repeated weakCompareAndSet succeeds in changing value when equal to expected */
public void testWeakCompareAndSet() {
double prev = Math.E;
double unused = Math.E + Math.PI;
AtomicDouble at = new AtomicDouble(prev);
for (double x : VALUES) {
assertBitEquals(prev, at.get());
assertFalse(at.weakCompareAndSet(unused, x));
assertBitEquals(prev, at.get());
while (!at.weakCompareAndSet(prev, x)) {
;
}
assertBitEquals(x, at.get());
prev = x;
}
}
/** getAndSet returns previous value and sets to given value */
public void testGetAndSet() {
double prev = Math.E;
AtomicDouble at = new AtomicDouble(prev);
for (double x : VALUES) {
assertBitEquals(prev, at.getAndSet(x));
prev = x;
}
}
/** getAndAdd returns previous value and adds given value */
public void testGetAndAdd() {
for (double x : VALUES) {
for (double y : VALUES) {
AtomicDouble a = new AtomicDouble(x);
double z = a.getAndAdd(y);
assertBitEquals(x, z);
assertBitEquals(x + y, a.get());
}
}
}
/** addAndGet adds given value to current, and returns current value */
public void testAddAndGet() {
for (double x : VALUES) {
for (double y : VALUES) {
AtomicDouble a = new AtomicDouble(x);
double z = a.addAndGet(y);
assertBitEquals(x + y, z);
assertBitEquals(x + y, a.get());
}
}
}
/** getAndAccumulate with sum adds given value to current, and returns previous value */
public void testGetAndAccumulateWithSum() {
for (double x : VALUES) {
for (double y : VALUES) {
AtomicDouble a = new AtomicDouble(x);
double z = a.getAndAccumulate(y, Double::sum);
assertBitEquals(x, z);
assertBitEquals(x + y, a.get());
}
}
}
/** getAndAccumulate with max stores max of given value to current, and returns previous value */
public void testGetAndAccumulateWithMax() {
for (double x : VALUES) {
for (double y : VALUES) {
AtomicDouble a = new AtomicDouble(x);
double z = a.getAndAccumulate(y, Double::max);
double expectedMax = max(x, y);
assertBitEquals(x, z);
assertBitEquals(expectedMax, a.get());
}
}
}
/** accumulateAndGet with sum adds given value to current, and returns current value */
public void testAccumulateAndGetWithSum() {
for (double x : VALUES) {
for (double y : VALUES) {
AtomicDouble a = new AtomicDouble(x);
double z = a.accumulateAndGet(y, Double::sum);
assertBitEquals(x + y, z);
assertBitEquals(x + y, a.get());
}
}
}
/** accumulateAndGet with max stores max of given value to current, and returns current value */
public void testAccumulateAndGetWithMax() {
for (double x : VALUES) {
for (double y : VALUES) {
AtomicDouble a = new AtomicDouble(x);
double z = a.accumulateAndGet(y, Double::max);
double expectedMax = max(x, y);
assertBitEquals(expectedMax, z);
assertBitEquals(expectedMax, a.get());
}
}
}
/** getAndUpdate with sum stores sum of given value to current, and returns previous value */
public void testGetAndUpdateWithSum() {
for (double x : VALUES) {
for (double y : VALUES) {
AtomicDouble a = new AtomicDouble(x);
double z = a.getAndUpdate(value -> value + y);
assertBitEquals(x, z);
assertBitEquals(x + y, a.get());
}
}
}
/**
* getAndUpdate with subtract stores subtraction of value from current, and returns previous value
*/
public void testGetAndUpdateWithSubtract() {
for (double x : VALUES) {
for (double y : VALUES) {
AtomicDouble a = new AtomicDouble(x);
double z = a.getAndUpdate(value -> value - y);
assertBitEquals(x, z);
assertBitEquals(x - y, a.get());
}
}
}
/** updateAndGet with sum stores sum of given value to current, and returns current value */
public void testUpdateAndGetWithSum() {
for (double x : VALUES) {
for (double y : VALUES) {
AtomicDouble a = new AtomicDouble(x);
double z = a.updateAndGet(value -> value + y);
assertBitEquals(x + y, z);
assertBitEquals(x + y, a.get());
}
}
}
/**
* updateAndGet with subtract stores subtraction of value from current, and returns current value
*/
public void testUpdateAndGetWithSubtract() {
for (double x : VALUES) {
for (double y : VALUES) {
AtomicDouble a = new AtomicDouble(x);
double z = a.updateAndGet(value -> value - y);
assertBitEquals(x - y, z);
assertBitEquals(x - y, a.get());
}
}
}
/** a deserialized serialized atomic holds same value */
public void testSerialization() throws Exception {
AtomicDouble a = new AtomicDouble();
AtomicDouble b = serialClone(a);
assertNotSame(a, b);
a.set(-22.0);
AtomicDouble c = serialClone(a);
assertNotSame(b, c);
assertBitEquals(-22.0, a.get());
assertBitEquals(0.0, b.get());
assertBitEquals(-22.0, c.get());
for (double x : VALUES) {
AtomicDouble d = new AtomicDouble(x);
assertBitEquals(serialClone(d).get(), d.get());
}
}
/** toString returns current value */
public void testToString() {
AtomicDouble at = new AtomicDouble();
assertEquals("0.0", at.toString());
for (double x : VALUES) {
at.set(x);
assertEquals(Double.toString(x), at.toString());
}
}
/** intValue returns current value. */
public void testIntValue() {
AtomicDouble at = new AtomicDouble();
assertEquals(0, at.intValue());
for (double x : VALUES) {
at.set(x);
assertEquals((int) x, at.intValue());
}
}
/** longValue returns current value. */
public void testLongValue() {
AtomicDouble at = new AtomicDouble();
assertEquals(0L, at.longValue());
for (double x : VALUES) {
at.set(x);
assertEquals((long) x, at.longValue());
}
}
/** floatValue returns current value. */
public void testFloatValue() {
AtomicDouble at = new AtomicDouble();
assertEquals(0.0f, at.floatValue());
for (double x : VALUES) {
at.set(x);
assertEquals((float) x, at.floatValue());
}
}
/** doubleValue returns current value. */
public void testDoubleValue() {
AtomicDouble at = new AtomicDouble();
assertThat(at.doubleValue()).isEqualTo(0.0d);
for (double x : VALUES) {
at.set(x);
assertBitEquals(x, at.doubleValue());
}
}
/** compareAndSet treats +0.0 and -0.0 as distinct values */
public void testDistinctZeros() {
AtomicDouble at = new AtomicDouble(+0.0);
assertFalse(at.compareAndSet(-0.0, 7.0));
assertFalse(at.weakCompareAndSet(-0.0, 7.0));
assertBitEquals(+0.0, at.get());
assertTrue(at.compareAndSet(+0.0, -0.0));
assertBitEquals(-0.0, at.get());
assertFalse(at.compareAndSet(+0.0, 7.0));
assertFalse(at.weakCompareAndSet(+0.0, 7.0));
assertBitEquals(-0.0, at.get());
}
}
| AtomicDoubleTest |
java | apache__camel | components/camel-cxf/camel-cxf-soap/src/test/java/org/apache/camel/component/cxf/jaxws/HelloService.java | {
"start": 881,
"end": 1138
} | interface ____ {
String sayHello();
void ping();
int getInvocationCount();
String echo(String text) throws Exception;
Boolean echoBoolean(Boolean bool);
String complexParameters(List<String> par1, List<String> par2);
}
| HelloService |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/RBucketsRx.java | {
"start": 841,
"end": 1685
} | interface ____ {
/**
* Returns Redis object mapped by key. Result Map is not contains
* key-value entry for null values.
*
* @param <V> type of value
* @param keys - keys
* @return Map with name of bucket as key and bucket as value
*/
<V> Single<Map<String, V>> get(String... keys);
/**
* Try to save objects mapped by Redis key.
* If at least one of them is already exist then
* don't set none of them.
*
* @param buckets - map of buckets
* @return <code>true</code> if object has been set otherwise <code>false</code>
*/
Single<Boolean> trySet(Map<String, ?> buckets);
/**
* Saves objects mapped by Redis key.
*
* @param buckets - map of buckets
* @return void
*/
Completable set(Map<String, ?> buckets);
}
| RBucketsRx |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/capabilities/TranslationAware.java | {
"start": 3223,
"end": 3494
} | interface ____ extends TranslationAware {
/**
* Returns the field that only supports single-value semantics.
*/
Expression singleValueField();
}
/**
* How is this expression translatable?
*/
| SingleValueTranslationAware |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/vector/VectorFunction.java | {
"start": 334,
"end": 558
} | interface ____ vector functions. Makes possible to do implicit casting
* from multi values and hex strings to dense_vector field types, so parameters are actually
* processed as dense_vectors in vector functions
*/
public | for |
java | quarkusio__quarkus | core/processor/src/test/java/io/quarkus/annotation/processor/documentation/config/util/TypeUtilTest.java | {
"start": 173,
"end": 707
} | class ____ {
@Test
public void normalizeDurationValueTest() {
assertEquals("", TypeUtil.normalizeDurationValue(""));
assertEquals("1S", TypeUtil.normalizeDurationValue("1"));
assertEquals("1S", TypeUtil.normalizeDurationValue("1S"));
assertEquals("1S", TypeUtil.normalizeDurationValue("1s"));
// values are not validated here
assertEquals("1_000", TypeUtil.normalizeDurationValue("1_000"));
assertEquals("FOO", TypeUtil.normalizeDurationValue("foo"));
}
}
| TypeUtilTest |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/stream/LangCollectors.java | {
"start": 1769,
"end": 8556
} | class ____<T, A, R> implements Collector<T, A, R> {
private final BiConsumer<A, T> accumulator;
private final Set<Characteristics> characteristics;
private final BinaryOperator<A> combiner;
private final Function<A, R> finisher;
private final Supplier<A> supplier;
private SimpleCollector(final Supplier<A> supplier, final BiConsumer<A, T> accumulator, final BinaryOperator<A> combiner, final Function<A, R> finisher,
final Set<Characteristics> characteristics) {
this.supplier = supplier;
this.accumulator = accumulator;
this.combiner = combiner;
this.finisher = finisher;
this.characteristics = characteristics;
}
@Override
public BiConsumer<A, T> accumulator() {
return accumulator;
}
@Override
public Set<Characteristics> characteristics() {
return characteristics;
}
@Override
public BinaryOperator<A> combiner() {
return combiner;
}
@Override
public Function<A, R> finisher() {
return finisher;
}
@Override
public Supplier<A> supplier() {
return supplier;
}
}
private static final Set<Collector.Characteristics> CH_NOID = Collections.emptySet();
/**
* Delegates to {@link Stream#collect(Collector)} for a Stream on the given array.
*
* @param <T> The type of the array elements.
* @param <R> the type of the result.
* @param <A> the intermediate accumulation type of the {@code Collector}.
* @param collector the {@code Collector} describing the reduction.
* @param array The array, assumed to be unmodified during use, a null array treated as an empty array.
* @return the result of the reduction
* @see Stream#collect(Collector)
* @see Arrays#stream(Object[])
* @see Collectors
* @since 3.16.0
*/
@SafeVarargs
public static <T, R, A> R collect(final Collector<? super T, A, R> collector, final T... array) {
return Streams.of(array).collect(collector);
}
/**
* Returns a {@code Collector} that concatenates the input elements, separated by the specified delimiter, in encounter order.
* <p>
* This is a variation of {@link Collectors#joining()} that works with any element class, not just {@code CharSequence}.
* </p>
* <p>
* For example:
* </p>
*
* <pre>
* Stream.of(Long.valueOf(1), Long.valueOf(2), Long.valueOf(3))
* .collect(LangCollectors.joining())
* returns "123"
* </pre>
*
* @return A {@code Collector} which concatenates Object elements, separated by the specified delimiter, in encounter order.
*/
public static Collector<Object, ?, String> joining() {
return new SimpleCollector<>(StringBuilder::new, StringBuilder::append, StringBuilder::append, StringBuilder::toString, CH_NOID);
}
/**
* Returns a {@code Collector} that concatenates the input elements, separated by the specified delimiter, in encounter order.
* <p>
* This is a variation of {@link Collectors#joining(CharSequence)} that works with any element class, not just {@code CharSequence}.
* </p>
* <p>
* For example:
* </p>
*
* <pre>
* Stream.of(Long.valueOf(1), Long.valueOf(2), Long.valueOf(3))
* .collect(LangCollectors.joining("-"))
* returns "1-2-3"
* </pre>
*
* @param delimiter the delimiter to be used between each element.
* @return A {@code Collector} which concatenates Object elements, separated by the specified delimiter, in encounter order.
*/
public static Collector<Object, ?, String> joining(final CharSequence delimiter) {
return joining(delimiter, StringUtils.EMPTY, StringUtils.EMPTY);
}
/**
* Returns a {@code Collector} that concatenates the input elements, separated by the specified delimiter, with the
* specified prefix and suffix, in encounter order.
* <p>
* This is a variation of {@link Collectors#joining(CharSequence, CharSequence, CharSequence)} that works with any
* element class, not just {@code CharSequence}.
* </p>
* <p>
* For example:
* </p>
*
* <pre>
* Stream.of(Long.valueOf(1), Long.valueOf(2), Long.valueOf(3))
* .collect(LangCollectors.joining("-", "[", "]"))
* returns "[1-2-3]"
* </pre>
*
* @param delimiter the delimiter to be used between each element
* @param prefix the sequence of characters to be used at the beginning of the joined result
* @param suffix the sequence of characters to be used at the end of the joined result
* @return A {@code Collector} which concatenates CharSequence elements, separated by the specified delimiter, in
* encounter order
*/
public static Collector<Object, ?, String> joining(final CharSequence delimiter, final CharSequence prefix, final CharSequence suffix) {
return joining(delimiter, prefix, suffix, Objects::toString);
}
/**
* Returns a {@code Collector} that concatenates the input elements, separated by the specified delimiter, with the specified prefix and suffix, in
* encounter order.
* <p>
* This is a variation of {@link Collectors#joining(CharSequence, CharSequence, CharSequence)} that works with any element class, not just
* {@code CharSequence}.
* </p>
* <p>
* For example:
* </p>
*
* <pre>{@code
* Stream.of(Long.valueOf(1), null, Long.valueOf(3))
* .collect(LangCollectors.joining("-", "[", "]", o -> Objects.toString(o, "NUL")))
* returns "[1-NUL-3]"
* }</pre>
*
* @param delimiter the delimiter to be used between each element
* @param prefix the sequence of characters to be used at the beginning of the joined result
* @param suffix the sequence of characters to be used at the end of the joined result
* @param toString A function that takes an Object and returns a non-null String.
* @return A {@code Collector} which concatenates CharSequence elements, separated by the specified delimiter, in encounter order
*/
public static Collector<Object, ?, String> joining(final CharSequence delimiter, final CharSequence prefix, final CharSequence suffix,
final Function<Object, String> toString) {
return new SimpleCollector<>(() -> new StringJoiner(delimiter, prefix, suffix), (a, t) -> a.add(toString.apply(t)), StringJoiner::merge,
StringJoiner::toString, CH_NOID);
}
private LangCollectors() {
// No instance
}
}
| SimpleCollector |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/support/MessageSourceSupport.java | {
"start": 1481,
"end": 6568
} | class ____ {
private static final MessageFormat INVALID_MESSAGE_FORMAT = new MessageFormat("");
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
private boolean alwaysUseMessageFormat = false;
/**
* Cache to hold already generated MessageFormats per message.
* Used for passed-in default messages. MessageFormats for resolved
* codes are cached on a specific basis in subclasses.
*/
private final Map<String, Map<Locale, MessageFormat>> messageFormatsPerMessage = new ConcurrentHashMap<>();
/**
* Set whether to always apply the {@code MessageFormat} rules, parsing even
* messages without arguments.
* <p>Default is {@code false}: Messages without arguments are by default
* returned as-is, without parsing them through {@code MessageFormat}.
* Set this to {@code true} to enforce {@code MessageFormat} for all messages,
* expecting all message texts to be written with {@code MessageFormat} escaping.
* <p>For example, {@code MessageFormat} expects a single quote to be escaped
* as two adjacent single quotes ({@code "''"}). If your message texts are all
* written with such escaping, even when not defining argument placeholders,
* you need to set this flag to {@code true}. Otherwise, only message texts
* with actual arguments are supposed to be written with {@code MessageFormat}
* escaping.
* @see java.text.MessageFormat
*/
public void setAlwaysUseMessageFormat(boolean alwaysUseMessageFormat) {
this.alwaysUseMessageFormat = alwaysUseMessageFormat;
}
/**
* Return whether to always apply the {@code MessageFormat} rules, parsing even
* messages without arguments.
*/
protected boolean isAlwaysUseMessageFormat() {
return this.alwaysUseMessageFormat;
}
/**
* Render the given default message String. The default message is
* passed in as specified by the caller and can be rendered into
* a fully formatted default message shown to the user.
* <p>The default implementation passes the String to {@code formatMessage},
* resolving any argument placeholders found in them. Subclasses may override
* this method to plug in custom processing of default messages.
* @param defaultMessage the passed-in default message String
* @param args array of arguments that will be filled in for params within
* the message, or {@code null} if none.
* @param locale the Locale used for formatting
* @return the rendered default message (with resolved arguments)
* @see #formatMessage(String, Object[], java.util.Locale)
*/
protected String renderDefaultMessage(String defaultMessage, Object @Nullable [] args, @Nullable Locale locale) {
return formatMessage(defaultMessage, args, locale);
}
/**
* Format the given message String, using cached MessageFormats.
* By default invoked for passed-in default messages, to resolve
* any argument placeholders found in them.
* @param msg the message to format
* @param args array of arguments that will be filled in for params within
* the message, or {@code null} if none
* @param locale the Locale used for formatting
* @return the formatted message (with resolved arguments)
*/
protected String formatMessage(String msg, Object @Nullable [] args, @Nullable Locale locale) {
if (!isAlwaysUseMessageFormat() && ObjectUtils.isEmpty(args)) {
return msg;
}
Map<Locale, MessageFormat> messageFormatsPerLocale = this.messageFormatsPerMessage
.computeIfAbsent(msg, key -> new ConcurrentHashMap<>());
MessageFormat messageFormat = messageFormatsPerLocale.computeIfAbsent(locale, key -> {
try {
return createMessageFormat(msg, locale);
}
catch (IllegalArgumentException ex) {
// Invalid message format - probably not intended for formatting,
// rather using a message structure with no arguments involved...
if (isAlwaysUseMessageFormat()) {
throw ex;
}
// Silently proceed with raw message if format not enforced...
return INVALID_MESSAGE_FORMAT;
}
});
if (messageFormat == INVALID_MESSAGE_FORMAT) {
return msg;
}
synchronized (messageFormat) {
return messageFormat.format(resolveArguments(args, locale));
}
}
/**
* Create a {@code MessageFormat} for the given message and Locale.
* @param msg the message to create a {@code MessageFormat} for
* @param locale the Locale to create a {@code MessageFormat} for
* @return the {@code MessageFormat} instance
*/
protected MessageFormat createMessageFormat(String msg, @Nullable Locale locale) {
return new MessageFormat(msg, locale);
}
/**
* Template method for resolving argument objects.
* <p>The default implementation simply returns the given argument array as-is.
* Can be overridden in subclasses in order to resolve special argument types.
* @param args the original argument array
* @param locale the Locale to resolve against
* @return the resolved argument array
*/
protected Object[] resolveArguments(Object @Nullable [] args, @Nullable Locale locale) {
return (args != null ? args : new Object[0]);
}
}
| MessageSourceSupport |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/basic/StaticMethodInvokerTest.java | {
"start": 683,
"end": 3186
} | class ____ {
@RegisterExtension
public ArcTestContainer container = ArcTestContainer.builder()
.beanClasses(MyService.class)
.beanRegistrars(new InvokerHelperRegistrar(MyService.class, (bean, factory, invokers) -> {
MethodInfo hello = bean.getImplClazz().firstMethod("hello");
MethodInfo doSomething = bean.getImplClazz().firstMethod("doSomething");
MethodInfo fail = bean.getImplClazz().firstMethod("fail");
for (MethodInfo method : List.of(hello, doSomething, fail)) {
invokers.put(method.name(), factory.createInvoker(bean, method).build());
}
}))
.build();
@Test
public void test() throws Exception {
InvokerHelper helper = Arc.container().instance(InvokerHelper.class).get();
InstanceHandle<MyService> service = Arc.container().instance(MyService.class);
Invoker<MyService, String> hello = helper.getInvoker("hello");
assertEquals("foobar0[]", hello.invoke(service.get(), new Object[] { 0, List.of() }));
assertEquals("foobar1[]", hello.invoke(new MyService(), new Object[] { 1, List.of() }));
assertEquals("foobar2[]", hello.invoke(null, new Object[] { 2, List.of() }));
Invoker<Object, Object> helloDetyped = (Invoker) hello;
assertEquals("foobar3[]", helloDetyped.invoke(service.get(), new Object[] { 3, List.of() }));
assertEquals("foobar4[]", helloDetyped.invoke(new MyService(), new Object[] { 4, List.of() }));
assertEquals("foobar5[]", helloDetyped.invoke(null, new Object[] { 5, List.of() }));
Invoker<MyService, Void> doSomething = helper.getInvoker("doSomething");
assertEquals(0, MyService.counter);
assertNull(doSomething.invoke(service.get(), null));
assertEquals(1, MyService.counter);
assertNull(doSomething.invoke(new MyService(), new Object[] {}));
assertEquals(2, MyService.counter);
assertNull(doSomething.invoke(null, new Object[] {}));
assertEquals(3, MyService.counter);
Invoker<MyService, Void> fail = helper.getInvoker("fail");
assertNull(fail.invoke(null, new Object[] { false }));
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> {
fail.invoke(null, new Object[] { true });
});
assertEquals("expected", ex.getMessage());
}
@Singleton
static | StaticMethodInvokerTest |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainRefCountingTests.java | {
"start": 3882,
"end": 5434
} | class ____ implements ActionFilter {
private final ThreadPool threadPool;
private final int order = randomInt();
private TestAsyncActionFilter(ThreadPool threadPool) {
this.threadPool = Objects.requireNonNull(threadPool);
}
@Override
public int order() {
return order;
}
@Override
public <Req extends ActionRequest, Rsp extends ActionResponse> void apply(
Task task,
String action,
Req request,
ActionListener<Rsp> listener,
ActionFilterChain<Req, Rsp> chain
) {
if (action.equals(TYPE.name())) {
randomFrom(EsExecutors.DIRECT_EXECUTOR_SERVICE, threadPool.generic()).execute(new AbstractRunnable() {
@Override
public void onFailure(Exception e) {
fail(e);
}
@Override
protected void doRun() {
assertTrue(request.hasReferences());
if (randomBoolean()) {
chain.proceed(task, action, request, listener);
} else {
listener.onFailure(new ElasticsearchException("short-circuit failure"));
}
}
});
} else {
chain.proceed(task, action, request, listener);
}
}
}
private static | TestAsyncActionFilter |
java | apache__hadoop | hadoop-tools/hadoop-azure-datalake/src/test/java/org/apache/hadoop/fs/adl/live/TestAdlContractDeleteLive.java | {
"start": 1063,
"end": 1278
} | class ____ extends AbstractContractDeleteTest {
@Override
protected AbstractFSContract createContract(Configuration configuration) {
return new AdlStorageContract(configuration);
}
}
| TestAdlContractDeleteLive |
java | spring-projects__spring-boot | module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java | {
"start": 1435,
"end": 2591
} | class ____ implements ClientHttpRequestFactory {
private static final byte[] NO_DATA = {};
private final AtomicLong seq = new AtomicLong();
private final Deque<Object> responses = new ArrayDeque<>();
private final List<MockClientHttpRequest> executedRequests = new ArrayList<>();
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
return new MockRequest(uri, httpMethod);
}
public void willRespond(HttpStatus... response) {
for (HttpStatus status : response) {
this.responses.add(new Response(0, null, status));
}
}
public void willRespond(IOException... response) {
for (IOException exception : response) {
this.responses.addLast(exception);
}
}
public void willRespond(String... response) {
for (String payload : response) {
this.responses.add(new Response(0, payload.getBytes(), HttpStatus.OK));
}
}
public void willRespondAfterDelay(int delay, HttpStatus status) {
this.responses.add(new Response(delay, null, status));
}
public List<MockClientHttpRequest> getExecutedRequests() {
return this.executedRequests;
}
private | MockClientHttpRequestFactory |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/config/LocalResponseCacheAutoConfiguration.java | {
"start": 4919,
"end": 5133
} | class ____ {
}
@ConditionalOnProperty(name = GatewayProperties.PREFIX + ".global-filter.local-response-cache.enabled",
havingValue = "true", matchIfMissing = true)
static | OnLocalResponseCachePropertyEnabled |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/join/deltajoin/StreamingDeltaJoinOperatorTest.java | {
"start": 73631,
"end": 77591
} | class ____ {
abstract RowType getLeftInputRowType();
final InternalTypeInfo<RowData> getLeftTypeInfo() {
return InternalTypeInfo.of(getLeftInputRowType());
}
abstract Optional<int[]> getLeftUpsertKey();
final RowDataKeySelector getLeftUpsertKeySelector() {
return getUpsertKeySelector(getLeftInputRowType(), getLeftUpsertKey().orElse(null));
}
abstract RowType getRightInputRowType();
final InternalTypeInfo<RowData> getRightTypeInfo() {
return InternalTypeInfo.of(getRightInputRowType());
}
abstract Optional<int[]> getRightUpsertKey();
final RowDataKeySelector getRightUpsertKeySelector() {
return getUpsertKeySelector(getRightInputRowType(), getRightUpsertKey().orElse(null));
}
abstract int[] getLeftJoinKeyIndices();
final RowDataKeySelector getLeftJoinKeySelector() {
return HandwrittenSelectorUtil.getRowDataSelector(
getLeftJoinKeyIndices(),
getLeftInputRowType().getChildren().toArray(new LogicalType[0]));
}
abstract int[] getRightJoinKeyIndices();
final RowDataKeySelector getRightJoinKeySelector() {
return HandwrittenSelectorUtil.getRowDataSelector(
getRightJoinKeyIndices(),
getRightInputRowType().getChildren().toArray(new LogicalType[0]));
}
final RowType getOutputRowType() {
return RowType.of(
Stream.concat(
getLeftInputRowType().getChildren().stream(),
getRightInputRowType().getChildren().stream())
.toArray(LogicalType[]::new),
Stream.concat(
getLeftInputRowType().getFieldNames().stream(),
getRightInputRowType().getFieldNames().stream())
.toArray(String[]::new));
}
final int[] getOutputFieldIndices() {
return IntStream.range(0, getOutputRowType().getFieldCount()).toArray();
}
abstract Optional<Function<RowData, Boolean>> getFilterOnLeftTable();
abstract Optional<Function<RowData, Boolean>> getFilterOnRightTable();
private RowDataKeySelector getUpsertKeySelector(
RowType rowType, @Nullable int[] upsertKey) {
if (upsertKey == null) {
upsertKey = IntStream.range(0, rowType.getFieldCount()).toArray();
}
return HandwrittenSelectorUtil.getRowDataSelector(
upsertKey, rowType.getChildren().toArray(new LogicalType[0]));
}
}
/**
* Mock sql like the following.
*
* <pre>
* CREATE TABLE leftSrc(
* left_value INT,
* left_jk1 BOOLEAN,
* left_jk2_index STRING,
* INDEX(left_jk2_index)
* )
* </pre>
*
* <pre>
* CREATE TABLE rightSrc(
* right_jk2 STRING,
* right_value INT,
* right_jk1_index BOOLEAN,
* INDEX(right_jk1_index)
* )
* </pre>
*
* <p>If the flag {@link #filterOnTable} is false, the query is:
*
* <pre>
* select * from leftSrc join rightSrc
* on leftSrc.left_jk1 = rightSrc.right_jk1_index
* and leftSrc.left_jk2_index = rightSrc.right_jk2
* </pre>
*
* <p>If the flag {@link #filterOnTable} is true, the query is:
*
* <pre>
* select * from (
* select * from leftSrc where left_jk1 = 'true'
* ) join (
* select * from rightSrc where right_jk2 = 'jklk1'
* ) on left_jk1 = right_jk1_index
* and left_jk2_index = right_jk2
* </pre>
*/
private static | AbstractTestSpec |
java | quarkusio__quarkus | integration-tests/picocli/src/test/java/io/quarkus/it/picocli/TestOneCommand.java | {
"start": 395,
"end": 958
} | class ____ {
@RegisterExtension
static final QuarkusProdModeTest config = createConfig("hello-app", HelloCommand.class, EventListener.class)
.setCommandLineParameters("--name=Tester");
@Test
public void simpleTest() {
Assertions.assertThat(config.getStartupConsoleOutput()).containsOnlyOnce("ParseResult Event: Tester");
Assertions.assertThat(config.getStartupConsoleOutput()).containsOnlyOnce("Hello Tester!");
Assertions.assertThat(config.getExitCode()).isZero();
}
@Dependent
static | TestOneCommand |
java | FasterXML__jackson-core | src/test/java/tools/jackson/core/unittest/sym/SymbolsViaParserTest.java | {
"start": 577,
"end": 3601
} | class ____
extends tools.jackson.core.unittest.JacksonCoreTestBase
{
// for [jackson-core#213]
@Test
void test17CharSymbols() throws Exception {
_test17Chars(false);
}
// for [jackson-core#213]
@Test
void test17ByteSymbols() throws Exception {
_test17Chars(true);
}
// for [jackson-core#216]
@Test
void symbolTableExpansionChars() throws Exception {
_testSymbolTableExpansion(false);
}
// for [jackson-core#216]
@Test
void symbolTableExpansionBytes() throws Exception {
_testSymbolTableExpansion(true);
}
/*
/**********************************************************
/* Secondary test methods
/**********************************************************
*/
private void _test17Chars(boolean useBytes) throws IOException
{
String doc = _createDoc17();
JsonFactory f = new JsonFactory();
JsonParser p = useBytes
? f.createParser(ObjectReadContext.empty(), doc.getBytes(StandardCharsets.UTF_8))
: f.createParser(ObjectReadContext.empty(), doc);
HashSet<String> syms = new HashSet<>();
assertToken(JsonToken.START_OBJECT, p.nextToken());
for (int i = 0; i < 50; ++i) {
assertToken(JsonToken.PROPERTY_NAME, p.nextToken());
syms.add(p.currentName());
assertToken(JsonToken.VALUE_TRUE, p.nextToken());
}
assertToken(JsonToken.END_OBJECT, p.nextToken());
assertEquals(50, syms.size());
p.close();
}
private String _createDoc17() {
StringBuilder sb = new StringBuilder(1000);
sb.append("{\n");
for (int i = 1; i <= 50; ++i) {
if (i > 1) {
sb.append(",\n");
}
sb.append("\"lengthmatters")
.append(1000 + i)
.append("\": true");
}
sb.append("\n}");
return sb.toString();
}
public void _testSymbolTableExpansion(boolean useBytes) throws Exception
{
JsonFactory jsonFactory = new JsonFactory();
// Important: must create separate documents to gradually build up symbol table
for (int i = 0; i < 200; i++) {
String field = Integer.toString(i);
final String doc = "{ \"" + field + "\" : \"test\" }";
JsonParser parser = useBytes
? jsonFactory.createParser(ObjectReadContext.empty(), doc.getBytes("UTF-8"))
: jsonFactory.createParser(ObjectReadContext.empty(), doc);
assertToken(JsonToken.START_OBJECT, parser.nextToken());
assertToken(JsonToken.PROPERTY_NAME, parser.nextToken());
assertEquals(field, parser.currentName());
assertToken(JsonToken.VALUE_STRING, parser.nextToken());
assertToken(JsonToken.END_OBJECT, parser.nextToken());
assertNull(parser.nextToken());
parser.close();
}
}
}
| SymbolsViaParserTest |
java | spring-projects__spring-security | config/src/main/java/org/springframework/security/config/http/Saml2LoginBeanDefinitionParser.java | {
"start": 14037,
"end": 14112
} | class ____ provide configuration from applicationContext
*/
public static | to |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.