language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/util/DualClass.java
{ "start": 763, "end": 903 }
class ____. * * @param <A> Type of the actual value * @param <E> Type of the expected value * @author Alessandro Modolo */ public
reference
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java
{ "start": 41115, "end": 41410 }
class ____<T extends CharSequence> implements FactoryBean<T>, MyGenericInterfaceForFactoryBeans<T> { @Override public T getObject() { throw new UnsupportedOperationException(); } @Override public Class<?> getObjectType() { return String.class; } } public static
MyFactoryBean
java
apache__camel
tooling/openapi-rest-dsl-generator/src/main/java/org/apache/camel/generator/openapi/MethodBodySourceCodeEmitter.java
{ "start": 1190, "end": 5259 }
class ____ implements CodeEmitter<MethodSpec> { private final MethodSpec.Builder builder; private boolean first = true; private final Deque<Integer> indentIntentStack = new ArrayDeque<>(); private final Deque<Integer> indentStack = new ArrayDeque<>(); MethodBodySourceCodeEmitter(final MethodSpec.Builder builder) { this.builder = builder; indentStack.push(0); } @Override public CodeEmitter<MethodSpec> emit(final String method, final Object... args) { final boolean hasArgs = args != null && args.length > 0; final int indent = indentLevelOf(method); if (!first || indent == 0) { builder.addCode("\n"); } builder.addCode(String.join("", Collections.nCopies(indentStack.peek(), "$<"))); builder.addCode(String.join("", Collections.nCopies(indent, "$>"))); if (!first) { builder.addCode("."); } indentStack.push(indent); if (hasArgs) { builder.addCode("$L(" + invocationLiteralsFor(args) + ")", extend(method, argumentsFor(args))); } else { builder.addCode("$L()", method); } first = false; return this; } public void endEmit() { builder.addCode(";\n"); first = true; } @Override public MethodSpec result() { builder.addCode(String.join("", Collections.nCopies(indentStack.peek(), "$<"))); builder.addCode("\n"); return builder.build(); } int indentLevelOf(final String method) { switch (method) { case "rest": return 0; case "post": case "get": case "put": case "patch": case "delete": case "head": case "options": return 1; case "param": indentIntentStack.push(3); return 2; case "endParam": indentIntentStack.pop(); return 2; case "route": indentIntentStack.push(3); return 2; case "endRest": indentIntentStack.pop(); return 2; default: if (indentIntentStack.isEmpty()) { return 2; } return indentIntentStack.peek(); } } String invocationLiteralsFor(final Object[] args) { final StringJoiner literals = new StringJoiner(","); for (final Object arg : args) { if (isPrimitiveOrWrapper(arg.getClass())) { literals.add("$L"); } else if (arg instanceof String) { literals.add("$S"); } else if (arg instanceof Enum) { literals.add("$T.$L"); } else if (arg instanceof String[]) { literals.add("$S"); } } return literals.toString(); } static Object[] argumentsFor(final Object[] args) { final List<Object> arguments = new ArrayList<>(args.length); for (final Object arg : args) { if (isPrimitiveOrWrapper(arg.getClass())) { arguments.add(arg); } else if (arg instanceof String) { arguments.add(arg); } else if (arg instanceof Enum) { arguments.add(arg.getClass()); arguments.add(arg); } else if (arg instanceof String[]) { arguments.add(Arrays.stream((String[]) arg).collect(Collectors.joining(","))); } } return arguments.toArray(new Object[0]); } static Object[] extend(final Object first, final Object... others) { if (others == null || others.length == 0) { return new Object[] { first }; } final Object[] ret = new Object[1 + others.length]; ret[0] = first; System.arraycopy(others, 0, ret, 1, others.length); return ret; } }
MethodBodySourceCodeEmitter
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java
{ "start": 935, "end": 1108 }
interface ____ {@link IntConsumer} that declares a {@link Throwable}. * * @param <E> The kind of thrown exception or error. * @since 3.11 */ @FunctionalInterface public
like
java
apache__dubbo
dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/ServerVariable.java
{ "start": 1016, "end": 2706 }
class ____ extends Node<ServerVariable> { private List<String> enumeration; private String defaultValue; private String description; public List<String> getEnumeration() { return enumeration; } public ServerVariable setEnumeration(List<String> enumeration) { this.enumeration = enumeration; return this; } public ServerVariable addEnumeration(String value) { if (enumeration == null) { enumeration = new ArrayList<>(); } enumeration.add(value); return this; } public ServerVariable removeEnumeration(String value) { if (enumeration != null) { enumeration.remove(value); } return this; } public String getDefaultValue() { return defaultValue; } public ServerVariable setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; return this; } public String getDescription() { return description; } public ServerVariable setDescription(String description) { this.description = description; return this; } @Override public ServerVariable clone() { ServerVariable clone = super.clone(); if (enumeration != null) { clone.enumeration = new ArrayList<>(enumeration); } return clone; } @Override public Map<String, Object> writeTo(Map<String, Object> node, Context context) { write(node, "enum", enumeration); write(node, "default", defaultValue); write(node, "description", description); writeExtensions(node); return node; } }
ServerVariable
java
apache__maven
compat/maven-model/src/test/java/org/apache/maven/model/ActivationTest.java
{ "start": 1099, "end": 1647 }
class ____ { @Test void testHashCodeNullSafe() { new Activation().hashCode(); } @Test void testEqualsNullSafe() { assertFalse(new Activation().equals(null)); new Activation().equals(new Activation()); } @Test void testEqualsIdentity() { Activation thing = new Activation(); assertTrue(thing.equals(thing), "Expected " + thing + " to equal " + thing); } @Test void testToStringNullSafe() { assertNotNull(new Activation().toString()); } }
ActivationTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/PreferredInterfaceTypeTest.java
{ "start": 25324, "end": 25834 }
class ____ { // BUG: Diagnostic contains: static final ImmutableSet<String> FOO = static final Set<String> FOO = ImmutableSet.<String>builder().build(); } """) .doTest(); } @Test public void staticFinalListInitializedInDeclarationWithImmutableListOf() { testHelper .addSourceLines( "Test.java", """ import com.google.common.collect.ImmutableList; import java.util.List;
Test
java
apache__kafka
connect/runtime/src/test/resources/test-plugins/bad-packaging/test/plugins/DefaultConstructorPrivateConnector.java
{ "start": 1209, "end": 1797 }
class ____ extends SinkConnector { private DefaultConstructorPrivateConnector() { } @Override public String version() { return null; } @Override public void start(Map<String, String> props) { } @Override public Class<? extends Task> taskClass() { return null; } @Override public List<Map<String, String>> taskConfigs(int maxTasks) { return null; } @Override public void stop() { } @Override public ConfigDef config() { return null; } }
DefaultConstructorPrivateConnector
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java
{ "start": 18036, "end": 22356 }
class ____ stop appending fields for. */ private Class<?> upToClass; /** * Constructs a new instance. * * <p> * This constructor outputs using the default style set with {@code setDefaultStyle}. * </p> * * @param object * the Object to build a {@code toString} for, must not be {@code null} */ public ReflectionToStringBuilder(final Object object) { super(object); } /** * Constructs a new instance. * * <p> * If the style is {@code null}, the default style is used. * </p> * * @param object * the Object to build a {@code toString} for, must not be {@code null} * @param style * the style of the {@code toString} to create, may be {@code null} */ public ReflectionToStringBuilder(final Object object, final ToStringStyle style) { super(object, style); } /** * Constructs a new instance. * * <p> * If the style is {@code null}, the default style is used. * </p> * * <p> * If the buffer is {@code null}, a new one is created. * </p> * * @param object * the Object to build a {@code toString} for * @param style * the style of the {@code toString} to create, may be {@code null} * @param buffer * the {@link StringBuffer} to populate, may be {@code null} */ public ReflectionToStringBuilder(final Object object, final ToStringStyle style, final StringBuffer buffer) { super(object, style, buffer); } /** * Constructs a new instance. * * @param <T> * the type of the object * @param object * the Object to build a {@code toString} for * @param style * the style of the {@code toString} to create, may be {@code null} * @param buffer * the {@link StringBuffer} to populate, may be {@code null} * @param reflectUpToClass * the superclass to reflect up to (inclusive), may be {@code null} * @param outputTransients * whether to include transient fields * @param outputStatics * whether to include static fields * @since 2.1 */ public <T> ReflectionToStringBuilder( final T object, final ToStringStyle style, final StringBuffer buffer, final Class<? super T> reflectUpToClass, final boolean outputTransients, final boolean outputStatics) { super(object, style, buffer); setUpToClass(reflectUpToClass); setAppendTransients(outputTransients); setAppendStatics(outputStatics); } /** * Constructs a new instance. * * @param <T> * the type of the object * @param object * the Object to build a {@code toString} for * @param style * the style of the {@code toString} to create, may be {@code null} * @param buffer * the {@link StringBuffer} to populate, may be {@code null} * @param reflectUpToClass * the superclass to reflect up to (inclusive), may be {@code null} * @param outputTransients * whether to include transient fields * @param outputStatics * whether to include static fields * @param excludeNullValues * whether to exclude fields who value is null * @since 3.6 */ public <T> ReflectionToStringBuilder( final T object, final ToStringStyle style, final StringBuffer buffer, final Class<? super T> reflectUpToClass, final boolean outputTransients, final boolean outputStatics, final boolean excludeNullValues) { super(object, style, buffer); setUpToClass(reflectUpToClass); setAppendTransients(outputTransients); setAppendStatics(outputStatics); setExcludeNullValues(excludeNullValues); } /** * Returns whether or not to append the given {@link Field}. * <ul> * <li>Transient fields are appended only if {@link #isAppendTransients()} returns {@code true}. * <li>Static fields are appended only if {@link #isAppendStatics()} returns {@code true}. * <li>Inner
to
java
google__dagger
hilt-compiler/main/java/dagger/hilt/android/processor/internal/androidentrypoint/BroadcastReceiverGenerator.java
{ "start": 2602, "end": 5607 }
class ____$CLASS extends $BASE { // ... // } public void generate() throws IOException { TypeSpec.Builder builder = TypeSpec.classBuilder(generatedClassName.simpleName()) .superclass(metadata.baseClassName()) .addModifiers(metadata.generatedClassModifiers()) .addMethod(onReceiveMethod()); // Add an annotation used as a marker to let the bytecode injector know this receiver // will need to be injected with a super.onReceive call. This is only necessary if no concrete // onReceive call is implemented in any of the super classes. if (metadata.requiresBytecodeInjection() && !isOnReceiveImplemented(metadata.baseElement())) { builder.addAnnotation(ClassNames.ON_RECEIVE_BYTECODE_INJECTION_MARKER); } JavaPoetExtKt.addOriginatingElement(builder, metadata.element()); Generators.addGeneratedBaseClassJavadoc(builder, AndroidClassNames.ANDROID_ENTRY_POINT); Processors.addGeneratedAnnotation(builder, env, getClass()); Generators.copyConstructors(metadata.baseElement(), builder, metadata.element()); metadata.baseElement().getTypeParameters().stream() .map(XTypeParameterElement::getTypeVariableName) .forEachOrdered(builder::addTypeVariable); Generators.addInjectionMethods(metadata, builder); Generators.copyLintAnnotations(metadata.element(), builder); Generators.copySuppressAnnotations(metadata.element(), builder); env.getFiler() .write( JavaFile.builder(generatedClassName.packageName(), builder.build()).build(), XFiler.Mode.Isolating); } private static boolean isOnReceiveImplemented(XTypeElement typeElement) { boolean isImplemented = typeElement.getDeclaredMethods().stream() .filter(method -> !method.isAbstract()) .anyMatch(method -> method.getJvmDescriptor().equals(ON_RECEIVE_DESCRIPTOR)); if (isImplemented) { return true; } else if (typeElement.getSuperClass() != null) { return isOnReceiveImplemented(typeElement.getSuperClass().getTypeElement()); } else { return false; } } // @Override // public void onReceive(Context context, Intent intent) { // inject(context); // super.onReceive(); // } private MethodSpec onReceiveMethod() throws IOException { MethodSpec.Builder method = MethodSpec.methodBuilder("onReceive") .addAnnotation(Override.class) .addAnnotation(AndroidClassNames.CALL_SUPER) .addModifiers(Modifier.PUBLIC) .addParameter(ParameterSpec.builder(AndroidClassNames.CONTEXT, "context").build()) .addParameter(ParameterSpec.builder(AndroidClassNames.INTENT, "intent").build()) .addStatement("inject(context)"); if (metadata.overridesAndroidEntryPointClass()) { // We directly call super.onReceive here because we know Hilt base classes have a // non-abstract onReceive method. However, because the Hilt base
Hilt_
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/GenerationGroup.java
{ "start": 310, "end": 649 }
class ____ { @Id @GeneratedValue private int id; private Generation generation; public int getId() { return id; } public void setId(int id) { this.id = id; } public Generation getGeneration() { return generation; } public void setGeneration(Generation generation) { this.generation = generation; } }
GenerationGroup
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/index/LookupIndexModeIT.java
{ "start": 1676, "end": 10529 }
class ____ extends ESIntegTestCase { @Override protected int numberOfShards() { return 1; } public void testBasic() { internalCluster().ensureAtLeastNumDataNodes(1); Settings.Builder lookupSettings = Settings.builder().put("index.mode", "lookup"); if (randomBoolean()) { lookupSettings.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1); } CreateIndexRequest createRequest = new CreateIndexRequest("hosts"); createRequest.settings(lookupSettings); createRequest.simpleMapping("ip", "type=ip", "os", "type=keyword"); assertAcked(client().admin().indices().execute(TransportCreateIndexAction.TYPE, createRequest)); Settings settings = client().admin() .indices() .prepareGetSettings(TEST_REQUEST_TIMEOUT, "hosts") .get() .getIndexToSettings() .get("hosts"); assertThat(settings.get("index.mode"), equalTo("lookup")); assertNull(settings.get("index.auto_expand_replicas")); Map<String, String> allHosts = Map.of( "192.168.1.2", "Windows", "192.168.1.3", "MacOS", "192.168.1.4", "Linux", "192.168.1.5", "Android", "192.168.1.6", "iOS", "192.168.1.7", "Windows", "192.168.1.8", "MacOS", "192.168.1.9", "Linux", "192.168.1.10", "Linux", "192.168.1.11", "Windows" ); for (Map.Entry<String, String> e : allHosts.entrySet()) { client().prepareIndex("hosts").setSource("ip", e.getKey(), "os", e.getValue()).get(); } refresh("hosts"); assertAcked(client().admin().indices().prepareCreate("events").setSettings(Settings.builder().put("index.mode", "logsdb")).get()); int numDocs = between(1, 10); for (int i = 0; i < numDocs; i++) { String ip = randomFrom(allHosts.keySet()); String message = randomFrom("login", "logout", "shutdown", "restart"); client().prepareIndex("events").setSource("@timestamp", "2024-01-01", "ip", ip, "message", message).get(); } refresh("events"); // _search { SearchResponse resp = prepareSearch("events", "hosts").setQuery(new MatchQueryBuilder("_index_mode", "lookup")) .setSize(10000) .get(); for (SearchHit hit : resp.getHits()) { assertThat(hit.getIndex(), equalTo("hosts")); } assertHitCount(resp, allHosts.size()); resp.decRef(); } // field_caps { FieldCapabilitiesRequest request = new FieldCapabilitiesRequest(); request.indices("events", "hosts"); request.fields("*"); request.setMergeResults(false); request.indexFilter(new MatchQueryBuilder("_index_mode", "lookup")); var resp = client().fieldCaps(request).actionGet(); assertThat(resp.getIndexResponses(), hasSize(1)); FieldCapabilitiesIndexResponse indexResponse = resp.getIndexResponses().getFirst(); assertThat(indexResponse.getIndexMode(), equalTo(IndexMode.LOOKUP)); assertThat(indexResponse.getIndexName(), equalTo("hosts")); } } public void testRejectMoreThanOneShard() { int numberOfShards = between(2, 5); IllegalArgumentException error = expectThrows(IllegalArgumentException.class, () -> { client().admin() .indices() .prepareCreate("hosts") .setSettings(Settings.builder().put("index.mode", "lookup").put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, numberOfShards)) .setMapping("ip", "type=ip", "os", "type=keyword") .get(); }); assertThat( error.getMessage(), equalTo("index with [lookup] mode must have [index.number_of_shards] set to 1 or unset; provided " + numberOfShards) ); } public void testResizeLookupIndex() { Settings.Builder createSettings = Settings.builder().put("index.mode", "lookup"); if (randomBoolean()) { createSettings.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1); } CreateIndexRequest createIndexRequest = new CreateIndexRequest("lookup-1").settings(createSettings); assertAcked(client().admin().indices().execute(TransportCreateIndexAction.TYPE, createIndexRequest)); client().admin().indices().prepareAddBlock(IndexMetadata.APIBlock.WRITE, "lookup-1").get(); assertAcked(ResizeIndexTestUtils.executeResize(ResizeType.CLONE, "lookup-1", "lookup-2", Settings.builder())); Settings settings = client().admin() .indices() .prepareGetSettings(TEST_REQUEST_TIMEOUT, "lookup-2") .get() .getIndexToSettings() .get("lookup-2"); assertThat(settings.get("index.mode"), equalTo("lookup")); assertThat(settings.get("index.number_of_shards"), equalTo("1")); ResizeRequest split = ResizeIndexTestUtils.resizeRequest( ResizeType.SPLIT, "lookup-1", "lookup-3", Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 3) ); IllegalArgumentException error = expectThrows( IllegalArgumentException.class, () -> client().execute(TransportResizeAction.TYPE, split).actionGet() ); assertThat( error.getMessage(), equalTo("index with [lookup] mode must have [index.number_of_shards] set to 1 or unset; provided 3") ); } public void testResizeRegularIndexToLookup() { String dataNode = internalCluster().startDataOnlyNode(); assertAcked( client().admin() .indices() .prepareCreate("regular-1") .setSettings( Settings.builder() .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 2) .put("index.routing.allocation.require._name", dataNode) ) .setMapping("ip", "type=ip", "os", "type=keyword") .get() ); client().admin().indices().prepareAddBlock(IndexMetadata.APIBlock.WRITE, "regular-1").get(); client().admin() .indices() .prepareUpdateSettings("regular-1") .setSettings(Settings.builder().put("index.number_of_replicas", 0)) .get(); ResizeRequest clone = ResizeIndexTestUtils.resizeRequest( ResizeType.CLONE, "regular-1", "lookup-3", Settings.builder().put("index.mode", "lookup") ); IllegalArgumentException error = expectThrows( IllegalArgumentException.class, () -> client().execute(TransportResizeAction.TYPE, clone).actionGet() ); assertThat( error.getMessage(), equalTo("index with [lookup] mode must have [index.number_of_shards] set to 1 or unset; provided 2") ); ResizeRequest shrink = ResizeIndexTestUtils.resizeRequest( ResizeType.SHRINK, "regular-1", "lookup-4", Settings.builder().put("index.mode", "lookup").put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1) ); error = expectThrows(IllegalArgumentException.class, () -> client().execute(TransportResizeAction.TYPE, shrink).actionGet()); assertThat(error.getMessage(), equalTo("can't change setting [index.mode] during resize")); } public void testDoNotOverrideAutoExpandReplicas() { internalCluster().ensureAtLeastNumDataNodes(1); Settings.Builder createSettings = Settings.builder().put("index.mode", "lookup"); if (randomBoolean()) { createSettings.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1); } createSettings.put("index.auto_expand_replicas", "3-5"); CreateIndexRequest createRequest = new CreateIndexRequest("hosts"); createRequest.settings(createSettings); createRequest.simpleMapping("ip", "type=ip", "os", "type=keyword"); assertAcked(client().admin().indices().execute(TransportCreateIndexAction.TYPE, createRequest)); Settings settings = client().admin() .indices() .prepareGetSettings(TEST_REQUEST_TIMEOUT, "hosts") .get() .getIndexToSettings() .get("hosts"); assertThat(settings.get("index.mode"), equalTo("lookup")); assertThat(settings.get("index.auto_expand_replicas"), equalTo("3-5")); } }
LookupIndexModeIT
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/LongArrayState.java
{ "start": 1465, "end": 4797 }
class ____ extends AbstractArrayState implements GroupingAggregatorState { private final long init; private LongArray values; LongArrayState(BigArrays bigArrays, long init) { super(bigArrays); this.values = bigArrays.newLongArray(1, false); this.values.set(0, init); this.init = init; } long get(int groupId) { return values.get(groupId); } long getOrDefault(int groupId) { return groupId < values.size() ? values.get(groupId) : init; } void set(int groupId, long value) { ensureCapacity(groupId); values.set(groupId, value); trackGroupId(groupId); } void increment(int groupId, long value) { ensureCapacity(groupId); values.increment(groupId, value); trackGroupId(groupId); } Block toValuesBlock(org.elasticsearch.compute.data.IntVector selected, DriverContext driverContext) { if (false == trackingGroupIds()) { try (var builder = driverContext.blockFactory().newLongVectorFixedBuilder(selected.getPositionCount())) { for (int i = 0; i < selected.getPositionCount(); i++) { builder.appendLong(i, values.get(selected.getInt(i))); } return builder.build().asBlock(); } } try (LongBlock.Builder builder = driverContext.blockFactory().newLongBlockBuilder(selected.getPositionCount())) { for (int i = 0; i < selected.getPositionCount(); i++) { int group = selected.getInt(i); if (hasValue(group)) { builder.appendLong(values.get(group)); } else { builder.appendNull(); } } return builder.build(); } } private void ensureCapacity(int groupId) { if (groupId >= values.size()) { long prevSize = values.size(); values = bigArrays.grow(values, groupId + 1); values.fill(prevSize, values.size(), init); } } /** Extracts an intermediate view of the contents of this state. */ @Override public void toIntermediate( Block[] blocks, int offset, IntVector selected, org.elasticsearch.compute.operator.DriverContext driverContext ) { assert blocks.length >= offset + 2; try ( var valuesBuilder = driverContext.blockFactory().newLongBlockBuilder(selected.getPositionCount()); var hasValueBuilder = driverContext.blockFactory().newBooleanVectorFixedBuilder(selected.getPositionCount()) ) { for (int i = 0; i < selected.getPositionCount(); i++) { int group = selected.getInt(i); if (group < values.size()) { valuesBuilder.appendLong(values.get(group)); } else { valuesBuilder.appendLong(0); // TODO can we just use null? } hasValueBuilder.appendBoolean(i, hasValue(group)); } blocks[offset + 0] = valuesBuilder.build(); blocks[offset + 1] = hasValueBuilder.build().asBlock(); } } @Override public void close() { Releasables.close(values, super::close); } }
LongArrayState
java
apache__flink
flink-python/src/main/java/org/apache/flink/table/runtime/operators/python/aggregate/arrow/batch/BatchArrowPythonOverWindowAggregateFunctionOperator.java
{ "start": 2269, "end": 16245 }
class ____ extends AbstractBatchArrowPythonAggregateFunctionOperator { private static final long serialVersionUID = 1L; private static final String PANDAS_BATCH_OVER_WINDOW_AGG_FUNCTION_URN = "flink:transform:batch_over_window_aggregate_function:arrow:v1"; /** Used to serialize the boundary of range window. */ private static final IntSerializer windowBoundarySerializer = IntSerializer.INSTANCE; /** Window lower boundary. e.g. Long.MIN_VALUE means unbounded preceding. */ private final long[] lowerBoundary; /** Window upper boundary. e.g. Long.MAX_VALUE means unbounded following. */ private final long[] upperBoundary; /** Whether the specified position window is a range window. */ private final boolean[] isRangeWindows; /** The window index of the specified aggregate function belonging to. */ private final int[] aggWindowIndex; /** The row time index of the input data. */ private final int inputTimeFieldIndex; /** The order of row time. True for ascending. */ private final boolean asc; /** The type serializer for the forwarded fields. */ private transient RowDataSerializer forwardedInputSerializer; /** Stores the start position of the last key data in forwardedInputQueue. */ private transient int lastKeyDataStartPos; /** Reusable OutputStream used to holding the window boundary with input elements. */ private transient ByteArrayOutputStreamWithPos windowBoundaryWithDataBaos; /** OutputStream Wrapper. */ private transient DataOutputViewStreamWrapper windowBoundaryWithDataWrapper; /** Stores bounded range window boundaries. */ private transient List<List<Integer>> boundedRangeWindowBoundaries; /** Stores index of the bounded range window. */ private transient ArrayList<Integer> boundedRangeWindowIndex; public BatchArrowPythonOverWindowAggregateFunctionOperator( Configuration config, PythonFunctionInfo[] pandasAggFunctions, RowType inputType, RowType udfInputType, RowType udfOutputType, long[] lowerBoundary, long[] upperBoundary, boolean[] isRangeWindows, int[] aggWindowIndex, int inputTimeFieldIndex, boolean asc, GeneratedProjection inputGeneratedProjection, GeneratedProjection groupKeyGeneratedProjection, GeneratedProjection groupSetGeneratedProjection) { super( config, pandasAggFunctions, inputType, udfInputType, udfOutputType, inputGeneratedProjection, groupKeyGeneratedProjection, groupSetGeneratedProjection); this.lowerBoundary = lowerBoundary; this.upperBoundary = upperBoundary; this.isRangeWindows = isRangeWindows; this.aggWindowIndex = aggWindowIndex; this.inputTimeFieldIndex = inputTimeFieldIndex; this.asc = asc; } @Override public void open() throws Exception { super.open(); forwardedInputSerializer = new RowDataSerializer(inputType); this.lastKeyDataStartPos = 0; windowBoundaryWithDataBaos = new ByteArrayOutputStreamWithPos(); windowBoundaryWithDataWrapper = new DataOutputViewStreamWrapper(windowBoundaryWithDataBaos); boundedRangeWindowBoundaries = new ArrayList<>(lowerBoundary.length); boundedRangeWindowIndex = new ArrayList<>(); for (int i = 0; i < lowerBoundary.length; i++) { // range window with bounded preceding or bounded following if (isRangeWindows[i] && (lowerBoundary[i] != Long.MIN_VALUE || upperBoundary[i] != Long.MAX_VALUE)) { boundedRangeWindowIndex.add(i); boundedRangeWindowBoundaries.add(new ArrayList<>()); } } } @Override public void bufferInput(RowData input) throws Exception { BinaryRowData currentKey = groupKeyProjection.apply(input).copy(); if (isNewKey(currentKey)) { if (lastGroupKey != null) { invokeCurrentBatch(); } lastGroupKey = currentKey; lastGroupSet = groupSetProjection.apply(input).copy(); } RowData forwardedFields = forwardedInputSerializer.copy(input); forwardedInputQueue.add(forwardedFields); } @Override protected void invokeCurrentBatch() throws Exception { if (currentBatchCount > 0) { arrowSerializer.finishCurrentBatch(); ListIterator<RowData> iter = forwardedInputQueue.listIterator(lastKeyDataStartPos); int[] lowerBoundaryPos = new int[boundedRangeWindowIndex.size()]; int[] upperBoundaryPos = new int[boundedRangeWindowIndex.size()]; for (int i = 0; i < lowerBoundaryPos.length; i++) { lowerBoundaryPos[i] = lastKeyDataStartPos; upperBoundaryPos[i] = lastKeyDataStartPos; } while (iter.hasNext()) { RowData curData = iter.next(); // loop every bounded range window for (int j = 0; j < boundedRangeWindowIndex.size(); j++) { int windowPos = boundedRangeWindowIndex.get(j); long curMills = curData.getTimestamp(inputTimeFieldIndex, 3).getMillisecond(); List<Integer> curWindowBoundary = boundedRangeWindowBoundaries.get(j); // bounded preceding if (lowerBoundary[windowPos] != Long.MIN_VALUE) { int curLowerBoundaryPos = lowerBoundaryPos[j]; long lowerBoundaryTime = curMills + lowerBoundary[windowPos]; while (isInCurrentOverWindow( forwardedInputQueue.get(curLowerBoundaryPos), lowerBoundaryTime, false)) { curLowerBoundaryPos += 1; } lowerBoundaryPos[j] = curLowerBoundaryPos; curWindowBoundary.add(curLowerBoundaryPos - lastKeyDataStartPos); } // bounded following if (upperBoundary[windowPos] != Long.MAX_VALUE) { int curUpperBoundaryPos = upperBoundaryPos[j]; long upperBoundaryTime = curMills + upperBoundary[windowPos]; while (curUpperBoundaryPos < forwardedInputQueue.size() && isInCurrentOverWindow( forwardedInputQueue.get(curUpperBoundaryPos), upperBoundaryTime, true)) { curUpperBoundaryPos += 1; } upperBoundaryPos[j] = curUpperBoundaryPos; curWindowBoundary.add(curUpperBoundaryPos - lastKeyDataStartPos); } } } // serialize the num of bounded range window. windowBoundarySerializer.serialize( boundedRangeWindowBoundaries.size(), windowBoundaryWithDataWrapper); // serialize every bounded range window boundaries. for (List<Integer> boundedRangeWindowBoundary : boundedRangeWindowBoundaries) { windowBoundarySerializer.serialize( boundedRangeWindowBoundary.size(), windowBoundaryWithDataWrapper); for (int ele : boundedRangeWindowBoundary) { windowBoundarySerializer.serialize(ele, windowBoundaryWithDataWrapper); } boundedRangeWindowBoundary.clear(); } // write arrow format data. windowBoundaryWithDataBaos.write(baos.toByteArray()); baos.reset(); pythonFunctionRunner.process(windowBoundaryWithDataBaos.toByteArray()); windowBoundaryWithDataBaos.reset(); elementCount += currentBatchCount; checkInvokeFinishBundleByCount(); currentBatchCount = 0; arrowSerializer.resetWriter(); } lastKeyDataStartPos = forwardedInputQueue.size(); } @Override public void processElementInternal(RowData value) { arrowSerializer.write(getFunctionInput(value)); currentBatchCount++; } @Override @SuppressWarnings("ConstantConditions") public void emitResult(Tuple3<String, byte[], Integer> resultTuple) throws Exception { byte[] udafResult = resultTuple.f1; int length = resultTuple.f2; bais.setBuffer(udafResult, 0, length); int rowCount = arrowSerializer.load(); for (int i = 0; i < rowCount; i++) { RowData input = forwardedInputQueue.poll(); lastKeyDataStartPos--; reuseJoinedRow.setRowKind(input.getRowKind()); rowDataWrapper.collect(reuseJoinedRow.replace(input, arrowSerializer.read(i))); } arrowSerializer.resetReader(); } @Override public FlinkFnApi.UserDefinedFunctions createUserDefinedFunctionsProto() { FlinkFnApi.UserDefinedFunctions.Builder builder = FlinkFnApi.UserDefinedFunctions.newBuilder(); // add udaf proto for (int i = 0; i < pandasAggFunctions.length; i++) { FlinkFnApi.UserDefinedFunction.Builder functionBuilder = createUserDefinedFunctionProto(pandasAggFunctions[i]).toBuilder(); functionBuilder.setWindowIndex(aggWindowIndex[i]); builder.addUdfs(functionBuilder); } builder.setMetricEnabled(config.get(PYTHON_METRIC_ENABLED)); builder.setProfileEnabled(config.get(PYTHON_PROFILE_ENABLED)); builder.addAllJobParameters( getRuntimeContext().getGlobalJobParameters().entrySet().stream() .map( entry -> FlinkFnApi.JobParameter.newBuilder() .setKey(entry.getKey()) .setValue(entry.getValue()) .build()) .collect(Collectors.toList())); // add windows for (int i = 0; i < lowerBoundary.length; i++) { FlinkFnApi.OverWindow.Builder windowBuilder = FlinkFnApi.OverWindow.newBuilder(); if (isRangeWindows[i]) { // range window if (lowerBoundary[i] != Long.MIN_VALUE) { if (upperBoundary[i] != Long.MAX_VALUE) { // range sliding window windowBuilder.setWindowType(FlinkFnApi.OverWindow.WindowType.RANGE_SLIDING); } else { // range unbounded following window windowBuilder.setWindowType( FlinkFnApi.OverWindow.WindowType.RANGE_UNBOUNDED_FOLLOWING); } } else { if (upperBoundary[i] != Long.MAX_VALUE) { // range unbounded preceding window windowBuilder.setWindowType( FlinkFnApi.OverWindow.WindowType.RANGE_UNBOUNDED_PRECEDING); } else { // range unbounded window windowBuilder.setWindowType( FlinkFnApi.OverWindow.WindowType.RANGE_UNBOUNDED); } } } else { // row window if (lowerBoundary[i] != Long.MIN_VALUE) { windowBuilder.setLowerBoundary(lowerBoundary[i]); if (upperBoundary[i] != Long.MAX_VALUE) { // row sliding window windowBuilder.setUpperBoundary(upperBoundary[i]); windowBuilder.setWindowType(FlinkFnApi.OverWindow.WindowType.ROW_SLIDING); } else { // row unbounded following window windowBuilder.setWindowType( FlinkFnApi.OverWindow.WindowType.ROW_UNBOUNDED_FOLLOWING); } } else { if (upperBoundary[i] != Long.MAX_VALUE) { // row unbounded preceding window windowBuilder.setUpperBoundary(upperBoundary[i]); windowBuilder.setWindowType( FlinkFnApi.OverWindow.WindowType.ROW_UNBOUNDED_PRECEDING); } else { // row unbounded window windowBuilder.setWindowType(FlinkFnApi.OverWindow.WindowType.ROW_UNBOUNDED); } } } builder.addWindows(windowBuilder); } return builder.build(); } @Override public String getFunctionUrn() { return PANDAS_BATCH_OVER_WINDOW_AGG_FUNCTION_URN; } @Override public FlinkFnApi.CoderInfoDescriptor createInputCoderInfoDescriptor(RowType runnerInputType) { return createOverWindowArrowTypeCoderInfoDescriptorProto( runnerInputType, FlinkFnApi.CoderInfoDescriptor.Mode.MULTIPLE, false); } private boolean isInCurrentOverWindow(RowData data, long time, boolean includeEqual) { long dataTime = data.getTimestamp(inputTimeFieldIndex, 3).getMillisecond(); long diff = time - dataTime; return (diff > 0 && asc) || (diff == 0 && includeEqual); } }
BatchArrowPythonOverWindowAggregateFunctionOperator
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocolPB/NamenodeProtocolPB.java
{ "start": 1329, "end": 1701 }
interface ____ * add annotations required for security. */ @KerberosInfo( serverPrincipal = DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY, clientPrincipal = DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY) @ProtocolInfo(protocolName = "org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol", protocolVersion = 1) @InterfaceAudience.Private public
to
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests.java
{ "start": 3216, "end": 3452 }
class ____ implements SimpleBeforeAdvice { private int invocationCounter; @Override public void before() { ++invocationCounter; } public int getInvocationCounter() { return invocationCounter; } } final
SimpleBeforeAdviceImpl
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/uri/UriTemplate.java
{ "start": 1639, "end": 19920 }
class ____ implements Comparable<UriTemplate> { private static final String STRING_PATTERN_SCHEME = "([^:/?#]+):"; private static final String STRING_PATTERN_USER_INFO = "([^@\\[/?#]*)"; private static final String STRING_PATTERN_HOST_IPV4 = "[^\\[{/?#:]*"; private static final String STRING_PATTERN_HOST_IPV6 = "\\[[\\p{XDigit}:.]*[%\\p{Alnum}]*]"; private static final String STRING_PATTERN_HOST = "(" + STRING_PATTERN_HOST_IPV6 + "|" + STRING_PATTERN_HOST_IPV4 + ")"; private static final String STRING_PATTERN_PORT = "(\\d*(?:\\{[^/]+?})?)"; private static final String STRING_PATTERN_PATH = "([^#]*)"; private static final String STRING_PATTERN_QUERY = "([^#]*)"; private static final String STRING_PATTERN_REMAINING = "(.*)"; private static final char QUERY_OPERATOR = '?'; private static final char SLASH_OPERATOR = '/'; private static final char HASH_OPERATOR = '#'; private static final char EXPAND_MODIFIER = '*'; private static final char OPERATOR_NONE = '0'; private static final char VAR_START = '{'; private static final char VAR_END = '}'; private static final char AND_OPERATOR = '&'; private static final String SLASH_STRING = "/"; private static final char DOT_OPERATOR = '.'; // Regex patterns that matches URIs. See RFC 3986, appendix B private static final Pattern PATTERN_SCHEME = Pattern.compile("^" + STRING_PATTERN_SCHEME + "//.*"); private static final Pattern PATTERN_FULL_URI = Pattern.compile( "^(" + STRING_PATTERN_SCHEME + ")?" + "(//(" + STRING_PATTERN_USER_INFO + "@)?" + STRING_PATTERN_HOST + "(:" + STRING_PATTERN_PORT + ")?" + ")?" + STRING_PATTERN_PATH + "(\\?" + STRING_PATTERN_QUERY + ")?" + "(#" + STRING_PATTERN_REMAINING + ")?"); protected final String templateString; final List<PathSegment> segments = new ArrayList<>(); private String asString; /** * Construct a new URI template for the given template. * * @param templateString The template string */ public UriTemplate(CharSequence templateString) { this(templateString, EMPTY_OBJECT_ARRAY); } /** * Construct a new URI template for the given template. * * @param templateString The template string * @param parserArguments The parsed arguments */ @SuppressWarnings("MagicNumber") protected UriTemplate(CharSequence templateString, Object... parserArguments) { if (templateString == null) { throw new IllegalArgumentException("Argument [templateString] should not be null"); } String templateAsString = templateString.toString(); if (templateAsString.endsWith(SLASH_STRING)) { int len = templateAsString.length(); if (len > 1) { templateAsString = templateAsString.substring(0, len - 1); } } if (PATTERN_SCHEME.matcher(templateAsString).matches()) { Matcher matcher = PATTERN_FULL_URI.matcher(templateAsString); if (matcher.find()) { this.templateString = templateAsString; String scheme = matcher.group(2); if (scheme != null) { createParser(scheme + "://", parserArguments).parse(segments); } String userInfo = matcher.group(5); String host = matcher.group(6); String port = matcher.group(8); String path = matcher.group(9); String query = matcher.group(11); String fragment = matcher.group(13); if (userInfo != null) { createParser(userInfo, parserArguments).parse(segments); } if (host != null) { createParser(host, parserArguments).parse(segments); } if (port != null) { createParser(':' + port, parserArguments).parse(segments); } if (path != null) { if (fragment != null) { createParser(path + HASH_OPERATOR + fragment).parse(segments); } else { createParser(path, parserArguments).parse(segments); } } if (query != null) { createParser(query, parserArguments).parse(segments); } } else { throw new IllegalArgumentException("Invalid URI template: " + templateString); } } else { this.templateString = templateAsString; createParser(this.templateString, parserArguments).parse(segments); } } /** * @param templateString The template * @param segments The list of segments */ protected UriTemplate(String templateString, List<PathSegment> segments) { this.templateString = templateString; this.segments.addAll(segments); } /** * @return The template string */ public String getTemplateString() { return templateString; } /** * @return The number of segments that are variable */ public long getVariableSegmentCount() { return segments.stream().filter(PathSegment::isVariable).count(); } /** * @return The number of path segments that are variable */ public long getPathVariableSegmentCount() { return segments.stream().filter(PathSegment::isVariable).filter(s -> !s.isQuerySegment()).count(); } /** * @return The number of segments that are raw */ public long getRawSegmentCount() { return segments.stream().filter(segment -> !segment.isVariable()).count(); } /** * @return The number of segments that are raw */ public int getRawSegmentLength() { return segments.stream() .filter(segment -> !segment.isVariable()) .map(CharSequence::length) .reduce(Integer::sum) .orElse(0); } /** * Nests another URI template with this template. * * @param uriTemplate The URI template. If it does not begin with forward slash it will automatically be appended with forward slash * @return The new URI template */ public UriTemplate nest(CharSequence uriTemplate) { return nest(uriTemplate, EMPTY_OBJECT_ARRAY); } /** * Expand the string with the given parameters. * * @param parameters The parameters * @return The expanded URI */ public String expand(Map<String, Object> parameters) { StringBuilder builder = new StringBuilder(templateString.length()); boolean anyPreviousHasContent = false; boolean anyPreviousHasOperator = false; boolean queryParameter = false; for (PathSegment segment : segments) { String result = segment.expand(parameters, anyPreviousHasContent, anyPreviousHasOperator); if (result == null) { continue; } if (segment instanceof UriTemplateParser.VariablePathSegment varPathSegment) { if (varPathSegment.isQuerySegment && !queryParameter) { // reset anyPrevious* when we reach query parameters queryParameter = true; anyPreviousHasContent = false; anyPreviousHasOperator = false; } final char operator = varPathSegment.operator(); if (operator != OPERATOR_NONE && result.contains(String.valueOf(operator))) { anyPreviousHasOperator = true; } anyPreviousHasContent = anyPreviousHasContent || !result.isEmpty(); } builder.append(result); } return builder.toString(); } /** * Expand the string with the given bean. * * @param bean The bean * @return The expanded URI */ public String expand(Object bean) { return expand(BeanMap.of(bean)); } @Override public String toString() { if (asString == null) { asString = toString(pathSegment -> true); } return asString; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UriTemplate that = (UriTemplate) o; return templateString.equals(that.templateString); } @Override public int hashCode() { return templateString.hashCode(); } @Override public int compareTo(UriTemplate o) { if (this == o) { return 0; } int thisVariableCount = 0; int thatVariableCount = 0; int thisRawLength = 0; int thatRawLength = 0; for (PathSegment segment : this.segments) { if (segment.isVariable()) { if (!segment.isQuerySegment()) { thisVariableCount++; } } else { thisRawLength += segment.length(); } } for (PathSegment segment : o.segments) { if (segment.isVariable()) { if (!segment.isQuerySegment()) { thatVariableCount++; } } else { thatRawLength += segment.length(); } } //using that.compareTo because more raw length should have higher precedence int rawCompare = Integer.compare(thatRawLength, thisRawLength); if (rawCompare == 0) { return Integer.compare(thisVariableCount, thatVariableCount); } else { return rawCompare; } } /** * Create a new {@link UriTemplate} for the given URI. * * @param uri The URI * @return The template */ public static UriTemplate of(String uri) { return new UriTemplate(uri); } /** * Nests another URI template with this template. * * @param uriTemplate The URI template. If it does not begin with forward slash it will automatically be * appended with forward slash * @param parserArguments The parsed arguments * @return The new URI template */ protected UriTemplate nest(CharSequence uriTemplate, Object... parserArguments) { if (uriTemplate == null) { return this; } int len = uriTemplate.length(); if (len == 0) { return this; } List<PathSegment> newSegments = buildNestedSegments(uriTemplate, len, parserArguments); return newUriTemplate(uriTemplate, newSegments); } /** * @param uriTemplate The URI template * @param newSegments The new segments * @return The new {@link UriTemplate} */ protected UriTemplate newUriTemplate(CharSequence uriTemplate, List<PathSegment> newSegments) { return new UriTemplate(normalizeNested(this.templateString, uriTemplate), newSegments); } /** * Normalize a nested URI. * * @param uri The URI * @param nested The nested URI * @return The new URI */ protected String normalizeNested(String uri, CharSequence nested) { if (StringUtils.isEmpty(nested)) { return uri; } String nestedStr = nested.toString(); char firstNested = nestedStr.charAt(0); int len = nestedStr.length(); if (len == 1 && firstNested == SLASH_OPERATOR) { return uri; } switch (firstNested) { case VAR_START: if (len > 1) { switch (nested.charAt(1)) { case SLASH_OPERATOR: case HASH_OPERATOR: case QUERY_OPERATOR: case AND_OPERATOR: if (uri.endsWith(SLASH_STRING)) { return uri.substring(0, uri.length() - 1) + nestedStr; } else { return uri + nestedStr; } default: if (!uri.endsWith(SLASH_STRING)) { return uri + SLASH_STRING + nestedStr; } else { return uri + nestedStr; } } } else { return uri; } case SLASH_OPERATOR: if (uri.endsWith(SLASH_STRING)) { return uri + nestedStr.substring(1); } else { return uri + nestedStr; } default: if (uri.endsWith(SLASH_STRING)) { return uri + nestedStr; } else { return uri + SLASH_STRING + nestedStr; } } } /** * @param uriTemplate The URI template * @param len The length * @param parserArguments The parsed arguments * @return A list of path segments */ protected List<PathSegment> buildNestedSegments(CharSequence uriTemplate, int len, Object... parserArguments) { var newSegments = new ArrayList<PathSegment>(); var querySegments = new ArrayList<PathSegment>(); for (PathSegment segment : segments) { if (!segment.isQuerySegment()) { newSegments.add(segment); } else { querySegments.add(segment); } } String templateString = uriTemplate.toString(); if (shouldPrependSlash(templateString, len)) { templateString = SLASH_OPERATOR + templateString; } else if (!segments.isEmpty() && templateString.startsWith(SLASH_STRING)) { if (len == 1 && uriTemplate.charAt(0) == SLASH_OPERATOR) { templateString = StringUtils.EMPTY_STRING; } else { PathSegment last = segments.get(segments.size() - 1); if (last instanceof UriTemplateParser.RawPathSegment segment) { String v = segment.value; if (v.endsWith(SLASH_STRING)) { templateString = templateString.substring(1); } else { templateString = normalizeNested(SLASH_STRING, templateString.substring(1)); } } } } createParser(templateString, parserArguments).parse(newSegments); newSegments.addAll(querySegments); return newSegments; } /** * Creates a parser. * * @param templateString The template * @param parserArguments The parsed arguments * @return The created parser */ protected UriTemplateParser createParser(String templateString, Object... parserArguments) { return new UriTemplateParser(templateString); } /** * Returns the template as a string filtering the segments * with the provided filter. * * @param filter The filter to test segments * @return The template as a string */ protected String toString(Predicate<PathSegment> filter) { var builder = new StringBuilder(templateString.length()); UriTemplateParser.VariablePathSegment previousVariable = null; for (PathSegment segment : segments) { if (!filter.test(segment)) { continue; } boolean isVar = segment instanceof UriTemplateParser.VariablePathSegment; if (previousVariable != null && isVar) { var varSeg = (UriTemplateParser.VariablePathSegment) segment; if (varSeg.operator == previousVariable.operator && varSeg.modifierChar != EXPAND_MODIFIER) { builder.append(varSeg.delimiter); } else { builder.append(VAR_END) .append(VAR_START); char op = varSeg.operator; if (OPERATOR_NONE != op) { builder.append(op); } } builder.append(segment); previousVariable = varSeg; } else { if (isVar) { previousVariable = (UriTemplateParser.VariablePathSegment) segment; builder.append(VAR_START); char op = previousVariable.operator; if (OPERATOR_NONE != op) { builder.append(op); } builder.append(segment); } else { if (previousVariable != null) { builder.append(VAR_END); previousVariable = null; } builder.append(segment); } } } if (previousVariable != null) { builder.append(VAR_END); } return builder.toString(); } private boolean shouldPrependSlash(String templateString, int len) { String parentString = this.templateString; int parentLen = parentString.length(); return (parentLen > 0 && parentString.charAt(parentLen - 1) != SLASH_OPERATOR) && templateString.charAt(0) != SLASH_OPERATOR && isAdditionalPathVar(templateString, len); } private boolean isAdditionalPathVar(String templateString, int len) { if (len > 1) { boolean isVar = templateString.charAt(0) == VAR_START; if (isVar) { return switch (templateString.charAt(1)) { case SLASH_OPERATOR, QUERY_OPERATOR, HASH_OPERATOR -> false; default -> true; }; } } return templateString.charAt(0) != SLASH_OPERATOR; } /** * Represents an expandable path segment. */ protected
UriTemplate
java
google__guava
android/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java
{ "start": 8173, "end": 8880 }
interface ____ extends Iterable<String> {} public void testResolveType() { assertEquals(String.class, TypeToken.of(this.getClass()).resolveType(String.class).getType()); assertEquals( String.class, TypeToken.of(StringIterable.class) .resolveType(Iterable.class.getTypeParameters()[0]) .getType()); assertEquals( String.class, TypeToken.of(StringIterable.class) .resolveType(Iterable.class.getTypeParameters()[0]) .getType()); assertThrows(NullPointerException.class, () -> TypeToken.of(this.getClass()).resolveType(null)); } public void testContextIsParameterizedType() throws Exception {
StringIterable
java
google__guava
guava-testlib/src/com/google/common/collect/testing/google/MultisetForEachEntryTester.java
{ "start": 1753, "end": 3272 }
class ____<E> extends AbstractMultisetTester<E> { public void testForEachEntry() { List<Entry<E>> expected = new ArrayList<>(getMultiset().entrySet()); List<Entry<E>> actual = new ArrayList<>(); getMultiset() .forEachEntry((element, count) -> actual.add(Multisets.immutableEntry(element, count))); assertEqualIgnoringOrder(expected, actual); } @CollectionFeature.Require(KNOWN_ORDER) public void testForEachEntryOrdered() { List<Entry<E>> expected = new ArrayList<>(getMultiset().entrySet()); List<Entry<E>> actual = new ArrayList<>(); getMultiset() .forEachEntry((element, count) -> actual.add(Multisets.immutableEntry(element, count))); assertEquals(expected, actual); } public void testForEachEntryDuplicates() { initThreeCopies(); List<Entry<E>> expected = singletonList(Multisets.immutableEntry(e0(), 3)); List<Entry<E>> actual = new ArrayList<>(); getMultiset() .forEachEntry((element, count) -> actual.add(Multisets.immutableEntry(element, count))); assertEquals(expected, actual); } /** * Returns {@link Method} instances for the remove tests that assume multisets support duplicates * so that the test of {@code Multisets.forSet()} can suppress them. */ @J2ktIncompatible @GwtIncompatible // reflection public static List<Method> getForEachEntryDuplicateInitializingMethods() { return asList(getMethod(MultisetForEachEntryTester.class, "testForEachEntryDuplicates")); } }
MultisetForEachEntryTester
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/support/AnnotationSupport.java
{ "start": 25207, "end": 26502 }
interface ____ which to find the fields; never {@code null} * @param annotationType the annotation type to search for; never {@code null} * @param fieldType the declared type of fields to find; never {@code null} * @return the list of all such field values found; neither {@code null} nor mutable * @since 1.4 * @see Field#getType() * @see #findAnnotatedFields(Class, Class) * @see #findAnnotatedFields(Class, Class, Predicate, HierarchyTraversalMode) * @see ReflectionSupport#findFields(Class, Predicate, HierarchyTraversalMode) * @see ReflectionSupport#tryToReadFieldValue(Field, Object) */ @SuppressWarnings("unchecked") @API(status = MAINTAINED, since = "1.4") public static <T extends @Nullable Object> List<T> findAnnotatedFieldValues(Class<?> clazz, Class<? extends Annotation> annotationType, Class<T> fieldType) { Preconditions.notNull(fieldType, "fieldType must not be null"); Predicate<Field> predicate = // field -> ModifierSupport.isStatic(field) && fieldType.isAssignableFrom(field.getType()); List<Field> fields = findAnnotatedFields(clazz, annotationType, predicate, HierarchyTraversalMode.TOP_DOWN); return (List<T>) ReflectionUtils.readFieldValues(fields, null); } /** * Find all distinct {@linkplain Method methods} of the supplied
in
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.java
{ "start": 8300, "end": 9801 }
class ____ { @GetMapping("/v2/good-login") public String v2Login(HttpServletRequest request) throws ServletException { request.login("user2", "password2"); return this.principal(); } @GetMapping("/good-login") public String login(HttpServletRequest request) throws ServletException { request.login("user", "password"); return this.principal(); } @GetMapping("/v2/authenticate") public String v2Authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { return this.authenticate(request, response); } @GetMapping("/authenticate") public String authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { request.authenticate(response); return this.principal(); } @GetMapping("/v2/do-logout") public String v2Logout(HttpServletRequest request) throws ServletException { return this.logout(request); } @GetMapping("/do-logout") public String logout(HttpServletRequest request) throws ServletException { request.logout(); return this.principal(); } @GetMapping("/role") public String role(HttpServletRequest request) { return String.valueOf(request.isUserInRole("USER")); } private String principal() { if (SecurityContextHolder.getContext().getAuthentication() != null) { return SecurityContextHolder.getContext().getAuthentication().getName(); } return null; } } }
ServletAuthenticatedController
java
mapstruct__mapstruct
integrationtest/src/test/java/org/mapstruct/itest/testutil/extension/ProcessorTestTemplateInvocationContextProvider.java
{ "start": 571, "end": 1619 }
class ____ implements TestTemplateInvocationContextProvider { @Override public boolean supportsTestTemplate(ExtensionContext context) { return AnnotationSupport.isAnnotated( context.getTestMethod(), ProcessorTest.class ); } @Override public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(ExtensionContext context) { Method testMethod = context.getRequiredTestMethod(); ProcessorTest processorTest = AnnotationSupport.findAnnotation( testMethod, ProcessorTest.class ) .orElseThrow( () -> new RuntimeException( "Failed to get ProcessorTest on " + testMethod ) ); return Stream.of( processorTest.processorTypes() ) .map( processorType -> new ProcessorTestTemplateInvocationContext( new ProcessorTestContext( processorTest.baseDir(), processorType, processorTest.commandLineEnhancer(), processorTest.forkJvm() ) ) ); } }
ProcessorTestTemplateInvocationContextProvider
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/TestSchemaCompatibilityMissingEnumSymbols.java
{ "start": 1365, "end": 2355 }
class ____ { private static final Schema RECORD1_WITH_ENUM_AB = SchemaBuilder.record("Record1").fields() // .name("field1").type(ENUM1_AB_SCHEMA).noDefault() // .endRecord(); private static final Schema RECORD1_WITH_ENUM_ABC = SchemaBuilder.record("Record1").fields() // .name("field1").type(ENUM1_ABC_SCHEMA).noDefault() // .endRecord(); public static Stream<Arguments> data() { return Stream.of(Arguments.of(ENUM1_AB_SCHEMA, ENUM1_ABC_SCHEMA, "[C]", "/symbols"), Arguments.of(ENUM1_BC_SCHEMA, ENUM1_ABC_SCHEMA, "[A]", "/symbols"), Arguments.of(RECORD1_WITH_ENUM_AB, RECORD1_WITH_ENUM_ABC, "[C]", "/fields/0/type/symbols")); } @ParameterizedTest @MethodSource("data") public void testTypeMismatchSchemas(Schema reader, Schema writer, String details, String location) { validateIncompatibleSchemas(reader, writer, SchemaIncompatibilityType.MISSING_ENUM_SYMBOLS, details, location); } }
TestSchemaCompatibilityMissingEnumSymbols
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/rest/ApiKeyDefinition.java
{ "start": 1257, "end": 3574 }
class ____ extends RestSecurityDefinition { @XmlAttribute(name = "name", required = true) @Metadata(required = true) private String name; @XmlAttribute(name = "inHeader") @Metadata(javaType = "java.lang.Boolean") private String inHeader; @XmlAttribute(name = "inQuery") @Metadata(javaType = "java.lang.Boolean") private String inQuery; @XmlAttribute(name = "inCookie") @Metadata(javaType = "java.lang.Boolean") private String inCookie; public ApiKeyDefinition() { } public ApiKeyDefinition(RestDefinition rest) { super(rest); } public String getName() { return name; } /** * The name of the header or query parameter to be used. */ public void setName(String name) { this.name = name; } public String getInHeader() { return inHeader; } /** * To use header as the location of the API key. */ public void setInHeader(String inHeader) { this.inHeader = inHeader; } public String getInQuery() { return inQuery; } /** * To use query parameter as the location of the API key. */ public void setInQuery(String inQuery) { this.inQuery = inQuery; } public String getInCookie() { return inCookie; } /** * To use a cookie as the location of the API key. */ public void setInCookie(String inCookie) { this.inCookie = inCookie; } public ApiKeyDefinition withHeader(String name) { setName(name); setInHeader(Boolean.toString(true)); setInQuery(Boolean.toString(false)); setInCookie(Boolean.toString(false)); return this; } public ApiKeyDefinition withQuery(String name) { setName(name); setInQuery(Boolean.toString(true)); setInHeader(Boolean.toString(false)); setInCookie(Boolean.toString(false)); return this; } public ApiKeyDefinition withCookie(String name) { setName(name); setInCookie(Boolean.toString(true)); setInHeader(Boolean.toString(false)); setInQuery(Boolean.toString(false)); return this; } public RestSecuritiesDefinition end() { return rest.getSecurityDefinitions(); } }
ApiKeyDefinition
java
apache__hadoop
hadoop-tools/hadoop-archives/src/main/java/org/apache/hadoop/tools/HadoopArchives.java
{ "start": 20720, "end": 25851 }
class ____ implements Mapper<LongWritable, HarEntry, IntWritable, Text> { private JobConf conf = null; int partId = -1 ; Path tmpOutputDir = null; Path tmpOutput = null; String partname = null; Path rootPath = null; FSDataOutputStream partStream = null; FileSystem destFs = null; byte[] buffer; int buf_size = 128 * 1024; private int replication = 3; long blockSize = 512 * 1024 * 1024l; // configure the mapper and create // the part file. // use map reduce framework to write into // tmp files. public void configure(JobConf conf) { this.conf = conf; replication = conf.getInt(HAR_REPLICATION_LABEL, 3); // this is tightly tied to map reduce // since it does not expose an api // to get the partition partId = conf.getInt(MRJobConfig.TASK_PARTITION, -1); // create a file name using the partition // we need to write to this directory tmpOutputDir = FileOutputFormat.getWorkOutputPath(conf); blockSize = conf.getLong(HAR_BLOCKSIZE_LABEL, blockSize); // get the output path and write to the tmp // directory partname = "part-" + partId; tmpOutput = new Path(tmpOutputDir, partname); rootPath = (conf.get(SRC_PARENT_LABEL, null) == null) ? null : new Path(conf.get(SRC_PARENT_LABEL)); if (rootPath == null) { throw new RuntimeException("Unable to read parent " + "path for har from config"); } try { destFs = tmpOutput.getFileSystem(conf); //this was a stale copy destFs.delete(tmpOutput, false); partStream = destFs.create(tmpOutput, false, conf.getInt("io.file.buffer.size", 4096), destFs.getDefaultReplication(tmpOutput), blockSize); } catch(IOException ie) { throw new RuntimeException("Unable to open output file " + tmpOutput, ie); } buffer = new byte[buf_size]; } // copy raw data. public void copyData(Path input, FSDataInputStream fsin, FSDataOutputStream fout, Reporter reporter) throws IOException { try { for (int cbread=0; (cbread = fsin.read(buffer))>= 0;) { fout.write(buffer, 0,cbread); reporter.progress(); } } finally { fsin.close(); } } /** * get rid of / in the beginning of path * @param p the path * @return return path without / */ private Path realPath(Path p, Path parent) { Path rootPath = new Path(Path.SEPARATOR); if (rootPath.compareTo(p) == 0) { return parent; } return new Path(parent, new Path(p.toString().substring(1))); } private static String encodeName(String s) throws UnsupportedEncodingException { return URLEncoder.encode(s,"UTF-8"); } private static String encodeProperties( FileStatus fStatus ) throws UnsupportedEncodingException { String propStr = encodeName( fStatus.getModificationTime() + " " + fStatus.getPermission().toShort() + " " + encodeName(fStatus.getOwner()) + " " + encodeName(fStatus.getGroup())); return propStr; } // read files from the split input // and write it onto the part files. // also output hash(name) and string // for reducer to create index // and masterindex files. public void map(LongWritable key, HarEntry value, OutputCollector<IntWritable, Text> out, Reporter reporter) throws IOException { Path relPath = new Path(value.path); int hash = HarFileSystem.getHarHash(relPath); String towrite = null; Path srcPath = realPath(relPath, rootPath); long startPos = partStream.getPos(); FileSystem srcFs = srcPath.getFileSystem(conf); FileStatus srcStatus = srcFs.getFileStatus(srcPath); String propStr = encodeProperties(srcStatus); if (value.isDir()) { towrite = encodeName(relPath.toString()) + " dir " + propStr + " 0 0 "; StringBuilder sbuff = new StringBuilder(); sbuff.append(towrite); for (String child: value.children) { sbuff.append(encodeName(child) + " "); } towrite = sbuff.toString(); //reading directories is also progress reporter.progress(); } else { FSDataInputStream input = srcFs.open(srcStatus.getPath()); reporter.setStatus("Copying file " + srcStatus.getPath() + " to archive."); copyData(srcStatus.getPath(), input, partStream, reporter); towrite = encodeName(relPath.toString()) + " file " + partname + " " + startPos + " " + srcStatus.getLen() + " " + propStr + " "; } out.collect(new IntWritable(hash), new Text(towrite)); } public void close() throws IOException { // close the part files. partStream.close(); destFs.setReplication(tmpOutput, (short) replication); } } /** the reduce for creating the index and the master index * */ static
HArchivesMapper
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/testkit/TolkienCharacterAssert.java
{ "start": 731, "end": 1930 }
class ____ extends AbstractAssert<TolkienCharacterAssert, TolkienCharacter> { public TolkienCharacterAssert(TolkienCharacter actual) { super(actual, TolkienCharacterAssert.class); } public static TolkienCharacterAssert assertThat(TolkienCharacter actual) { return new TolkienCharacterAssert(actual); } // 4 - a specific assertion ! public TolkienCharacterAssert hasName(String name) { // check that actual TolkienCharacter we want to make assertions on is not null. isNotNull(); // check condition if (!Objects.equals(actual.name, name)) { failWithMessage("Expected character's name to be <%s> but was <%s>", name, actual.name); } // return the current assertion for method chaining return this; } // 4 - another specific assertion ! public TolkienCharacterAssert hasAge(int age) { // check that actual TolkienCharacter we want to make assertions on is not null. isNotNull(); // check condition if (actual.age != age) { failWithMessage("Expected character's age to be <%s> but was <%s>", age, actual.age); } // return the current assertion for method chaining return this; } }
TolkienCharacterAssert
java
spring-projects__spring-security
cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java
{ "start": 17400, "end": 18132 }
class ____ implements StatelessTicketCache { private Map<String, CasAuthenticationToken> cache = new HashMap<>(); @Override public CasAuthenticationToken getByTicketId(String serviceTicket) { return this.cache.get(serviceTicket); } @Override public void putTicketInCache(CasAuthenticationToken token) { this.cache.put(token.getCredentials().toString(), token); } @Override public void removeTicketFromCache(CasAuthenticationToken token) { throw new UnsupportedOperationException("mock method not implemented"); } @Override public void removeTicketFromCache(String serviceTicket) { throw new UnsupportedOperationException("mock method not implemented"); } } private
MockStatelessTicketCache
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/TopDoubleLongAggregator.java
{ "start": 1427, "end": 3159 }
class ____ { public static SingleState initSingle(BigArrays bigArrays, int limit, boolean ascending) { return new SingleState(bigArrays, limit, ascending); } public static void combine(SingleState state, double v, long outputValue) { state.add(v, outputValue); } public static void combineIntermediate(SingleState state, DoubleBlock values, LongBlock outputValues) { int start = values.getFirstValueIndex(0); int end = start + values.getValueCount(0); for (int i = start; i < end; i++) { combine(state, values.getDouble(i), outputValues.getLong(i)); } } public static Block evaluateFinal(SingleState state, DriverContext driverContext) { return state.toBlock(driverContext.blockFactory()); } public static GroupingState initGrouping(BigArrays bigArrays, int limit, boolean ascending) { return new GroupingState(bigArrays, limit, ascending); } public static void combine(GroupingState state, int groupId, double v, long outputValue) { state.add(groupId, v, outputValue); } public static void combineIntermediate(GroupingState state, int groupId, DoubleBlock values, LongBlock outputValues, int position) { int start = values.getFirstValueIndex(position); int end = start + values.getValueCount(position); for (int i = start; i < end; i++) { combine(state, groupId, values.getDouble(i), outputValues.getLong(i)); } } public static Block evaluateFinal(GroupingState state, IntVector selected, GroupingAggregatorEvaluationContext ctx) { return state.toBlock(ctx.blockFactory(), selected); } public static
TopDoubleLongAggregator
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/uuid_test/User.java
{ "start": 729, "end": 999 }
class ____ { private UUID id; private String name; public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
User
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java
{ "start": 42047, "end": 42484 }
class ____ implements ArgumentConverter { @Override public Class<?> convert(Object beanClassName, ParameterContext context) throws ArgumentConversionException { try { String name = getClass().getEnclosingClass().getEnclosingClass().getName() + "$" + beanClassName; return getClass().getClassLoader().loadClass(name); } catch (Exception ex) { throw new ArgumentConversionException("Failed to convert
Converter
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/TestNewSpout.java
{ "start": 10290, "end": 11174 }
class ____ { private long innodbPagesRead; private long time; private double queryTime; private double lockTime; public long rowsAffected; public long getInnodbPagesRead() { return innodbPagesRead; } public void setInnodbPagesRead(long innodbPagesRead) { this.innodbPagesRead = innodbPagesRead; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public void setQueryTime(double queryTime) { this.queryTime = queryTime; } public void setLockTime(double lockTime) { this.lockTime = lockTime; } public void setRowsAffected(long rowsAffected) { this.rowsAffected = rowsAffected; } } static
SqlInfo
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/security/HttpSecurity.java
{ "start": 8972, "end": 12421 }
interface ____ { /** * HTTP request must be authenticated using basic authentication mechanism configured * in the 'application.properties' file or the mechanism created with the {@link Basic} API and registered * against the {@link HttpSecurity#mechanism(HttpAuthenticationMechanism)}. */ HttpPermission basic(); /** * HTTP request must be authenticated using form-based authentication mechanism configured * in the 'application.properties' file or the mechanism created with the {@link Form} API and registered * against the {@link HttpSecurity#mechanism(HttpAuthenticationMechanism)}. */ HttpPermission form(); /** * HTTP request must be authenticated using mutual-TLS authentication. */ HttpPermission mTLS(); /** * HTTP request must be authenticated using Bearer token authentication. */ HttpPermission bearer(); /** * HTTP request must be authenticated using WebAuthn mechanism. */ HttpPermission webAuthn(); /** * HTTP request must be authenticated using Authorization Code Flow mechanism. */ HttpPermission authorizationCodeFlow(); /** * HTTP requests will only be accessible if {@link io.quarkus.security.identity.SecurityIdentity} * is not anonymous. */ HttpSecurity authenticated(); /** * HTTP request must be authenticated using a mechanism * with matching {@link HttpCredentialTransport#getAuthenticationScheme()}. * Please note that annotation-based mechanism selection has higher priority during the mechanism selection. */ HttpPermission authenticatedWith(String scheme); /** * Indicates that this policy always applies to the matched paths in addition to the policy with a winning path. * Programmatic analogy to the 'quarkus.http.auth.permission."permissions".shared' configuration property. */ HttpPermission shared(); /** * Whether permission check should be applied on all matching paths, or paths specific for the Jakarta REST resources. * Programmatic analogy to the 'quarkus.http.auth.permission."permissions".applies-to' configuration property. */ HttpPermission applyToJaxRs(); /** * The methods that this permission set applies to. If this is not set then they apply to all methods. * Programmatic analogy to the 'quarkus.http.auth.permission."permissions".methods' configuration property. */ HttpPermission methods(String... httpMethods); /** * Allows to configure HTTP request authorization requirement on the returned instance. */ Authorization authorization(); /** * This method is a shortcut for {@link Authorization#permit()}. */ HttpSecurity permit(); /** * This method is a shortcut for {@link Authorization#roles(String...)}. */ HttpSecurity roles(String... roles); /** * This method is a shortcut for {@link Authorization#policy(HttpSecurityPolicy)}. */ HttpSecurity policy(HttpSecurityPolicy httpSecurityPolicy); } /** * Represents HTTP request authorization. */
HttpPermission
java
playframework__playframework
core/play/src/main/java/play/mvc/Http.java
{ "start": 18056, "end": 18387 }
class ____ extends play.core.j.RequestImpl { /** * Constructor with a {@link RequestBody}. * * @param request the body of the request */ public RequestImpl(play.api.mvc.Request<RequestBody> request) { super(request); } } /** The builder for building a request. */ public static
RequestImpl
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/configuration/AutowiredConfigurationTests.java
{ "start": 13775, "end": 14245 }
class ____ { @AliasedProp("#{systemProperties[myProp]}") private String name; private String name2; @AliasedProp("#{systemProperties[myProp]}") public void setName2(String name) { this.name2 = name; } @Bean @Scope("prototype") public TestBean testBean() { return new TestBean(name); } @Bean @Scope("prototype") public TestBean testBean2() { return new TestBean(name2); } } @Configuration static
ValueConfigWithAliasedMetaAnnotation
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/user/QueryUserResponse.java
{ "start": 919, "end": 2907 }
class ____ extends ActionResponse implements ToXContentObject { private final long total; private final Item[] items; public QueryUserResponse(long total, Collection<Item> items) { this.total = total; Objects.requireNonNull(items, "items must be provided"); this.items = items.toArray(new Item[0]); } public long getTotal() { return total; } public Item[] getItems() { return items; } public int getCount() { return items.length; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject().field("total", total).field("count", items.length).array("users", (Object[]) items); return builder.endObject(); } @Override public String toString() { return "QueryUsersResponse{" + "total=" + total + ", items=" + Arrays.toString(items) + '}'; } @Override public void writeTo(StreamOutput out) throws IOException { TransportAction.localOnly(); } public record Item(User user, @Nullable Object[] sortValues, @Nullable String profileUid) implements ToXContentObject { @Override public Object[] sortValues() { return sortValues; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); user.innerToXContent(builder); if (sortValues != null && sortValues.length > 0) { builder.array("_sort", sortValues); } if (profileUid != null) { builder.field("profile_uid", profileUid); } builder.endObject(); return builder; } @Override public String toString() { return "Item{" + "user=" + user + ", sortValues=" + Arrays.toString(sortValues) + '}'; } } }
QueryUserResponse
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/benchmarks/AccessModeBenchmark.java
{ "start": 1343, "end": 2437 }
interface ____ { AccessMode CONCURRENT = new AccessMode() { final VarHandle LOCALS_UPDATER = MethodHandles.arrayElementVarHandle(Object[].class); @Override public Object get(Object[] locals, int idx) { return LOCALS_UPDATER.getVolatile(locals, idx); } @Override public void put(Object[] locals, int idx, Object value) { LOCALS_UPDATER.setRelease(locals, idx, value); } @Override public Object getOrCreate(Object[] locals, int index, Supplier<Object> initialValueSupplier) { Object res; while (true) { res = LOCALS_UPDATER.getVolatile(locals, index); if (res != null) { break; } Object initial = initialValueSupplier.get(); if (initial == null) { throw new IllegalStateException(); } if (LOCALS_UPDATER.compareAndSet(locals, index, null, initial)) { res = initial; break; } } return res; } }; } @State(Scope.Thread) public static
OldAccessMode
java
grpc__grpc-java
gcp-csm-observability/src/main/java/io/grpc/gcp/csm/observability/MetadataExchanger.java
{ "start": 12260, "end": 12315 }
interface ____ { String get(String name); }
Lookup
java
apache__camel
components/camel-grpc/src/test/java/org/apache/camel/component/grpc/GrpcProducerStreamingTest.java
{ "start": 1803, "end": 5432 }
class ____ extends CamelTestSupport { private static final Logger LOG = LoggerFactory.getLogger(GrpcProducerStreamingTest.class); private static final int GRPC_TEST_PORT = AvailablePortFinder.getNextAvailable(); private static Server grpcServer; private static PingPongImpl pingPongServer; @BeforeEach public void startGrpcServer() throws Exception { pingPongServer = new PingPongImpl(); grpcServer = ServerBuilder.forPort(GRPC_TEST_PORT).addService(pingPongServer).build().start(); LOG.info("gRPC server started on port {}", GRPC_TEST_PORT); } @AfterEach public void stopGrpcServer() { if (grpcServer != null) { grpcServer.shutdown(); LOG.info("gRPC server stopped"); pingPongServer = null; } } @Test public void testPingAsyncAsync() throws Exception { int messageCount = 10; for (int i = 1; i <= messageCount; i++) { template.sendBody("direct:grpc-stream-async-async-route", PingRequest.newBuilder().setPingName(String.valueOf(i)).build()); } MockEndpoint replies = getMockEndpoint("mock:grpc-replies"); replies.expectedMessageCount(messageCount); replies.assertIsSatisfied(); context().stop(); assertNotNull(pingPongServer.getLastStreamRequests()); await().untilAsserted(() -> assertListSize(pingPongServer.getLastStreamRequests(), 1)); assertListSize(pingPongServer.getLastStreamRequests().get(0), messageCount); } @Test public void testPingAsyncAsyncRecovery() throws Exception { int messageGroupCount = 5; for (int i = 1; i <= messageGroupCount; i++) { template.sendBody("direct:grpc-stream-async-async-route", PingRequest.newBuilder().setPingName(String.valueOf(i)).build()); } template.sendBody("direct:grpc-stream-async-async-route", PingRequest.newBuilder().setPingName("error").build()); MockEndpoint replies = getMockEndpoint("mock:grpc-replies"); replies.expectedMessageCount(messageGroupCount); replies.assertIsSatisfied(); Thread.sleep(2000); for (int i = messageGroupCount + 1; i <= 2 * messageGroupCount; i++) { template.sendBody("direct:grpc-stream-async-async-route", PingRequest.newBuilder().setPingName(String.valueOf(i)).build()); } replies.reset(); replies.expectedMessageCount(messageGroupCount); replies.assertIsSatisfied(); context().stop(); assertNotNull(pingPongServer.getLastStreamRequests()); await().untilAsserted(() -> assertListSize(pingPongServer.getLastStreamRequests(), 2)); assertListSize(pingPongServer.getLastStreamRequests().get(0), messageGroupCount + 1); assertListSize(pingPongServer.getLastStreamRequests().get(1), messageGroupCount); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:grpc-stream-async-async-route") .to("grpc://localhost:" + GRPC_TEST_PORT + "/org.apache.camel.component.grpc.PingPong?producerStrategy=STREAMING&streamRepliesTo=direct:grpc-replies&method=pingAsyncAsync"); from("direct:grpc-replies") .to("mock:grpc-replies"); } }; } /** * Test gRPC PingPong server implementation */ static
GrpcProducerStreamingTest
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/typeinfo/TypeInformation.java
{ "start": 1419, "end": 2564 }
class ____ Flink's type system. Flink requires a type information for * all types that are used as input or return type of a user function. This type information class * acts as the tool to generate serializers and comparators, and to perform semantic checks such as * whether the fields that are used as join/grouping keys actually exist. * * <p>The type information also bridges between the programming languages object model and a logical * flat schema. It maps fields from the types to columns (fields) in a flat schema. Not all fields * from a type are mapped to a separate fields in the flat schema and often, entire types are mapped * to one field. It is important to notice that the schema must hold for all instances of a type. * For that reason, elements in lists and arrays are not assigned to individual fields, but the * lists and arrays are considered to be one field in total, to account for different lengths in the * arrays. * * <ul> * <li>Basic types are indivisible and are considered a single field. * <li>Arrays and collections are one field * <li>Tuples and case classes represent as many fields as the
of
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/ShouldHaveSameClass_create_Test.java
{ "start": 1120, "end": 1487 }
class ____ { @Test void should_create_error_message() { // GIVEN ErrorMessageFactory factory = shouldHaveSameClass("Yoda", 10L); // WHEN String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo("[Test] %nExpecting%n \"Yoda\"%nto have the same
ShouldHaveSameClass_create_Test
java
google__error-prone
annotation/src/test/java/com/google/errorprone/BugPatternValidatorTest.java
{ "start": 6236, "end": 6565 }
class ____ {} BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class); ValidationException e = assertThrows(ValidationException.class, () -> BugPatternValidator.validate(annotation)); assertThat(e).hasMessageThat().contains("Name must not contain whitespace"); } }
BugPatternTestClass
java
spring-projects__spring-framework
spring-webflux/src/test/java/org/springframework/web/reactive/function/client/support/WebClientProxyRegistryIntegrationTests.java
{ "start": 4691, "end": 5021 }
class ____ extends BaseEchoConfig { } @Configuration(proxyBeanMethods = false) @ImportHttpServices(clientType = ClientType.WEB_CLIENT, group = "echo", basePackageClasses = EchoA.class) @ImportHttpServices(clientType = ClientType.WEB_CLIENT, group = "greeting", basePackageClasses = GreetingA.class) private static
ListingConfig
java
google__error-prone
core/src/test/java/com/google/errorprone/matchers/MatchersTest.java
{ "start": 9736, "end": 10528 }
class ____ { public boolean doesntMatch1() { return true; } public Object doesntMatch2() { return Integer.valueOf(42); } // BUG: Diagnostic contains: public void matches() { System.out.println(42); } } """) .doTest(); } @Test public void methodReturnsPrimitiveOrVoidType() { Matcher<MethodTree> matcher = methodReturns(isPrimitiveOrVoidType()); CompilationTestHelper.newInstance(methodTreeCheckerSupplier(matcher), getClass()) .addSourceLines( "test/MethodReturnsPrimitiveOrVoidTypeTest.java", """ package test; public
MethodReturnsVoidTypeTest
java
apache__logging-log4j2
log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/ThreadContextBenchmark2.java
{ "start": 3761, "end": 4371 }
class ____ { @Param({"Default", "NoGcSortedArray"}) public String threadContextMapAlias; @Setup public void setup() { System.setProperty( "log4j2.threadContextMap", IMPLEMENTATIONS.get(threadContextMapAlias).getName()); for (int i = 0; i < VALUES.length; i++) { ThreadContext.put(KEYS[i], VALUES[i]); } } @TearDown public void teardown() { ThreadContext.clearMap(); } } @State(Scope.Benchmark) public static
ReadThreadContextState
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java
{ "start": 3858, "end": 4029 }
class ____ abstraction of the mechanism used to launch a container on the * underlying OS. All executor implementations must extend ContainerExecutor. */ public abstract
is
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/client/BulkApiClient.java
{ "start": 1465, "end": 1620 }
interface ____ { void onResponse(BatchInfo batchInfo, Map<String, String> headers, SalesforceException ex); } public
BatchInfoResponseCallback
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/jakarta/JakartaSchemaToolingSettingPrecedenceTests.java
{ "start": 963, "end": 1243 }
class ____ { @Test public void verifySchemaCreated(SessionFactoryScope scope) { // the query would fail if the schema were not exported - just a smoke test scope.inTransaction( (s) -> s.createQuery( "from SimpleEntity" ).list() ); } }
JakartaSchemaToolingSettingPrecedenceTests
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/MonoSingleMono.java
{ "start": 1072, "end": 1519 }
class ____<T> extends InternalMonoOperator<T, T> { MonoSingleMono(Mono<? extends T> source) { super(source); } @Override public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) { return new MonoSingle.SingleSubscriber<>(actual, null, false); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } }
MonoSingleMono
java
elastic__elasticsearch
modules/data-streams/src/internalClusterTest/java/org/elasticsearch/datastreams/ResolveClusterDataStreamIT.java
{ "start": 3477, "end": 25638 }
class ____ extends AbstractMultiClustersTestCase { private static final String REMOTE_CLUSTER_1 = "remote1"; private static final String REMOTE_CLUSTER_2 = "remote2"; private static long EARLIEST_TIMESTAMP = 1691348810000L; private static long LATEST_TIMESTAMP = 1691348820000L; @Override protected List<String> remoteClusterAlias() { return List.of(REMOTE_CLUSTER_1, REMOTE_CLUSTER_2); } @Override protected Map<String, Boolean> skipUnavailableForRemoteClusters() { return Map.of(REMOTE_CLUSTER_1, randomBoolean(), REMOTE_CLUSTER_2, true); } @Override protected boolean reuseClusters() { return false; } @Override protected Collection<Class<? extends Plugin>> nodePlugins(String clusterAlias) { return List.of(DataStreamsPlugin.class); } public void testClusterResolveWithDataStreams() throws Exception { Map<String, Object> testClusterInfo = setupThreeClusters(false); String localDataStream = (String) testClusterInfo.get("local.datastream"); String remoteDataStream1 = (String) testClusterInfo.get("remote1.datastream"); String remoteIndex2 = (String) testClusterInfo.get("remote2.index"); boolean skipUnavailable1 = (Boolean) testClusterInfo.get("remote1.skip_unavailable"); boolean skipUnavailable2 = true; // test all clusters against data streams (present only on local and remote1) { String[] indexExpressions = new String[] { localDataStream, REMOTE_CLUSTER_1 + ":" + remoteDataStream1, REMOTE_CLUSTER_2 + ":" + remoteDataStream1 // does not exist on remote2 }; ResolveClusterActionRequest request = new ResolveClusterActionRequest(indexExpressions); ActionFuture<ResolveClusterActionResponse> future = client(LOCAL_CLUSTER).admin() .indices() .execute(TransportResolveClusterAction.TYPE, request); ResolveClusterActionResponse response = future.actionGet(10, TimeUnit.SECONDS); assertNotNull(response); Map<String, ResolveClusterInfo> clusterInfo = response.getResolveClusterInfo(); assertEquals(3, clusterInfo.size()); Set<String> expectedClusterNames = Set.of(RemoteClusterAware.LOCAL_CLUSTER_GROUP_KEY, REMOTE_CLUSTER_1, REMOTE_CLUSTER_2); assertThat(clusterInfo.keySet(), equalTo(expectedClusterNames)); ResolveClusterInfo remote1 = clusterInfo.get(REMOTE_CLUSTER_1); assertThat(remote1.isConnected(), equalTo(true)); assertThat(remote1.getSkipUnavailable(), equalTo(skipUnavailable1)); assertThat(remote1.getMatchingIndices(), equalTo(true)); assertNotNull(remote1.getBuild().version()); assertNull(remote1.getError()); ResolveClusterInfo remote2 = clusterInfo.get(REMOTE_CLUSTER_2); assertThat(remote2.isConnected(), equalTo(true)); assertThat(remote2.getSkipUnavailable(), equalTo(skipUnavailable2)); assertNull(remote2.getMatchingIndices()); assertNull(remote2.getBuild()); assertNotNull(remote2.getError()); assertThat(remote2.getError(), containsString("no such index [" + remoteDataStream1 + "]")); ResolveClusterInfo local = clusterInfo.get(RemoteClusterAware.LOCAL_CLUSTER_GROUP_KEY); assertThat(local.isConnected(), equalTo(true)); assertThat(local.getSkipUnavailable(), equalTo(false)); assertThat(local.getMatchingIndices(), equalTo(true)); assertNotNull(local.getBuild().version()); assertNull(local.getError()); } // test clusters against datastream or indices, such that all should match { String[] indexExpressions = new String[] { localDataStream, REMOTE_CLUSTER_1 + ":" + remoteDataStream1, REMOTE_CLUSTER_2 + ":" + remoteIndex2 }; ResolveClusterActionRequest request = new ResolveClusterActionRequest(indexExpressions); ActionFuture<ResolveClusterActionResponse> future = client(LOCAL_CLUSTER).admin() .indices() .execute(TransportResolveClusterAction.TYPE, request); ResolveClusterActionResponse response = future.actionGet(10, TimeUnit.SECONDS); assertNotNull(response); Map<String, ResolveClusterInfo> clusterInfo = response.getResolveClusterInfo(); assertEquals(3, clusterInfo.size()); Set<String> expectedClusterNames = Set.of(RemoteClusterAware.LOCAL_CLUSTER_GROUP_KEY, REMOTE_CLUSTER_1, REMOTE_CLUSTER_2); assertThat(clusterInfo.keySet(), equalTo(expectedClusterNames)); ResolveClusterInfo remote1 = clusterInfo.get(REMOTE_CLUSTER_1); assertThat(remote1.isConnected(), equalTo(true)); assertThat(remote1.getSkipUnavailable(), equalTo(skipUnavailable1)); assertThat(remote1.getMatchingIndices(), equalTo(true)); assertNotNull(remote1.getBuild().version()); assertNull(remote1.getError()); ResolveClusterInfo remote2 = clusterInfo.get(REMOTE_CLUSTER_2); assertThat(remote2.isConnected(), equalTo(true)); assertThat(remote2.getSkipUnavailable(), equalTo(skipUnavailable2)); assertThat(remote2.getMatchingIndices(), equalTo(true)); assertNotNull(remote2.getBuild().version()); assertNull(remote2.getError()); ResolveClusterInfo local = clusterInfo.get(RemoteClusterAware.LOCAL_CLUSTER_GROUP_KEY); assertThat(local.isConnected(), equalTo(true)); assertThat(local.getSkipUnavailable(), equalTo(false)); assertThat(local.getMatchingIndices(), equalTo(true)); assertNotNull(local.getBuild().version()); assertNull(local.getError()); } // test wildcards against datastream names { String[] indexExpressions = new String[] { localDataStream.substring(0, 3) + "*", REMOTE_CLUSTER_1.substring(0, 3) + "*:" + remoteDataStream1.substring(0, 3) + "*", REMOTE_CLUSTER_2 + ":" + remoteIndex2.substring(0, 2) + "*" }; ResolveClusterActionRequest request = new ResolveClusterActionRequest(indexExpressions); ActionFuture<ResolveClusterActionResponse> future = client(LOCAL_CLUSTER).admin() .indices() .execute(TransportResolveClusterAction.TYPE, request); ResolveClusterActionResponse response = future.actionGet(10, TimeUnit.SECONDS); assertNotNull(response); Map<String, ResolveClusterInfo> clusterInfo = response.getResolveClusterInfo(); assertEquals(3, clusterInfo.size()); Set<String> expectedClusterNames = Set.of(RemoteClusterAware.LOCAL_CLUSTER_GROUP_KEY, REMOTE_CLUSTER_1, REMOTE_CLUSTER_2); assertThat(clusterInfo.keySet(), equalTo(expectedClusterNames)); ResolveClusterInfo remote1 = clusterInfo.get(REMOTE_CLUSTER_1); assertThat(remote1.isConnected(), equalTo(true)); assertThat(remote1.getSkipUnavailable(), equalTo(skipUnavailable1)); assertThat(remote1.getMatchingIndices(), equalTo(true)); assertNotNull(remote1.getBuild().version()); assertNull(remote1.getError()); ResolveClusterInfo remote2 = clusterInfo.get(REMOTE_CLUSTER_2); assertThat(remote2.isConnected(), equalTo(true)); assertThat(remote2.getSkipUnavailable(), equalTo(skipUnavailable2)); assertThat(remote2.getMatchingIndices(), equalTo(true)); assertNotNull(remote2.getBuild().version()); assertNull(remote2.getError()); ResolveClusterInfo local = clusterInfo.get(RemoteClusterAware.LOCAL_CLUSTER_GROUP_KEY); assertThat(local.isConnected(), equalTo(true)); assertThat(local.getSkipUnavailable(), equalTo(false)); assertThat(local.getMatchingIndices(), equalTo(true)); assertNotNull(local.getBuild().version()); assertNull(local.getError()); } // test remote only clusters { String[] indexExpressions = new String[] { REMOTE_CLUSTER_1 + ":" + remoteDataStream1, REMOTE_CLUSTER_2 + ":" + remoteIndex2.substring(0, 2) + "*" }; ResolveClusterActionRequest request = new ResolveClusterActionRequest(indexExpressions); ActionFuture<ResolveClusterActionResponse> future = client(LOCAL_CLUSTER).admin() .indices() .execute(TransportResolveClusterAction.TYPE, request); ResolveClusterActionResponse response = future.actionGet(10, TimeUnit.SECONDS); assertNotNull(response); Map<String, ResolveClusterInfo> clusterInfo = response.getResolveClusterInfo(); assertEquals(2, clusterInfo.size()); Set<String> expectedClusterNames = Set.of(REMOTE_CLUSTER_1, REMOTE_CLUSTER_2); assertThat(clusterInfo.keySet(), equalTo(expectedClusterNames)); ResolveClusterInfo remote1 = clusterInfo.get(REMOTE_CLUSTER_1); assertThat(remote1.isConnected(), equalTo(true)); assertThat(remote1.getSkipUnavailable(), equalTo(skipUnavailable1)); assertThat(remote1.getMatchingIndices(), equalTo(true)); assertNotNull(remote1.getBuild().version()); assertNull(remote1.getError()); ResolveClusterInfo remote2 = clusterInfo.get(REMOTE_CLUSTER_2); assertThat(remote2.isConnected(), equalTo(true)); assertThat(remote2.getSkipUnavailable(), equalTo(skipUnavailable2)); assertThat(remote2.getMatchingIndices(), equalTo(true)); assertNotNull(remote2.getBuild().version()); assertNull(remote2.getError()); } } public void testClusterResolveWithDataStreamsUsingAlias() throws Exception { Map<String, Object> testClusterInfo = setupThreeClusters(true); String localDataStreamAlias = (String) testClusterInfo.get("local.datastream.alias"); String remoteDataStream1Alias = (String) testClusterInfo.get("remote1.datastream.alias"); String remoteIndex2 = (String) testClusterInfo.get("remote2.index"); boolean skipUnavailable1 = (Boolean) testClusterInfo.get("remote1.skip_unavailable"); boolean skipUnavailable2 = true; // test all clusters against datastream alias (present only on local and remote1) { String[] indexExpressions = new String[] { localDataStreamAlias, REMOTE_CLUSTER_1 + ":" + remoteDataStream1Alias, REMOTE_CLUSTER_2 + ":" + remoteIndex2 }; ResolveClusterActionRequest request = new ResolveClusterActionRequest(indexExpressions); ActionFuture<ResolveClusterActionResponse> future = client(LOCAL_CLUSTER).admin() .indices() .execute(TransportResolveClusterAction.TYPE, request); ResolveClusterActionResponse response = future.actionGet(10, TimeUnit.SECONDS); assertNotNull(response); Map<String, ResolveClusterInfo> clusterInfo = response.getResolveClusterInfo(); assertEquals(3, clusterInfo.size()); Set<String> expectedClusterNames = Set.of(RemoteClusterAware.LOCAL_CLUSTER_GROUP_KEY, REMOTE_CLUSTER_1, REMOTE_CLUSTER_2); assertThat(clusterInfo.keySet(), equalTo(expectedClusterNames)); ResolveClusterInfo remote1 = clusterInfo.get(REMOTE_CLUSTER_1); assertThat(remote1.isConnected(), equalTo(true)); assertThat(remote1.getSkipUnavailable(), equalTo(skipUnavailable1)); assertThat(remote1.getMatchingIndices(), equalTo(true)); assertNotNull(remote1.getBuild().version()); assertNull(remote1.getError()); ResolveClusterInfo remote2 = clusterInfo.get(REMOTE_CLUSTER_2); assertThat(remote2.isConnected(), equalTo(true)); assertThat(remote2.getSkipUnavailable(), equalTo(skipUnavailable2)); assertThat(remote2.getMatchingIndices(), equalTo(true)); assertNotNull(remote2.getBuild().version()); assertNull(remote2.getError()); ResolveClusterInfo local = clusterInfo.get(RemoteClusterAware.LOCAL_CLUSTER_GROUP_KEY); assertThat(local.isConnected(), equalTo(true)); assertThat(local.getSkipUnavailable(), equalTo(false)); assertThat(local.getMatchingIndices(), equalTo(true)); assertNotNull(local.getBuild().version()); assertNull(local.getError()); } } private Map<String, Object> setupThreeClusters(boolean useAlias) throws IOException, ExecutionException, InterruptedException { String dataStreamLocal = "metrics-foo"; String dataStreamLocalAlias = randomAlphaOfLengthBetween(5, 16); // set up data stream on local cluster { Client client = client(LOCAL_CLUSTER); List<String> backingIndices = new ArrayList<>(); Map<String, AliasMetadata> aliases = null; if (useAlias) { aliases = new HashMap<>(); aliases.put(dataStreamLocalAlias, AliasMetadata.builder(dataStreamLocalAlias).writeIndex(randomBoolean()).build()); } putComposableIndexTemplate(client, "id1", List.of(dataStreamLocal + "*"), aliases); CreateDataStreamAction.Request createDataStreamRequest = new CreateDataStreamAction.Request( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "metrics-foo" ); assertAcked(client.execute(CreateDataStreamAction.INSTANCE, createDataStreamRequest).get()); GetDataStreamAction.Request getDataStreamRequest = new GetDataStreamAction.Request(TEST_REQUEST_TIMEOUT, new String[] { "*" }); GetDataStreamAction.Response getDataStreamResponse = client.execute(GetDataStreamAction.INSTANCE, getDataStreamRequest) .actionGet(); DataStream fooDataStream = getDataStreamResponse.getDataStreams().get(0).getDataStream(); String backingIndex = fooDataStream.getIndices().get(0).getName(); backingIndices.add(backingIndex); GetIndexResponse getIndexResponse = client.admin() .indices() .getIndex(new GetIndexRequest(TEST_REQUEST_TIMEOUT).indices(backingIndex)) .actionGet(); assertThat(getIndexResponse.getSettings().get(backingIndex), notNullValue()); assertThat(getIndexResponse.getSettings().get(backingIndex).getAsBoolean("index.hidden", null), is(true)); Map<?, ?> mappings = getIndexResponse.getMappings().get(backingIndex).getSourceAsMap(); assertThat(ObjectPath.eval("properties.@timestamp.type", mappings), is("date")); int numDocsBar = randomIntBetween(2, 16); indexDataStreamDocs(client, dataStreamLocal, numDocsBar); } // set up data stream on remote1 cluster String dataStreamRemote1 = "metrics-bar"; String dataStreamRemote1Alias = randomAlphaOfLengthBetween(5, 16); { Client client = client(REMOTE_CLUSTER_1); List<String> backingIndices = new ArrayList<>(); Map<String, AliasMetadata> aliases = null; if (useAlias) { aliases = new HashMap<>(); aliases.put(dataStreamRemote1Alias, AliasMetadata.builder(dataStreamRemote1Alias).writeIndex(randomBoolean()).build()); } putComposableIndexTemplate(client, "id2", List.of(dataStreamRemote1 + "*"), aliases); CreateDataStreamAction.Request createDataStreamRequest = new CreateDataStreamAction.Request( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "metrics-bar" ); assertAcked(client.execute(CreateDataStreamAction.INSTANCE, createDataStreamRequest).get()); GetDataStreamAction.Request getDataStreamRequest = new GetDataStreamAction.Request(TEST_REQUEST_TIMEOUT, new String[] { "*" }); GetDataStreamAction.Response getDataStreamResponse = client.execute(GetDataStreamAction.INSTANCE, getDataStreamRequest) .actionGet(); DataStream barDataStream = getDataStreamResponse.getDataStreams().get(0).getDataStream(); String backingIndex = barDataStream.getIndices().get(0).getName(); backingIndices.add(backingIndex); GetIndexResponse getIndexResponse = client.admin() .indices() .getIndex(new GetIndexRequest(TEST_REQUEST_TIMEOUT).indices(backingIndex)) .actionGet(); assertThat(getIndexResponse.getSettings().get(backingIndex), notNullValue()); assertThat(getIndexResponse.getSettings().get(backingIndex).getAsBoolean("index.hidden", null), is(true)); Map<?, ?> mappings = getIndexResponse.getMappings().get(backingIndex).getSourceAsMap(); assertThat(ObjectPath.eval("properties.@timestamp.type", mappings), is("date")); int numDocsBar = randomIntBetween(2, 16); indexDataStreamDocs(client, dataStreamRemote1, numDocsBar); } // set up remote2 cluster and non-datastream index String remoteIndex2 = "prod123"; int numShardsRemote2 = randomIntBetween(2, 4); final InternalTestCluster remoteCluster2 = cluster(REMOTE_CLUSTER_2); remoteCluster2.ensureAtLeastNumDataNodes(randomIntBetween(1, 2)); final Settings.Builder remoteSettings2 = Settings.builder(); remoteSettings2.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, numShardsRemote2); assertAcked( client(REMOTE_CLUSTER_2).admin() .indices() .prepareCreate(remoteIndex2) .setSettings(Settings.builder().put(remoteSettings2.build()).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)) .setMapping("@timestamp", "type=date", "f", "type=text") ); assertFalse( client(REMOTE_CLUSTER_2).admin() .cluster() .prepareHealth(TEST_REQUEST_TIMEOUT, remoteIndex2) .setWaitForYellowStatus() .setTimeout(TimeValue.timeValueSeconds(10)) .get() .isTimedOut() ); indexDocs(client(REMOTE_CLUSTER_2), remoteIndex2); String skipUnavailableKey = Strings.format("cluster.remote.%s.skip_unavailable", REMOTE_CLUSTER_1); Setting<?> skipUnavailableSetting = cluster(REMOTE_CLUSTER_1).clusterService().getClusterSettings().get(skipUnavailableKey); boolean skipUnavailable1 = (boolean) cluster(RemoteClusterAware.LOCAL_CLUSTER_GROUP_KEY).clusterService() .getClusterSettings() .get(skipUnavailableSetting); Map<String, Object> clusterInfo = new HashMap<>(); clusterInfo.put("local.datastream", dataStreamLocal); clusterInfo.put("local.datastream.alias", dataStreamLocalAlias); clusterInfo.put("remote1.skip_unavailable", skipUnavailable1); clusterInfo.put("remote1.datastream", dataStreamRemote1); clusterInfo.put("remote1.datastream.alias", dataStreamRemote1Alias); clusterInfo.put("remote2.index", remoteIndex2); clusterInfo.put("remote2.skip_unavailable", true); return clusterInfo; } private int indexDocs(Client client, String index) { int numDocs = between(50, 100); for (int i = 0; i < numDocs; i++) { long ts = EARLIEST_TIMESTAMP + i; if (i == numDocs - 1) { ts = LATEST_TIMESTAMP; } client.prepareIndex(index).setSource("f", "v", "@timestamp", ts).get(); } client.admin().indices().prepareRefresh(index).get(); return numDocs; } void putComposableIndexTemplate(Client client, String id, List<String> patterns, @Nullable Map<String, AliasMetadata> aliases) throws IOException { TransportPutComposableIndexTemplateAction.Request request = new TransportPutComposableIndexTemplateAction.Request(id); request.indexTemplate( ComposableIndexTemplate.builder() .indexPatterns(patterns) .template(Template.builder().aliases(aliases)) .dataStreamTemplate(new ComposableIndexTemplate.DataStreamTemplate()) .build() ); client.execute(TransportPutComposableIndexTemplateAction.TYPE, request).actionGet(); } void indexDataStreamDocs(Client client, String dataStream, int numDocs) { BulkRequest bulkRequest = new BulkRequest(); for (int i = 0; i < numDocs; i++) { String value = DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.formatMillis(System.currentTimeMillis()); bulkRequest.add( new IndexRequest(dataStream).opType(DocWriteRequest.OpType.CREATE) .source(String.format(Locale.ROOT, "{\"%s\":\"%s\"}", DEFAULT_TIMESTAMP_FIELD, value), XContentType.JSON) ); } BulkResponse bulkResponse = client.bulk(bulkRequest).actionGet(); assertThat(bulkResponse.getItems().length, equalTo(numDocs)); String backingIndexPrefix = DataStream.BACKING_INDEX_PREFIX + dataStream; for (BulkItemResponse itemResponse : bulkResponse) { assertThat(itemResponse.getFailureMessage(), nullValue()); assertThat(itemResponse.status(), equalTo(RestStatus.CREATED)); assertThat(itemResponse.getIndex(), startsWith(backingIndexPrefix)); } client.admin().indices().refresh(new RefreshRequest(dataStream)).actionGet(); } }
ResolveClusterDataStreamIT
java
square__javapoet
src/main/java/com/squareup/javapoet/MethodSpec.java
{ "start": 1539, "end": 10795 }
class ____ { static final String CONSTRUCTOR = "<init>"; public final String name; public final CodeBlock javadoc; public final List<AnnotationSpec> annotations; public final Set<Modifier> modifiers; public final List<TypeVariableName> typeVariables; public final TypeName returnType; public final List<ParameterSpec> parameters; public final boolean varargs; public final List<TypeName> exceptions; public final CodeBlock code; public final CodeBlock defaultValue; private MethodSpec(Builder builder) { CodeBlock code = builder.code.build(); checkArgument(code.isEmpty() || !builder.modifiers.contains(Modifier.ABSTRACT), "abstract method %s cannot have code", builder.name); checkArgument(!builder.varargs || lastParameterIsArray(builder.parameters), "last parameter of varargs method %s must be an array", builder.name); this.name = checkNotNull(builder.name, "name == null"); this.javadoc = builder.javadoc.build(); this.annotations = Util.immutableList(builder.annotations); this.modifiers = Util.immutableSet(builder.modifiers); this.typeVariables = Util.immutableList(builder.typeVariables); this.returnType = builder.returnType; this.parameters = Util.immutableList(builder.parameters); this.varargs = builder.varargs; this.exceptions = Util.immutableList(builder.exceptions); this.defaultValue = builder.defaultValue; this.code = code; } private boolean lastParameterIsArray(List<ParameterSpec> parameters) { return !parameters.isEmpty() && TypeName.asArray((parameters.get(parameters.size() - 1).type)) != null; } void emit(CodeWriter codeWriter, String enclosingName, Set<Modifier> implicitModifiers) throws IOException { codeWriter.emitJavadoc(javadocWithParameters()); codeWriter.emitAnnotations(annotations, false); codeWriter.emitModifiers(modifiers, implicitModifiers); if (!typeVariables.isEmpty()) { codeWriter.emitTypeVariables(typeVariables); codeWriter.emit(" "); } if (isConstructor()) { codeWriter.emit("$L($Z", enclosingName); } else { codeWriter.emit("$T $L($Z", returnType, name); } boolean firstParameter = true; for (Iterator<ParameterSpec> i = parameters.iterator(); i.hasNext(); ) { ParameterSpec parameter = i.next(); if (!firstParameter) codeWriter.emit(",").emitWrappingSpace(); parameter.emit(codeWriter, !i.hasNext() && varargs); firstParameter = false; } codeWriter.emit(")"); if (defaultValue != null && !defaultValue.isEmpty()) { codeWriter.emit(" default "); codeWriter.emit(defaultValue); } if (!exceptions.isEmpty()) { codeWriter.emitWrappingSpace().emit("throws"); boolean firstException = true; for (TypeName exception : exceptions) { if (!firstException) codeWriter.emit(","); codeWriter.emitWrappingSpace().emit("$T", exception); firstException = false; } } if (hasModifier(Modifier.ABSTRACT)) { codeWriter.emit(";\n"); } else if (hasModifier(Modifier.NATIVE)) { // Code is allowed to support stuff like GWT JSNI. codeWriter.emit(code); codeWriter.emit(";\n"); } else { codeWriter.emit(" {\n"); codeWriter.indent(); codeWriter.emit(code, true); codeWriter.unindent(); codeWriter.emit("}\n"); } codeWriter.popTypeVariables(typeVariables); } private CodeBlock javadocWithParameters() { CodeBlock.Builder builder = javadoc.toBuilder(); boolean emitTagNewline = true; for (ParameterSpec parameterSpec : parameters) { if (!parameterSpec.javadoc.isEmpty()) { // Emit a new line before @param section only if the method javadoc is present. if (emitTagNewline && !javadoc.isEmpty()) builder.add("\n"); emitTagNewline = false; builder.add("@param $L $L", parameterSpec.name, parameterSpec.javadoc); } } return builder.build(); } public boolean hasModifier(Modifier modifier) { return modifiers.contains(modifier); } public boolean isConstructor() { return name.equals(CONSTRUCTOR); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (getClass() != o.getClass()) return false; return toString().equals(o.toString()); } @Override public int hashCode() { return toString().hashCode(); } @Override public String toString() { StringBuilder out = new StringBuilder(); try { CodeWriter codeWriter = new CodeWriter(out); emit(codeWriter, "Constructor", Collections.emptySet()); return out.toString(); } catch (IOException e) { throw new AssertionError(); } } public static Builder methodBuilder(String name) { return new Builder(name); } public static Builder constructorBuilder() { return new Builder(CONSTRUCTOR); } /** * Returns a new method spec builder that overrides {@code method}. * * <p>This will copy its visibility modifiers, type parameters, return type, name, parameters, and * throws declarations. An {@link Override} annotation will be added. * * <p>Note that in JavaPoet 1.2 through 1.7 this method retained annotations from the method and * parameters of the overridden method. Since JavaPoet 1.8 annotations must be added separately. */ public static Builder overriding(ExecutableElement method) { checkNotNull(method, "method == null"); Element enclosingClass = method.getEnclosingElement(); if (enclosingClass.getModifiers().contains(Modifier.FINAL)) { throw new IllegalArgumentException("Cannot override method on final class " + enclosingClass); } Set<Modifier> modifiers = method.getModifiers(); if (modifiers.contains(Modifier.PRIVATE) || modifiers.contains(Modifier.FINAL) || modifiers.contains(Modifier.STATIC)) { throw new IllegalArgumentException("cannot override method with modifiers: " + modifiers); } String methodName = method.getSimpleName().toString(); MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName); methodBuilder.addAnnotation(Override.class); modifiers = new LinkedHashSet<>(modifiers); modifiers.remove(Modifier.ABSTRACT); modifiers.remove(Modifier.DEFAULT); methodBuilder.addModifiers(modifiers); for (TypeParameterElement typeParameterElement : method.getTypeParameters()) { TypeVariable var = (TypeVariable) typeParameterElement.asType(); methodBuilder.addTypeVariable(TypeVariableName.get(var)); } methodBuilder.returns(TypeName.get(method.getReturnType())); methodBuilder.addParameters(ParameterSpec.parametersOf(method)); methodBuilder.varargs(method.isVarArgs()); for (TypeMirror thrownType : method.getThrownTypes()) { methodBuilder.addException(TypeName.get(thrownType)); } return methodBuilder; } /** * Returns a new method spec builder that overrides {@code method} as a member of {@code * enclosing}. This will resolve type parameters: for example overriding {@link * Comparable#compareTo} in a type that implements {@code Comparable<Movie>}, the {@code T} * parameter will be resolved to {@code Movie}. * * <p>This will copy its visibility modifiers, type parameters, return type, name, parameters, and * throws declarations. An {@link Override} annotation will be added. * * <p>Note that in JavaPoet 1.2 through 1.7 this method retained annotations from the method and * parameters of the overridden method. Since JavaPoet 1.8 annotations must be added separately. */ public static Builder overriding( ExecutableElement method, DeclaredType enclosing, Types types) { ExecutableType executableType = (ExecutableType) types.asMemberOf(enclosing, method); List<? extends TypeMirror> resolvedParameterTypes = executableType.getParameterTypes(); List<? extends TypeMirror> resolvedThrownTypes = executableType.getThrownTypes(); TypeMirror resolvedReturnType = executableType.getReturnType(); Builder builder = overriding(method); builder.returns(TypeName.get(resolvedReturnType)); for (int i = 0, size = builder.parameters.size(); i < size; i++) { ParameterSpec parameter = builder.parameters.get(i); TypeName type = TypeName.get(resolvedParameterTypes.get(i)); builder.parameters.set(i, parameter.toBuilder(type, parameter.name).build()); } builder.exceptions.clear(); for (int i = 0, size = resolvedThrownTypes.size(); i < size; i++) { builder.addException(TypeName.get(resolvedThrownTypes.get(i))); } return builder; } public Builder toBuilder() { Builder builder = new Builder(name); builder.javadoc.add(javadoc); builder.annotations.addAll(annotations); builder.modifiers.addAll(modifiers); builder.typeVariables.addAll(typeVariables); builder.returnType = returnType; builder.parameters.addAll(parameters); builder.exceptions.addAll(exceptions); builder.code.add(code); builder.varargs = varargs; builder.defaultValue = defaultValue; return builder; } public static final
MethodSpec
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/DeleteDataFrameAnalyticsAction.java
{ "start": 1384, "end": 3381 }
class ____ extends AcknowledgedRequest<Request> { public static final ParseField FORCE = new ParseField("force"); public static final ParseField TIMEOUT = new ParseField("timeout"); // Default timeout matches that of delete by query private static final TimeValue DEFAULT_TIMEOUT = new TimeValue(1, TimeUnit.MINUTES); private String id; private boolean force; public Request(StreamInput in) throws IOException { super(in); id = in.readString(); force = in.readBoolean(); } public Request() { super(TRAPPY_IMPLICIT_DEFAULT_MASTER_NODE_TIMEOUT, DEFAULT_ACK_TIMEOUT); ackTimeout(DEFAULT_TIMEOUT); } public Request(String id) { this(); this.id = ExceptionsHelper.requireNonNull(id, DataFrameAnalyticsConfig.ID); } public String getId() { return id; } public boolean isForce() { return force; } public void setForce(boolean force) { this.force = force; } @Override public String getDescription() { return DELETION_TASK_DESCRIPTION_PREFIX + id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DeleteDataFrameAnalyticsAction.Request request = (DeleteDataFrameAnalyticsAction.Request) o; return Objects.equals(id, request.id) && force == request.force && Objects.equals(ackTimeout(), request.ackTimeout()); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(id); out.writeBoolean(force); } @Override public int hashCode() { return Objects.hash(id, force, ackTimeout()); } } }
Request
java
spring-projects__spring-boot
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/export/stackdriver/StackdriverPropertiesConfigAdapterTests.java
{ "start": 1069, "end": 3530 }
class ____ extends AbstractPropertiesConfigAdapterTests<StackdriverProperties, StackdriverPropertiesConfigAdapter> { StackdriverPropertiesConfigAdapterTests() { super(StackdriverPropertiesConfigAdapter.class); } @Test void whenPropertiesProjectIdIsSetAdapterProjectIdReturnsIt() { StackdriverProperties properties = new StackdriverProperties(); properties.setProjectId("my-gcp-project-id"); assertThat(new StackdriverPropertiesConfigAdapter(properties).projectId()).isEqualTo("my-gcp-project-id"); } @Test void whenPropertiesResourceTypeIsSetAdapterResourceTypeReturnsIt() { StackdriverProperties properties = new StackdriverProperties(); properties.setResourceType("my-resource-type"); assertThat(new StackdriverPropertiesConfigAdapter(properties).resourceType()).isEqualTo("my-resource-type"); } @Test void whenPropertiesResourceLabelsAreSetAdapterResourceLabelsReturnsThem() { final Map<String, String> labels = new HashMap<>(); labels.put("labelOne", "valueOne"); labels.put("labelTwo", "valueTwo"); StackdriverProperties properties = new StackdriverProperties(); properties.setResourceLabels(labels); assertThat(new StackdriverPropertiesConfigAdapter(properties).resourceLabels()) .containsExactlyInAnyOrderEntriesOf(labels); } @Test void whenPropertiesUseSemanticMetricTypesIsSetAdapterUseSemanticMetricTypesReturnsIt() { StackdriverProperties properties = new StackdriverProperties(); properties.setUseSemanticMetricTypes(true); assertThat(new StackdriverPropertiesConfigAdapter(properties).useSemanticMetricTypes()).isTrue(); } @Test void whenPropertiesMetricTypePrefixIsSetAdapterMetricTypePrefixReturnsIt() { StackdriverProperties properties = new StackdriverProperties(); properties.setMetricTypePrefix("external.googleapis.com/prometheus"); assertThat(new StackdriverPropertiesConfigAdapter(properties).metricTypePrefix()) .isEqualTo("external.googleapis.com/prometheus"); } @Test void whenPropertiesAutoCreateMetricDescriptorsIsSetAdapterAutoCreateMetricDescriptorsReturnsIt() { StackdriverProperties properties = new StackdriverProperties(); properties.setAutoCreateMetricDescriptors(false); assertThat(new StackdriverPropertiesConfigAdapter(properties).autoCreateMetricDescriptors()).isFalse(); } @Test @Override protected void adapterOverridesAllConfigMethods() { adapterOverridesAllConfigMethodsExcept("credentials"); } }
StackdriverPropertiesConfigAdapterTests
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-links/deployment/src/test/java/io/quarkus/resteasy/reactive/links/deployment/RestLinksInjectionTest.java
{ "start": 452, "end": 5319 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(AbstractId.class, AbstractEntity.class, TestRecord.class, TestResource.class, TestRecordWithIdAndPersistenceIdAndRestLinkId.class, TestRecordWithIdAndRestLinkId.class, TestRecordWithIdAndPersistenceId.class, TestRecordWithPersistenceId.class, TestRecordWithRestLinkId.class, TestRecordWithPersistenceIdAndRestLinkId.class)); @TestHTTPResource("records") String recordsUrl; @TestHTTPResource("records/without-links") String recordsWithoutLinksUrl; @Test void shouldGetById() { List<String> firstRecordLinks = when().get(recordsUrl + "/1") .thenReturn() .getHeaders() .getValues("Link"); assertThat(firstRecordLinks).containsOnly( Link.fromUri(recordsUrl).rel("list").build().toString(), Link.fromUri(recordsWithoutLinksUrl).rel("list-without-links").build().toString(), Link.fromUriBuilder(UriBuilder.fromUri(recordsUrl).path("/1")).rel("self").build().toString(), Link.fromUriBuilder(UriBuilder.fromUri(recordsUrl).path("/first")).rel("get-by-slug").build().toString(), Link.fromUriBuilder(UriBuilder.fromUri(recordsUrl).path("/slugOrId/{slugOrId}")).rel("get-by-slug-or-id") .build("{slugOrId}").toString()); List<String> secondRecordLinks = when().get(recordsUrl + "/2") .thenReturn() .getHeaders() .getValues("Link"); assertThat(secondRecordLinks).containsOnly( Link.fromUri(recordsUrl).rel("list").build().toString(), Link.fromUri(recordsWithoutLinksUrl).rel("list-without-links").build().toString(), Link.fromUriBuilder(UriBuilder.fromUri(recordsUrl).path("/2")).rel("self").build().toString(), Link.fromUriBuilder(UriBuilder.fromUri(recordsUrl).path("/second")) .rel("get-by-slug") .build() .toString(), Link.fromUriBuilder(UriBuilder.fromUri(recordsUrl).path("/slugOrId/{slugOrId}")).rel("get-by-slug-or-id") .build("{slugOrId}").toString()); } @Test void shouldGetBySlug() { List<String> firstRecordLinks = when().get(recordsUrl + "/first") .thenReturn() .getHeaders() .getValues("Link"); assertThat(firstRecordLinks).containsOnly( Link.fromUri(recordsUrl).rel("list").build().toString(), Link.fromUri(recordsWithoutLinksUrl).rel("list-without-links").build().toString(), Link.fromUriBuilder(UriBuilder.fromUri(recordsUrl).path("/1")).rel("self").build().toString(), Link.fromUriBuilder(UriBuilder.fromUri(recordsUrl).path("/first")).rel("get-by-slug").build().toString(), Link.fromUriBuilder(UriBuilder.fromUri(recordsUrl).path("/slugOrId/{slugOrId}")).rel("get-by-slug-or-id") .build("{slugOrId}").toString()); List<String> secondRecordLinks = when().get(recordsUrl + "/second") .thenReturn() .getHeaders() .getValues("Link"); assertThat(secondRecordLinks).containsOnly( Link.fromUri(recordsUrl).rel("list").build().toString(), Link.fromUri(recordsWithoutLinksUrl).rel("list-without-links").build().toString(), Link.fromUriBuilder(UriBuilder.fromUri(recordsUrl).path("/2")).rel("self").build().toString(), Link.fromUriBuilder(UriBuilder.fromUri(recordsUrl).path("/second")) .rel("get-by-slug") .build() .toString(), Link.fromUriBuilder(UriBuilder.fromUri(recordsUrl).path("/slugOrId/{slugOrId}")).rel("get-by-slug-or-id") .build("{slugOrId}").toString()); } @Test void shouldGetAll() { List<String> links = when().get(recordsUrl) .thenReturn() .getHeaders() .getValues("Link"); assertThat(links).containsOnly( Link.fromUri(recordsUrl).rel("list").build().toString(), Link.fromUri(recordsWithoutLinksUrl).rel("list-without-links").build().toString()); } @Test void shouldGetAllWithoutLinks() { List<String> links = when().get(recordsWithoutLinksUrl) .thenReturn() .getHeaders() .getValues("Link"); assertThat(links).isEmpty(); } }
RestLinksInjectionTest
java
apache__camel
core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/ManagedConvertBodyMBean.java
{ "start": 916, "end": 1182 }
interface ____ extends ManagedProcessorMBean { @ManagedAttribute(description = "The java type to convert to") String getType(); @ManagedAttribute(description = "To use a specific charset when converting") String getCharset(); }
ManagedConvertBodyMBean
java
apache__flink
flink-table/flink-table-api-java-bridge/src/main/java/org/apache/flink/legacy/table/factories/StreamTableSourceFactory.java
{ "start": 1773, "end": 2772 }
interface ____<T> extends TableSourceFactory<T> { /** * Creates and configures a {@link StreamTableSource} using the given properties. * * @param properties normalized properties describing a stream table source. * @return the configured stream table source. * @deprecated {@link Context} contains more information, and already contains table schema too. * Please use {@link #createTableSource(Context)} instead. */ @Deprecated default StreamTableSource<T> createStreamTableSource(Map<String, String> properties) { return null; } /** Only create a stream table source. */ @Override default TableSource<T> createTableSource(Map<String, String> properties) { StreamTableSource<T> source = createStreamTableSource(properties); if (source == null) { throw new ValidationException("Please override 'createTableSource(Context)' method."); } return source; } }
StreamTableSourceFactory
java
qos-ch__slf4j
slf4j-api/src/main/java/org/slf4j/spi/LocationAwareLogger.java
{ "start": 1408, "end": 1744 }
interface ____ mainly used by SLF4J bridges * such as jcl-over-slf4j, jul-to-slf4j and log4j-over-slf4j or {@link Logger} wrappers * which need to provide hints so that the underlying logging system can extract * the correct location information (method name, line number). * * @author Ceki G&uuml;lc&uuml; * @since 1.3 */ public
is
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SessionFactoryProducer.java
{ "start": 424, "end": 787 }
class ____ implement SessionFactoryScopeContainer * and return the SessionFactoryProducer to be used for those tests. * The SessionFactoryProducer is then used to build the SessionFactoryScope * which is injected back into the SessionFactoryScopeContainer * * @see SessionFactoryExtension * @see SessionFactoryScope * * @author Steve Ebersole */ public
would
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java
{ "start": 1365, "end": 6465 }
class ____ { private final RandomValuePropertySource source = new RandomValuePropertySource(); @Test void getPropertyWhenNotRandomReturnsNull() { assertThat(this.source.getProperty("foo")).isNull(); } @Test void getPropertyWhenStringReturnsValue() { assertThat(this.source.getProperty("random.string")).isNotNull(); } @Test void getPropertyWhenIntReturnsValue() { Integer value = (Integer) this.source.getProperty("random.int"); assertThat(value).isNotNull(); } @Test void getPropertyWhenUuidReturnsValue() { String value = (String) this.source.getProperty("random.uuid"); assertThat(value).isNotNull(); assertThat(UUID.fromString(value)).isNotNull(); } @Test void getPropertyWhenIntRangeReturnsValue() { Integer value = (Integer) this.source.getProperty("random.int[4,10]"); assertThat(value).isNotNull(); assertThat(value).isGreaterThanOrEqualTo(4); assertThat(value).isLessThan(10); } @Test void intRangeWhenLowerBoundEqualsUpperBoundShouldFailWithIllegalArgumentException() { assertThatIllegalStateException().isThrownBy(() -> this.source.getProperty("random.int[4,4]")) .withMessage("Lower bound must be less than upper bound."); } @Test void intRangeWhenLowerBoundNegative() { Integer value = (Integer) this.source.getProperty("random.int[-4,4]"); assertThat(value).isGreaterThanOrEqualTo(-4); assertThat(value).isLessThan(4); } @Test void getPropertyWhenIntMaxReturnsValue() { Integer value = (Integer) this.source.getProperty("random.int(10)"); assertThat(value).isNotNull().isLessThan(10); } @Test void intMaxZero() { assertThatIllegalStateException().isThrownBy(() -> this.source.getProperty("random.int(0)")) .withMessage("Bound must be positive."); } @Test void intNegativeBound() { assertThatIllegalStateException().isThrownBy(() -> this.source.getProperty("random.int(-5)")) .withMessage("Bound must be positive."); } @Test void getPropertyWhenLongReturnsValue() { Long value = (Long) this.source.getProperty("random.long"); assertThat(value).isNotNull(); } @Test void getPropertyWhenLongRangeReturnsValue() { Long value = (Long) this.source.getProperty("random.long[4,10]"); assertThat(value).isNotNull().isBetween(4L, 10L); } @Test void longRangeWhenLowerBoundEqualsUpperBoundShouldFailWithIllegalArgumentException() { assertThatIllegalStateException().isThrownBy(() -> this.source.getProperty("random.long[4,4]")) .withMessage("Lower bound must be less than upper bound."); } @Test void longRangeWhenLowerBoundNegative() { Long value = (Long) this.source.getProperty("random.long[-4,4]"); assertThat(value).isGreaterThanOrEqualTo(-4); assertThat(value).isLessThan(4); } @Test void getPropertyWhenLongMaxReturnsValue() { Long value = (Long) this.source.getProperty("random.long(10)"); assertThat(value).isNotNull().isLessThan(10L); } @Test void longMaxZero() { assertThatIllegalStateException().isThrownBy(() -> this.source.getProperty("random.long(0)")) .withMessage("Bound must be positive."); } @Test void longNegativeBound() { assertThatIllegalStateException().isThrownBy(() -> this.source.getProperty("random.long(-5)")) .withMessage("Bound must be positive."); } @Test void getPropertyWhenLongOverflowReturnsValue() { RandomValuePropertySource source = spy(this.source); given(source.getSource()).willReturn(new Random() { @Override public long nextLong() { // constant that used to become -8, now becomes 8 return Long.MIN_VALUE; } }); Long value = (Long) source.getProperty("random.long(10)"); assertThat(value).isNotNull().isGreaterThanOrEqualTo(0L).isLessThan(10L); value = (Long) source.getProperty("random.long[4,10]"); assertThat(value).isNotNull().isGreaterThanOrEqualTo(4L).isLessThan(10L); } @Test void addToEnvironmentAddsSource() { MockEnvironment environment = new MockEnvironment(); RandomValuePropertySource.addToEnvironment(environment); assertThat(environment.getProperty("random.string")).isNotNull(); } @Test void addToEnvironmentWhenAlreadyAddedAddsSource() { MockEnvironment environment = new MockEnvironment(); RandomValuePropertySource.addToEnvironment(environment); RandomValuePropertySource.addToEnvironment(environment); assertThat(environment.getProperty("random.string")).isNotNull(); } @Test void addToEnvironmentAddsAfterSystemEnvironment() { MockEnvironment environment = new MockEnvironment(); environment.getPropertySources() .addFirst(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.emptyMap())); RandomValuePropertySource.addToEnvironment(environment); assertThat(environment.getPropertySources().stream().map(PropertySource::getName)).containsExactly( StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, RandomValuePropertySource.RANDOM_PROPERTY_SOURCE_NAME, "mockProperties"); } @Test void randomStringIs32CharsLong() { assertThat(this.source.getProperty("random.string")).asString().hasSize(32); } }
RandomValuePropertySourceTests
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RBatch.java
{ "start": 1060, "end": 16715 }
interface ____ { /** * Returns stream instance by <code>name</code> * * @param <K> type of key * @param <V> type of value * @param name of stream * @return RStream object */ <K, V> RStreamAsync<K, V> getStream(String name); /** * Returns stream instance by <code>name</code> * using provided <code>codec</code> for entries. * * @param <K> type of key * @param <V> type of value * @param name - name of stream * @param codec - codec for entry * @return RStream object */ <K, V> RStreamAsync<K, V> getStream(String name, Codec codec); /** * Returns geospatial items holder instance by <code>name</code>. * * @param <V> type of object * @param name - name of object * @return Geo object */ <V> RGeoAsync<V> getGeo(String name); /** * Returns geospatial items holder instance by <code>name</code> * using provided codec for geospatial members. * * @param <V> type of value * @param name - name of object * @param codec - codec for value * @return Geo object */ <V> RGeoAsync<V> getGeo(String name, Codec codec); /** * Returns Set based MultiMap instance by name. * * @param <K> type of key * @param <V> type of value * @param name - name of object * @return Multimap object */ <K, V> RMultimapAsync<K, V> getSetMultimap(String name); /** * Returns Set based MultiMap instance by name * using provided codec for both map keys and values. * * @param <K> type of key * @param <V> type of value * @param name - name of object * @param codec - provided codec * @return Multimap object */ <K, V> RMultimapAsync<K, V> getSetMultimap(String name, Codec codec); /** * Returns Set based Multimap instance by name. * Supports key-entry eviction with a given TTL value. * * <p>If eviction is not required then it's better to use regular map {@link #getSetMultimap(String)}.</p> * * @param <K> type of key * @param <V> type of value * @param name - name of object * @return SetMultimapCache object */ <K, V> RMultimapCacheAsync<K, V> getSetMultimapCache(String name); /** * Returns Set based Multimap instance by name * using provided codec for both map keys and values. * Supports key-entry eviction with a given TTL value. * * <p>If eviction is not required then it's better to use regular map {@link #getSetMultimap(String, Codec)}.</p> * * @param <K> type of key * @param <V> type of value * @param name - name of object * @param codec - provided codec * @return SetMultimapCache object */ <K, V> RMultimapCacheAsync<K, V> getSetMultimapCache(String name, Codec codec); /** * Returns set-based cache instance by <code>name</code>. * Uses map (value_hash, value) under the hood for minimal memory consumption. * Supports value eviction with a given TTL value. * * <p>If eviction is not required then it's better to use regular map {@link #getSet(String, Codec)}.</p> * * @param <V> type of value * @param name - name of object * @return SetCache object */ <V> RSetCacheAsync<V> getSetCache(String name); /** * Returns set-based cache instance by <code>name</code> * using provided <code>codec</code> for values. * Uses map (value_hash, value) under the hood for minimal memory consumption. * Supports value eviction with a given TTL value. * * <p>If eviction is not required then it's better to use regular map {@link #getSet(String, Codec)}.</p> * * @param <V> type of value * @param name - name of object * @param codec - codec for values * @return SetCache object */ <V> RSetCacheAsync<V> getSetCache(String name, Codec codec); /** * Returns map-based cache instance by <code>name</code> * using provided <code>codec</code> for both cache keys and values. * Supports entry eviction with a given TTL value. * * <p>If eviction is not required then it's better to use regular map {@link #getMap(String, Codec)}.</p> * * @param <K> type of key * @param <V> type of value * @param name - name of object * @param codec - codec for keys and values * @return MapCache object */ <K, V> RMapCacheAsync<K, V> getMapCache(String name, Codec codec); /** * Returns map-based cache instance by <code>name</code>. * Supports entry eviction with a given TTL value. * * <p>If eviction is not required then it's better to use regular map {@link #getMap(String)}.</p> * * @param <K> type of key * @param <V> type of value * @param name - name of object * @return MapCache object */ <K, V> RMapCacheAsync<K, V> getMapCache(String name); /** * Returns map instance by name. * Supports entry eviction with a given TTL. * <p> * Requires <b>Redis 7.4.0 and higher.</b> or <b>Valkey 9.0.0 and higher.</b> * * @param <K> type of key * @param <V> type of value * @param name name of object * @return Map object */ <K, V> RMapCacheNativeAsync<K, V> getMapCacheNative(String name); /** * Returns map instance by name * using provided codec for both map keys and values. * Supports entry eviction with a given TTL. * <p> * Requires <b>Redis 7.4.0 and higher.</b> or <b>Valkey 9.0.0 and higher.</b> * * @param <K> type of key * @param <V> type of value * @param name name of object * @param codec codec for keys and values * @return Map object */ <K, V> RMapCacheNativeAsync<K, V> getMapCacheNative(String name, Codec codec); /** * Returns object holder by <code>name</code> * * @param <V> type of object * @param name - name of object * @return Bucket object */ <V> RBucketAsync<V> getBucket(String name); <V> RBucketAsync<V> getBucket(String name, Codec codec); /** * Returns JSON data holder instance by name using provided codec. * * @see org.redisson.codec.JacksonCodec * * @param <V> type of value * @param name name of object * @param codec codec for values * @return JsonBucket object */ <V> RJsonBucketAsync<V> getJsonBucket(String name, JsonCodec codec); /** * Returns HyperLogLog object * * @param <V> type of object * @param name - name of object * @return HyperLogLog object */ <V> RHyperLogLogAsync<V> getHyperLogLog(String name); <V> RHyperLogLogAsync<V> getHyperLogLog(String name, Codec codec); /** * Returns list instance by name. * * @param <V> type of object * @param name - name of object * @return List object */ <V> RListAsync<V> getList(String name); <V> RListAsync<V> getList(String name, Codec codec); /** * Returns List based MultiMap instance by name. * * @param <K> type of key * @param <V> type of value * @param name - name of object * @return ListMultimap object */ <K, V> RMultimapAsync<K, V> getListMultimap(String name); /** * Returns List based MultiMap instance by name * using provided codec for both map keys and values. * * @param <K> type of key * @param <V> type of value * @param name - name of object * @param codec - codec for keys and values * @return ListMultimap object */ <K, V> RMultimapAsync<K, V> getListMultimap(String name, Codec codec); /** * Returns List based Multimap instance by name. * Supports key-entry eviction with a given TTL value. * * <p>If eviction is not required then it's better to use regular map {@link #getSetMultimap(String)}.</p> * * @param <K> type of key * @param <V> type of value * @param name - name of object * @return ListMultimapCache object */ <K, V> RMultimapCacheAsync<K, V> getListMultimapCache(String name); /** * Returns List based Multimap instance by name * using provided codec for both map keys and values. * Supports key-entry eviction with a given TTL value. * * <p>If eviction is not required then it's better to use regular map {@link #getSetMultimap(String, Codec)}.</p> * * @param <K> type of key * @param <V> type of value * @param name - name of object * @param codec - codec for keys and values * @return ListMultimapCache object */ <K, V> RMultimapCacheAsync<K, V> getListMultimapCache(String name, Codec codec); /** * Returns List based Multimap instance by name. * Supports key-entry eviction with a given TTL value. * Stores insertion order and allows duplicates for values mapped to key. * <p> * Uses Redis native commands for entry expiration and not a scheduled eviction task. * <p> * Requires <b>Redis 7.4.0 and higher.</b> or <b>Valkey 9.0.0 and higher.</b> * * @param <K> type of key * @param <V> type of value * @param name name of object * @return ListMultimapCache object */ <K, V> RMultimapCacheAsync<K, V> getListMultimapCacheNative(String name); /** * Returns List based Multimap instance by name * using provided codec for both map keys and values. * Supports key-entry eviction with a given TTL value. * Stores insertion order and allows duplicates for values mapped to key. * <p> * Uses Redis native commands for entry expiration and not a scheduled eviction task. * <p> * Requires <b>Redis 7.4.0 and higher.</b> or <b>Valkey 9.0.0 and higher.</b> * * @param <K> type of key * @param <V> type of value * @param name name of object * @param codec codec for keys and values * @return ListMultimapCache object */ <K, V> RMultimapCacheAsync<K, V> getListMultimapCacheNative(String name, Codec codec); /** * Returns Set based Multimap instance by name. * Supports key-entry eviction with a given TTL value. * Doesn't allow duplications for values mapped to key. * <p> * Uses Redis native commands for entry expiration and not a scheduled eviction task. * <p> * Requires <b>Redis 7.4.0 and higher.</b> or <b>Valkey 9.0.0 and higher.</b> * * @param <K> type of key * @param <V> type of value * @param name name of object * @return SetMultimapCache object */ <K, V> RMultimapCacheAsync<K, V> getSetMultimapCacheNative(String name); /** * Returns Set based Multimap instance by name * using provided codec for both map keys and values. * Supports key-entry eviction with a given TTL value. * Doesn't allow duplications for values mapped to key. * <p> * Uses Redis native commands for entry expiration and not a scheduled eviction task. * <p> * Requires <b>Redis 7.4.0 and higher.</b> or <b>Valkey 9.0.0 and higher.</b> * * @param <K> type of key * @param <V> type of value * @param name name of object * @param codec codec for keys and values * @return SetMultimapCache object */ <K, V> RMultimapCacheAsync<K, V> getSetMultimapCacheNative(String name, Codec codec); /** * Returns map instance by name. * * @param <K> type of key * @param <V> type of value * @param name - name of object * @return Map object */ <K, V> RMapAsync<K, V> getMap(String name); <K, V> RMapAsync<K, V> getMap(String name, Codec codec); /** * Returns set instance by name. * * @param <V> type of value * @param name - name of object * @return Set object */ <V> RSetAsync<V> getSet(String name); <V> RSetAsync<V> getSet(String name, Codec codec); /** * Returns topic instance by name. * * @param name - name of object * @return Topic object */ RTopicAsync getTopic(String name); RTopicAsync getTopic(String name, Codec codec); /** * Returns Sharded Topic instance by name. * <p> * Messages are delivered to message listeners connected to the same Topic. * <p> * * @param name - name of object * @return Topic object */ RShardedTopicAsync getShardedTopic(String name); /** * Returns Sharded Topic instance by name using provided codec for messages. * <p> * Messages are delivered to message listeners connected to the same Topic. * <p> * * @param name - name of object * @param codec - codec for message * @return Topic object */ RShardedTopicAsync getShardedTopic(String name, Codec codec); /** * Returns queue instance by name. * * @param <V> type of value * @param name - name of object * @return Queue object */ <V> RQueueAsync<V> getQueue(String name); <V> RQueueAsync<V> getQueue(String name, Codec codec); /** * Returns blocking queue instance by name. * * @param <V> type of value * @param name - name of object * @return BlockingQueue object */ <V> RBlockingQueueAsync<V> getBlockingQueue(String name); <V> RBlockingQueueAsync<V> getBlockingQueue(String name, Codec codec); /** * Returns deque instance by name. * * @param <V> type of value * @param name - name of object * @return Deque object */ <V> RDequeAsync<V> getDeque(String name); <V> RDequeAsync<V> getDeque(String name, Codec codec); /** * Returns blocking deque instance by name. * * @param <V> type of value * @param name - name of object * @return BlockingDeque object */ <V> RBlockingDequeAsync<V> getBlockingDeque(String name); <V> RBlockingDequeAsync<V> getBlockingDeque(String name, Codec codec); /** * Returns atomicLong instance by name. * * @param name - name of object * @return AtomicLong object */ RAtomicLongAsync getAtomicLong(String name); /** * Returns atomicDouble instance by name. * * @param name - name of object * @return AtomicDouble object */ RAtomicDoubleAsync getAtomicDouble(String name); /** * Returns Redis Sorted Set instance by name * * @param <V> type of value * @param name - name of object * @return ScoredSortedSet object */ <V> RScoredSortedSetAsync<V> getScoredSortedSet(String name); <V> RScoredSortedSetAsync<V> getScoredSortedSet(String name, Codec codec); /** * Returns String based Redis Sorted Set instance by name * All elements are inserted with the same score during addition, * in order to force lexicographical ordering * * @param name - name of object * @return LexSortedSet object */ RLexSortedSetAsync getLexSortedSet(String name); /** * Returns bitSet instance by name. * * @param name - name of object * @return BitSet object */ RBitSetAsync getBitSet(String name); /** * Returns script operations object * * @return Script object */ RScriptAsync getScript(); /** * Returns script operations object using provided codec. * * @param codec - codec for params and result * @return Script object */ RScriptAsync getScript(Codec codec); /** * Returns
RBatch
java
apache__camel
components/camel-bean/src/main/java/org/apache/camel/component/bean/ProxyHelper.java
{ "start": 1077, "end": 4419 }
class ____ { /** * Utility classes should not have a public constructor. */ private ProxyHelper() { } /** * Creates a Proxy which sends the exchange to the endpoint. */ @SuppressWarnings("unchecked") public static <T> T createProxyObject( Endpoint endpoint, boolean binding, Producer producer, ClassLoader classLoader, Class<T>[] interfaces, MethodInfoCache methodCache) { return (T) Proxy.newProxyInstance(classLoader, interfaces.clone(), new CamelInvocationHandler(endpoint, binding, producer, methodCache)); } /** * Creates a Proxy which sends the exchange to the endpoint. */ public static <T> T createProxy( Endpoint endpoint, boolean binding, ClassLoader cl, Class<T> interfaceClass, MethodInfoCache methodCache) throws Exception { return createProxy(endpoint, binding, cl, toArray(interfaceClass), methodCache); } /** * Creates a Proxy which sends the exchange to the endpoint. */ public static <T> T createProxy( Endpoint endpoint, boolean binding, ClassLoader cl, Class<T>[] interfaceClasses, MethodInfoCache methodCache) throws Exception { Producer producer = PluginHelper.getDeferServiceFactory(endpoint.getCamelContext()) .createProducer(endpoint); return createProxyObject(endpoint, binding, producer, cl, interfaceClasses, methodCache); } /** * Creates a Proxy which sends the exchange to the endpoint. */ public static <T> T createProxy(Endpoint endpoint, ClassLoader cl, Class<T> interfaceClass) throws Exception { return createProxy(endpoint, true, cl, toArray(interfaceClass)); } /** * Creates a Proxy which sends the exchange to the endpoint. */ public static <T> T createProxy(Endpoint endpoint, boolean binding, ClassLoader cl, Class<T>... interfaceClasses) throws Exception { return createProxy(endpoint, binding, cl, interfaceClasses, createMethodInfoCache(endpoint)); } /** * Creates a Proxy which sends the exchange to the endpoint. */ public static <T> T createProxy(Endpoint endpoint, Class<T> interfaceClass) throws Exception { return createProxy(endpoint, true, toArray(interfaceClass)); } /** * Creates a Proxy which sends the exchange to the endpoint. */ public static <T> T createProxy(Endpoint endpoint, boolean binding, Class<T>... interfaceClasses) throws Exception { return createProxy(endpoint, binding, getClassLoader(interfaceClasses), interfaceClasses); } /** * Creates a Proxy which sends the exchange to the endpoint. */ public static <T> T createProxy(Endpoint endpoint, Producer producer, Class<T> interfaceClass) { return createProxy(endpoint, true, producer, toArray(interfaceClass)); } /** * Creates a Proxy which sends the exchange to the endpoint. */ public static <T> T createProxy(Endpoint endpoint, boolean binding, Producer producer, Class<T>... interfaceClasses) { return createProxyObject(endpoint, binding, producer, getClassLoader(interfaceClasses), interfaceClasses, createMethodInfoCache(endpoint)); } /** * Returns the
ProxyHelper
java
netty__netty
codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java
{ "start": 5236, "end": 7949 }
class ____ { final Http2Stream stream; int streamableBytes; boolean windowNegative; boolean enqueued; boolean writing; State(Http2Stream stream) { this.stream = stream; } void updateStreamableBytes(int newStreamableBytes, boolean hasFrame, int windowSize) { assert hasFrame || newStreamableBytes == 0 : "hasFrame: " + hasFrame + " newStreamableBytes: " + newStreamableBytes; int delta = newStreamableBytes - streamableBytes; if (delta != 0) { streamableBytes = newStreamableBytes; totalStreamableBytes += delta; } // In addition to only enqueuing state when they have frames we enforce the following restrictions: // 1. If the window has gone negative. We never want to queue a state. However we also don't want to // Immediately remove the item if it is already queued because removal from deque is O(n). So // we allow it to stay queued and rely on the distribution loop to remove this state. // 2. If the window is zero we only want to queue if we are not writing. If we are writing that means // we gave the state a chance to write zero length frames. We wait until updateStreamableBytes is // called again before this state is allowed to write. windowNegative = windowSize < 0; if (hasFrame && (windowSize > 0 || windowSize == 0 && !writing)) { addToQueue(); } } /** * Write any allocated bytes for the given stream and updates the streamable bytes, * assuming all of the bytes will be written. */ void write(int numBytes, Writer writer) throws Http2Exception { writing = true; try { // Write the allocated bytes. writer.write(stream, numBytes); } catch (Throwable t) { throw connectionError(INTERNAL_ERROR, t, "byte distribution write error"); } finally { writing = false; } } void addToQueue() { if (!enqueued) { enqueued = true; queue.addLast(this); } } void removeFromQueue() { if (enqueued) { enqueued = false; queue.remove(this); } } void close() { // Remove this state from the queue. removeFromQueue(); // Clear the streamable bytes. updateStreamableBytes(0, false, 0); } } }
State
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/FileIOChannel.java
{ "start": 4575, "end": 5549 }
class ____ { private static AtomicInteger globalCounter = new AtomicInteger(); private final File[] paths; private final String namePrefix; private int localCounter; public Enumerator(File[] basePaths, Random random) { this.paths = basePaths; this.namePrefix = ID.randomString(random); this.localCounter = 0; } public ID next() { // The local counter is used to increment file names while the global counter is used // for indexing the directory and associated read and write threads. This performs a // round-robin among all spilling operators and avoids I/O bunching. int threadNum = globalCounter.getAndIncrement() % paths.length; String filename = String.format("%s.%06d.channel", namePrefix, (localCounter++)); return new ID(new File(paths[threadNum], filename), threadNum); } } }
Enumerator
java
apache__hadoop
hadoop-cloud-storage-project/hadoop-cos/src/main/java/org/apache/hadoop/fs/cosn/CosNFileReadTask.java
{ "start": 1478, "end": 4591 }
class ____ implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(CosNFileReadTask.class); private final String key; private final NativeFileSystemStore store; private final CosNInputStream.ReadBuffer readBuffer; private RetryPolicy retryPolicy; public CosNFileReadTask( Configuration conf, String key, NativeFileSystemStore store, CosNInputStream.ReadBuffer readBuffer) { this.key = key; this.store = store; this.readBuffer = readBuffer; RetryPolicy defaultPolicy = RetryPolicies.retryUpToMaximumCountWithFixedSleep( conf.getInt( CosNConfigKeys.COSN_MAX_RETRIES_KEY, CosNConfigKeys.DEFAULT_MAX_RETRIES), conf.getLong( CosNConfigKeys.COSN_RETRY_INTERVAL_KEY, CosNConfigKeys.DEFAULT_RETRY_INTERVAL), TimeUnit.SECONDS); Map<Class<? extends Exception>, RetryPolicy> retryPolicyMap = new HashMap<>(); retryPolicyMap.put(IOException.class, defaultPolicy); retryPolicyMap.put( IndexOutOfBoundsException.class, RetryPolicies.TRY_ONCE_THEN_FAIL); retryPolicyMap.put( NullPointerException.class, RetryPolicies.TRY_ONCE_THEN_FAIL); this.retryPolicy = RetryPolicies.retryByException( defaultPolicy, retryPolicyMap); } @Override public void run() { int retries = 0; RetryPolicy.RetryAction retryAction; try { this.readBuffer.lock(); do { try { InputStream inputStream = this.store.retrieveBlock(this.key, this.readBuffer.getStart(), this.readBuffer.getEnd()); IOUtils.readFully(inputStream, this.readBuffer.getBuffer(), 0, readBuffer.getBuffer().length); inputStream.close(); this.readBuffer.setStatus(CosNInputStream.ReadBuffer.SUCCESS); break; } catch (IOException e) { this.readBuffer.setStatus(CosNInputStream.ReadBuffer.ERROR); LOG.warn( "Exception occurs when retrieve the block range start: " + String.valueOf(this.readBuffer.getStart()) + " end: " + this.readBuffer.getEnd()); try { retryAction = this.retryPolicy.shouldRetry( e, retries++, 0, true); if (retryAction.action == RetryPolicy.RetryAction.RetryDecision.RETRY) { Thread.sleep(retryAction.delayMillis); } } catch (Exception e1) { String errMsg = String.format("Exception occurs when retry[%s] " + "to retrieve the block range start: %s, end:%s", this.retryPolicy.toString(), String.valueOf(this.readBuffer.getStart()), String.valueOf(this.readBuffer.getEnd())); LOG.error(errMsg, e1); break; } } } while (retryAction.action == RetryPolicy.RetryAction.RetryDecision.RETRY); this.readBuffer.signalAll(); } finally { this.readBuffer.unLock(); } } }
CosNFileReadTask
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/aggfunctions/FirstValueAggFunctionWithOrderTest.java
{ "start": 6777, "end": 8820 }
class ____ extends FirstValueAggFunctionWithOrderTestBase<DecimalData> { private int precision = 20; private int scale = 6; @Override protected List<List<DecimalData>> getInputValueSets() { return Arrays.asList( Arrays.asList( DecimalDataUtils.castFrom("1", precision, scale), DecimalDataUtils.castFrom("1000.000001", precision, scale), DecimalDataUtils.castFrom("-1", precision, scale), DecimalDataUtils.castFrom("-999.998999", precision, scale), null, DecimalDataUtils.castFrom("0", precision, scale), DecimalDataUtils.castFrom("-999.999", precision, scale), null, DecimalDataUtils.castFrom("999.999", precision, scale)), Arrays.asList(null, null, null, null, null), Arrays.asList(null, DecimalDataUtils.castFrom("0", precision, scale))); } @Override protected List<List<Long>> getInputOrderSets() { return Arrays.asList( Arrays.asList(10L, 2L, 1L, 5L, null, 3L, 1L, 5L, 2L), Arrays.asList(6L, 5L, null, 8L, null), Arrays.asList(8L, 6L)); } @Override protected List<DecimalData> getExpectedResults() { return Arrays.asList( DecimalDataUtils.castFrom("-1", precision, scale), null, DecimalDataUtils.castFrom("0", precision, scale)); } @Override protected AggregateFunction<DecimalData, RowData> getAggregator() { return new FirstValueAggFunction<>( DataTypes.DECIMAL(precision, scale).getLogicalType()); } } /** Test for {@link VarCharType}. */ @Nested final
DecimalFirstValueAggFunctionWithOrderTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/date/DateAssert_hasSecond_Test.java
{ "start": 838, "end": 1189 }
class ____ extends AbstractDateAssertWithOneIntArg_Test { @Override protected DateAssert assertionInvocationWithOneIntArg() { return assertions.hasSecond(intArg); } @Override protected void verifyAssertionInvocation() { verify(dates).assertHasSecond(getInfo(assertions), getActual(assertions), intArg); } }
DateAssert_hasSecond_Test
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java
{ "start": 22183, "end": 22583 }
class ____ { UserDetailsService uds = mock(UserDetailsService.class); @Bean UserDetailsService userDetailsService() { return this.uds; } @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } @Configuration @Import({ AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class }) static
UserDetailsServiceBeanWithPasswordEncoderConfig
java
elastic__elasticsearch
x-pack/plugin/ilm/qa/multi-node/src/javaRestTest/java/org/elasticsearch/xpack/TimeSeriesRestDriver.java
{ "start": 2876, "end": 2987 }
class ____ the operational REST functions needed to control an ILM time series lifecycle. */ public final
provides
java
netty__netty
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/extensions/WebSocketExtensionDecoder.java
{ "start": 949, "end": 1119 }
class ____ extends MessageToMessageDecoder<WebSocketFrame> { public WebSocketExtensionDecoder() { super(WebSocketFrame.class); } }
WebSocketExtensionDecoder
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleDetach.java
{ "start": 1006, "end": 1346 }
class ____<T> extends Single<T> { final SingleSource<T> source; public SingleDetach(SingleSource<T> source) { this.source = source; } @Override protected void subscribeActual(SingleObserver<? super T> observer) { source.subscribe(new DetachSingleObserver<>(observer)); } static final
SingleDetach
java
google__dagger
javatests/dagger/functional/subcomponent/ChildAbstractClassComponent.java
{ "start": 753, "end": 817 }
class ____ implements ChildComponent { }
ChildAbstractClassComponent
java
apache__flink
flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/testutils/junit/RetryOnFailure.java
{ "start": 1962, "end": 2008 }
interface ____ { int times(); }
RetryOnFailure
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/date/DateFieldTest4.java
{ "start": 3116, "end": 3363 }
class ____ { private Date value; @JSONField(format = "yyyy-MM-dd") public Date getValue() { return value; } public void setValue(Date value) { this.value = value; } } }
V0
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/TestSubtypes.java
{ "start": 522, "end": 632 }
class ____ extends DatabindTestUtil { @JsonTypeInfo(use=JsonTypeInfo.Id.NAME) static abstract
TestSubtypes
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/Jt400EndpointBuilderFactory.java
{ "start": 47581, "end": 50143 }
interface ____ extends EndpointProducerBuilder { default Jt400EndpointProducerBuilder basic() { return (Jt400EndpointProducerBuilder) this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedJt400EndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedJt400EndpointProducerBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } } /** * Builder for endpoint for the JT400 component. */ public
AdvancedJt400EndpointProducerBuilder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/MultiLoadTest.java
{ "start": 19772, "end": 20170 }
class ____ { Integer id; String text; public SimpleEntity() { } public SimpleEntity(Integer id, String text) { this.id = id; this.text = text; } @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } } }
SimpleEntity
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/BedrockAgentEndpointBuilderFactory.java
{ "start": 61679, "end": 65516 }
interface ____ extends EndpointProducerBuilder { default BedrockAgentEndpointProducerBuilder basic() { return (BedrockAgentEndpointProducerBuilder) this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedBedrockAgentEndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedBedrockAgentEndpointProducerBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * To use an existing configured AWS Bedrock Agent client. * * The option is a: * <code>software.amazon.awssdk.services.bedrockagent.BedrockAgentClient</code> type. * * Group: advanced * * @param bedrockAgentClient the value to set * @return the dsl builder */ default AdvancedBedrockAgentEndpointProducerBuilder bedrockAgentClient(software.amazon.awssdk.services.bedrockagent.BedrockAgentClient bedrockAgentClient) { doSetProperty("bedrockAgentClient", bedrockAgentClient); return this; } /** * To use an existing configured AWS Bedrock Agent client. * * The option will be converted to a * <code>software.amazon.awssdk.services.bedrockagent.BedrockAgentClient</code> type. * * Group: advanced * * @param bedrockAgentClient the value to set * @return the dsl builder */ default AdvancedBedrockAgentEndpointProducerBuilder bedrockAgentClient(String bedrockAgentClient) { doSetProperty("bedrockAgentClient", bedrockAgentClient); return this; } } /** * Builder for endpoint for the AWS Bedrock Agent component. */ public
AdvancedBedrockAgentEndpointProducerBuilder
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ConstantOverflowTest.java
{ "start": 1221, "end": 2071 }
class ____ { static final int C = 1; void g(int x) {} void f() { // BUG: Diagnostic contains: if (1000L * 1000 * 1000 * 10 * 1L == 0) if (1000 * 1000 * 1000 * 10 * 1L == 0) ; // BUG: Diagnostic contains: int x = (int) (1000L * 1000 * 1000 * 10 * 1L); int x = (int) (1000 * 1000 * 1000 * 10 * 1L); // BUG: Diagnostic contains: long y = 1000L * 1000 * 1000 * 10; int y = 1000 * 1000 * 1000 * 10; // BUG: Diagnostic contains: g(C * 1000 * 1000 * 1000 * 10); } } """) .doTest(); } @Test public void positiveFields() { testHelper .addSourceLines( "Test.java", """
Test
java
google__dagger
hilt-testing/main/java/dagger/hilt/android/testing/compile/HiltCompilerProcessors.java
{ "start": 2518, "end": 3030 }
class ____ implements SymbolProcessorProvider { private final Function<XProcessingEnv, BaseProcessingStep> processingStep; Provider(Function<XProcessingEnv, BaseProcessingStep> processingStep) { this.processingStep = processingStep; } @Override public SymbolProcessor create(SymbolProcessorEnvironment symbolProcessorEnvironment) { return new KspProcessor(symbolProcessorEnvironment, processingStep); } } } private HiltCompilerProcessors() {} }
Provider
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/reflect/ClassUtils.java
{ "start": 8234, "end": 8551 }
class ____ */ public static String pathToClassName(String path) { path = path.replace('/', '.'); if (path.endsWith(CLASS_EXTENSION)) { path = path.substring(0, path.length() - CLASS_EXTENSION.length()); } return path; } /** * Check whether the given
name
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/MPNetTokenizationUpdateTests.java
{ "start": 595, "end": 3221 }
class ____ extends AbstractBWCWireSerializationTestCase<MPNetTokenizationUpdate> { public static MPNetTokenizationUpdate randomInstance() { Integer span = randomBoolean() ? null : randomIntBetween(8, 128); Tokenization.Truncate truncate = randomBoolean() ? null : randomFrom(Tokenization.Truncate.values()); if (truncate != Tokenization.Truncate.NONE) { span = null; } return new MPNetTokenizationUpdate(truncate, span); } public void testApply() { expectThrows( IllegalArgumentException.class, () -> new MPNetTokenizationUpdate(Tokenization.Truncate.SECOND, 100).apply(MPNetTokenizationTests.createRandom()) ); var updatedSpan = new MPNetTokenizationUpdate(null, 100).apply( new MPNetTokenization(false, false, 512, Tokenization.Truncate.NONE, 50) ); assertEquals(new MPNetTokenization(false, false, 512, Tokenization.Truncate.NONE, 100), updatedSpan); var updatedTruncate = new MPNetTokenizationUpdate(Tokenization.Truncate.FIRST, null).apply( new MPNetTokenization(true, true, 512, Tokenization.Truncate.SECOND, null) ); assertEquals(new MPNetTokenization(true, true, 512, Tokenization.Truncate.FIRST, null), updatedTruncate); var updatedNone = new MPNetTokenizationUpdate(Tokenization.Truncate.NONE, null).apply( new MPNetTokenization(true, true, 512, Tokenization.Truncate.SECOND, null) ); assertEquals(new MPNetTokenization(true, true, 512, Tokenization.Truncate.NONE, null), updatedNone); var unmodified = new MPNetTokenization(true, true, 512, Tokenization.Truncate.NONE, null); assertThat(new MPNetTokenizationUpdate(null, null).apply(unmodified), sameInstance(unmodified)); } @Override protected Writeable.Reader<MPNetTokenizationUpdate> instanceReader() { return MPNetTokenizationUpdate::new; } @Override protected MPNetTokenizationUpdate createTestInstance() { return randomInstance(); } @Override protected MPNetTokenizationUpdate mutateInstance(MPNetTokenizationUpdate instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected MPNetTokenizationUpdate mutateInstanceForVersion(MPNetTokenizationUpdate instance, TransportVersion version) { if (version.before(TransportVersions.V_8_2_0)) { return new MPNetTokenizationUpdate(instance.getTruncate(), null); } return instance; } }
MPNetTokenizationUpdateTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java
{ "start": 38129, "end": 38494 }
class ____ { public int test(int a) { a = 2; return a; } } """) .doTest(); } @Test public void assignmentToEnhancedForLoop() { refactoringHelper .addInputLines( "Test.java", """ package unusedvars; public
Test
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/checkpointing/UnalignedCheckpointRescaleITCase.java
{ "start": 24501, "end": 31342 }
class ____ extends KeyedBroadcastProcessFunction<Long, Long, Long, Long> { private static final long serialVersionUID = 7852973507735751404L; TestKeyedBroadcastProcessFunction() {} @Override public void processElement(Long value, ReadOnlyContext ctx, Collector<Long> out) { out.collect(checkHeader(value)); } @Override public void processBroadcastElement(Long value, Context ctx, Collector<Long> out) {} } } @Parameterized.Parameters(name = "{0} {1} from {2} to {3}, sourceSleepMs = {4}") public static Object[][] getScaleFactors() { // We use `sourceSleepMs` > 0 to test rescaling without backpressure and only very few // captured in-flight records, see FLINK-31963. Object[][] parameters = new Object[][] { new Object[] {"downscale", Topology.CUSTOM_PARTITIONER, 3, 2, 0L}, new Object[] {"downscale", Topology.KEYED_DIFFERENT_PARALLELISM, 12, 7, 0L}, new Object[] {"upscale", Topology.KEYED_DIFFERENT_PARALLELISM, 7, 12, 0L}, new Object[] {"downscale", Topology.KEYED_DIFFERENT_PARALLELISM, 5, 3, 5L}, new Object[] {"upscale", Topology.KEYED_DIFFERENT_PARALLELISM, 3, 5, 5L}, new Object[] {"downscale", Topology.KEYED_BROADCAST, 7, 2, 0L}, new Object[] {"upscale", Topology.KEYED_BROADCAST, 2, 7, 0L}, new Object[] {"downscale", Topology.KEYED_BROADCAST, 5, 3, 5L}, new Object[] {"upscale", Topology.KEYED_BROADCAST, 3, 5, 5L}, new Object[] {"downscale", Topology.BROADCAST, 5, 2, 0L}, new Object[] {"upscale", Topology.BROADCAST, 2, 5, 0L}, new Object[] {"downscale", Topology.BROADCAST, 5, 3, 5L}, new Object[] {"upscale", Topology.BROADCAST, 3, 5, 5L}, new Object[] {"upscale", Topology.PIPELINE, 1, 2, 0L}, new Object[] {"upscale", Topology.PIPELINE, 2, 3, 0L}, new Object[] {"upscale", Topology.PIPELINE, 3, 7, 0L}, new Object[] {"upscale", Topology.PIPELINE, 4, 8, 0L}, new Object[] {"upscale", Topology.PIPELINE, 20, 21, 0L}, new Object[] {"upscale", Topology.PIPELINE, 3, 5, 5L}, new Object[] {"downscale", Topology.PIPELINE, 2, 1, 0L}, new Object[] {"downscale", Topology.PIPELINE, 3, 2, 0L}, new Object[] {"downscale", Topology.PIPELINE, 7, 3, 0L}, new Object[] {"downscale", Topology.PIPELINE, 8, 4, 0L}, new Object[] {"downscale", Topology.PIPELINE, 21, 20, 0L}, new Object[] {"downscale", Topology.PIPELINE, 5, 3, 5L}, new Object[] {"no scale", Topology.PIPELINE, 1, 1, 0L}, new Object[] {"no scale", Topology.PIPELINE, 3, 3, 0L}, new Object[] {"no scale", Topology.PIPELINE, 7, 7, 0L}, new Object[] {"no scale", Topology.PIPELINE, 20, 20, 0L}, new Object[] {"upscale", Topology.UNION, 1, 2, 0L}, new Object[] {"upscale", Topology.UNION, 2, 3, 0L}, new Object[] {"upscale", Topology.UNION, 3, 7, 0L}, new Object[] {"upscale", Topology.UNION, 3, 5, 5L}, new Object[] {"downscale", Topology.UNION, 2, 1, 0L}, new Object[] {"downscale", Topology.UNION, 3, 2, 0L}, new Object[] {"downscale", Topology.UNION, 7, 3, 0L}, new Object[] {"downscale", Topology.UNION, 5, 3, 5L}, new Object[] {"no scale", Topology.UNION, 1, 1, 0L}, new Object[] {"no scale", Topology.UNION, 7, 7, 0L}, new Object[] {"upscale", Topology.MULTI_INPUT, 1, 2, 0L}, new Object[] {"upscale", Topology.MULTI_INPUT, 2, 3, 0L}, new Object[] {"upscale", Topology.MULTI_INPUT, 3, 7, 0L}, new Object[] {"upscale", Topology.MULTI_INPUT, 3, 5, 5L}, new Object[] {"downscale", Topology.MULTI_INPUT, 2, 1, 0L}, new Object[] {"downscale", Topology.MULTI_INPUT, 3, 2, 0L}, new Object[] {"downscale", Topology.MULTI_INPUT, 7, 3, 0L}, new Object[] {"downscale", Topology.MULTI_INPUT, 5, 3, 5L}, new Object[] {"no scale", Topology.MULTI_INPUT, 1, 1, 0L}, new Object[] {"no scale", Topology.MULTI_INPUT, 7, 7, 0L}, }; return Arrays.stream(parameters) .map(params -> new Object[][] {ArrayUtils.insert(params.length, params)}) .flatMap(Arrays::stream) .toArray(Object[][]::new); } public UnalignedCheckpointRescaleITCase( String desc, Topology topology, int oldParallelism, int newParallelism, long sourceSleepMs) { this.topology = topology; this.oldParallelism = oldParallelism; this.newParallelism = newParallelism; this.sourceSleepMs = sourceSleepMs; } @Test public void shouldRescaleUnalignedCheckpoint() throws Exception { final UnalignedSettings prescaleSettings = new UnalignedSettings(topology) .setParallelism(oldParallelism) .setExpectedFailures(1) .setSourceSleepMs(sourceSleepMs); prescaleSettings.setGenerateCheckpoint(true); final File checkpointDir = super.execute(prescaleSettings); // resume final UnalignedSettings postscaleSettings = new UnalignedSettings(topology) .setParallelism(newParallelism) .setExpectedFailures(1); postscaleSettings.setRestoreCheckpoint(checkpointDir); super.execute(postscaleSettings); } protected void checkCounters(JobExecutionResult result) { collector.checkThat( "NUM_OUTPUTS = NUM_INPUTS", result.<Long>getAccumulatorResult(NUM_OUTPUTS), equalTo(result.getAccumulatorResult(NUM_INPUTS))); if (!topology.equals(Topology.CUSTOM_PARTITIONER)) { collector.checkThat( "NUM_DUPLICATES", result.<Long>getAccumulatorResult(NUM_DUPLICATES), equalTo(0L)); } } /** * A sink that checks if the members arrive in the expected order without any missing values. */ protected static
TestKeyedBroadcastProcessFunction
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/action/UpdateConnectorLastSyncStatsAction.java
{ "start": 8764, "end": 9513 }
class ____ { private String connectorId; private ConnectorSyncInfo syncInfo; private Object syncCursor; public Builder setConnectorId(String connectorId) { this.connectorId = connectorId; return this; } public Builder setSyncInfo(ConnectorSyncInfo syncInfo) { this.syncInfo = syncInfo; return this; } public Builder setSyncCursor(Object syncCursor) { this.syncCursor = syncCursor; return this; } public Request build() { return new Request(connectorId, syncInfo, syncCursor); } } } }
Builder
java
apache__kafka
trogdor/src/main/java/org/apache/kafka/trogdor/workload/PayloadGenerator.java
{ "start": 2161, "end": 2420 }
interface ____ { /** * Generate a payload. * * @param position The position to use to generate the payload * * @return A new array object containing the payload. */ byte[] generate(long position); }
PayloadGenerator
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/catalog/CatalogCalciteSchema.java
{ "start": 1497, "end": 3625 }
class ____ extends FlinkSchema { private final String catalogName; private final CatalogManager catalogManager; // Flag that tells if the current planner should work in a batch or streaming mode. private final boolean isStreamingMode; public CatalogCalciteSchema( String catalogName, CatalogManager catalog, boolean isStreamingMode) { this.catalogName = catalogName; this.catalogManager = catalog; this.isStreamingMode = isStreamingMode; } /** * Look up a sub-schema (database) by the given sub-schema name. * * @param schemaName name of sub-schema to look up * @return the sub-schema with a given database name, or null */ @Override public Schema getSubSchema(String schemaName) { if (catalogManager.schemaExists(catalogName, schemaName)) { if (getSchemaVersion().isPresent()) { return new DatabaseCalciteSchema( catalogName, schemaName, catalogManager, isStreamingMode) .snapshot(getSchemaVersion().get()); } else { return new DatabaseCalciteSchema( catalogName, schemaName, catalogManager, isStreamingMode); } } else { return null; } } @Override public Set<String> getSubSchemaNames() { return catalogManager.listSchemas(catalogName); } @Override public Table getTable(String name) { return null; } @Override public Set<String> getTableNames() { return new HashSet<>(); } @Override public Expression getExpression(SchemaPlus parentSchema, String name) { return Schemas.subSchemaExpression(parentSchema, name, getClass()); } @Override public boolean isMutable() { return true; } @Override public CatalogSchemaModel getModel(String name) { return null; } @Override public FlinkSchema copy() { return new CatalogCalciteSchema(catalogName, catalogManager, isStreamingMode); } }
CatalogCalciteSchema
java
dropwizard__dropwizard
dropwizard-testing/src/test/java/io/dropwizard/testing/junit5/DropwizardAppExtensionWithCustomCommandTest.java
{ "start": 674, "end": 1640 }
class ____ { private static final DropwizardAppExtension<TestConfiguration> EXTENSION = new DropwizardAppExtension<>( DropwizardTestApplication.class, "test-config.yaml", new ResourceConfigurationSourceProvider(), null, application -> new Command("test", "Test command") { @Override public void configure(Subparser subparser) { } @Override public void run(Bootstrap<?> bootstrap, Namespace namespace) throws Exception { } }); @Test void configurationIsNull() { assertThatNullPointerException().isThrownBy(EXTENSION::getConfiguration); } @Test void returnsApplication() { assertThat(EXTENSION.<DropwizardTestApplication>getApplication()).isNotNull(); } @Test void environmentIsNull() { assertThatNullPointerException().isThrownBy(EXTENSION::getEnvironment); } }
DropwizardAppExtensionWithCustomCommandTest
java
dropwizard__dropwizard
dropwizard-jackson/src/main/java/io/dropwizard/jackson/GuavaExtrasModule.java
{ "start": 1617, "end": 1928 }
class ____ extends JsonSerializer<CacheBuilderSpec> { @Override public void serialize(CacheBuilderSpec value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeString(value.toParsableString()); } } private static
CacheBuilderSpecSerializer
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/action/EsqlExecutionInfoTests.java
{ "start": 490, "end": 3026 }
class ____ extends ESTestCase { static final EsqlExecutionInfo.Cluster localCluster = new EsqlExecutionInfo.Cluster( RemoteClusterService.LOCAL_CLUSTER_GROUP_KEY, "test" ); static final EsqlExecutionInfo.Cluster remoteCluster = new EsqlExecutionInfo.Cluster("remote", "test"); public void testHasMetadataInclude() { // includeCCSMetadata + non-local clusters will produce true EsqlExecutionInfo info = new EsqlExecutionInfo(true); assertFalse(info.hasMetadataToReport()); info.swapCluster(RemoteClusterService.LOCAL_CLUSTER_GROUP_KEY, (k, v) -> localCluster); assertFalse(info.hasMetadataToReport()); info.swapCluster("remote", (k, v) -> remoteCluster); assertTrue(info.hasMetadataToReport()); // Only remote is enough info = new EsqlExecutionInfo(true); info.swapCluster("remote", (k, v) -> remoteCluster); assertTrue(info.hasMetadataToReport()); } public void testHasMetadataIncludeFalse() { // If includeCCSMetadata is false, then it should always return false EsqlExecutionInfo info = new EsqlExecutionInfo(false); assertFalse(info.hasMetadataToReport()); assertFalse(info.hasMetadataToReport()); info.swapCluster(RemoteClusterService.LOCAL_CLUSTER_GROUP_KEY, (k, v) -> localCluster); assertFalse(info.hasMetadataToReport()); info.swapCluster("remote", (k, v) -> remoteCluster); assertFalse(info.hasMetadataToReport()); } public void testHasMetadataPartial() { EsqlExecutionInfo info = new EsqlExecutionInfo(false); String key = randomFrom(RemoteClusterService.LOCAL_CLUSTER_GROUP_KEY, "remote"); info.swapCluster(key, (k, v) -> new EsqlExecutionInfo.Cluster(k, "test", false, EsqlExecutionInfo.Cluster.Status.SUCCESSFUL)); assertFalse(info.isPartial()); assertFalse(info.hasMetadataToReport()); info.swapCluster(key, (k, v) -> new EsqlExecutionInfo.Cluster(k, "test", false, EsqlExecutionInfo.Cluster.Status.PARTIAL)); assertTrue(info.isPartial()); assertFalse(info.hasMetadataToReport()); info.swapCluster(key, (k, v) -> { EsqlExecutionInfo.Cluster.Builder builder = new EsqlExecutionInfo.Cluster.Builder(v); builder.addFailures(List.of(new ShardSearchFailure(new IllegalStateException("shard failure")))); return builder.build(); }); assertTrue(info.hasMetadataToReport()); } }
EsqlExecutionInfoTests
java
grpc__grpc-java
benchmarks/src/generated/main/grpc/io/grpc/benchmarks/proto/BenchmarkServiceGrpc.java
{ "start": 30552, "end": 30728 }
class ____ extends BenchmarkServiceBaseDescriptorSupplier { BenchmarkServiceFileDescriptorSupplier() {} } private static final
BenchmarkServiceFileDescriptorSupplier
java
apache__flink
flink-filesystems/flink-s3-fs-base/src/main/java/com/amazonaws/services/s3/model/transform/XmlResponsesSaxParser.java
{ "start": 104255, "end": 108417 }
class ____ extends AbstractHandler { private final BucketCrossOriginConfiguration configuration = new BucketCrossOriginConfiguration(new ArrayList<CORSRule>()); private CORSRule currentRule; private List<AllowedMethods> allowedMethods = null; private List<String> allowedOrigins = null; private List<String> exposedHeaders = null; private List<String> allowedHeaders = null; public BucketCrossOriginConfiguration getConfiguration() { return configuration; } @Override protected void doStartElement(String uri, String name, String qName, Attributes attrs) { if (in("CORSConfiguration")) { if (name.equals("CORSRule")) { currentRule = new CORSRule(); } } else if (in("CORSConfiguration", "CORSRule")) { if (name.equals("AllowedOrigin")) { if (allowedOrigins == null) { allowedOrigins = new ArrayList<String>(); } } else if (name.equals("AllowedMethod")) { if (allowedMethods == null) { allowedMethods = new ArrayList<AllowedMethods>(); } } else if (name.equals("ExposeHeader")) { if (exposedHeaders == null) { exposedHeaders = new ArrayList<String>(); } } else if (name.equals("AllowedHeader")) { if (allowedHeaders == null) { allowedHeaders = new LinkedList<String>(); } } } } @Override protected void doEndElement(String uri, String name, String qName) { if (in("CORSConfiguration")) { if (name.equals("CORSRule")) { currentRule.setAllowedHeaders(allowedHeaders); currentRule.setAllowedMethods(allowedMethods); currentRule.setAllowedOrigins(allowedOrigins); currentRule.setExposedHeaders(exposedHeaders); allowedHeaders = null; allowedMethods = null; allowedOrigins = null; exposedHeaders = null; configuration.getRules().add(currentRule); currentRule = null; } } else if (in("CORSConfiguration", "CORSRule")) { if (name.equals("ID")) { currentRule.setId(getText()); } else if (name.equals("AllowedOrigin")) { allowedOrigins.add(getText()); } else if (name.equals("AllowedMethod")) { allowedMethods.add(AllowedMethods.fromValue(getText())); } else if (name.equals("MaxAgeSeconds")) { currentRule.setMaxAgeSeconds(Integer.parseInt(getText())); } else if (name.equals("ExposeHeader")) { exposedHeaders.add(getText()); } else if (name.equals("AllowedHeader")) { allowedHeaders.add(getText()); } } } } /* HTTP/1.1 200 OK x-amz-id-2: ITnGT1y4RyTmXa3rPi4hklTXouTf0hccUjo0iCPjz6FnfIutBj3M7fPGlWO2SEWp x-amz-request-id: 51991C342C575321 Date: Wed, 14 May 2014 02:11:22 GMT Server: AmazonS3 Content-Length: ... <?xml version="1.0" encoding="UTF-8"?> <MetricsConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <Id>metrics-id</Id> <Filter> <!-- A filter should have only one of Prefix, Tag or And predicate. -> <Prefix>prefix</Prefix> <Tag> <Key>Project</Key> <Value>Foo</Value> </Tag> <And> <Prefix>documents/</Prefix> <Tag> <Key>foo</Key> <Value>bar</Value> </Tag> </And> </Filter> </MetricsConfiguration> */ public static
BucketCrossOriginConfigurationHandler
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/fields/FieldsMappingTest.java
{ "start": 551, "end": 2382 }
class ____ { @ProcessorTest public void shouldMapSourceToTarget() { Source source = new Source(); source.normalInt = 4; source.normalList = Lists.newArrayList( 10, 11, 12 ); source.fieldOnlyWithGetter = 20; Target target = SourceTargetMapper.INSTANCE.toTarget( source ); assertThat( target ).isNotNull(); assertThat( target.finalInt ).isEqualTo( "10" ); assertThat( target.normalInt ).isEqualTo( "4" ); assertThat( target.finalList ).containsOnly( "1", "2", "3" ); assertThat( target.normalList ).containsOnly( "10", "11", "12" ); assertThat( target.privateFinalList ).containsOnly( 3, 4, 5 ); // +21 from the source getter and append 11 on the setter from the target assertThat( target.fieldWithMethods ).isEqualTo( "4111" ); } @ProcessorTest public void shouldMapTargetToSource() { Target target = new Target(); target.finalInt = "40"; target.normalInt = "4"; target.finalList = Lists.newArrayList( "2", "3" ); target.normalList = Lists.newArrayList( "10", "11", "12" ); target.privateFinalList = Lists.newArrayList( 10, 11, 12 ); target.fieldWithMethods = "20"; Source source = SourceTargetMapper.INSTANCE.toSource( target ); assertThat( source ).isNotNull(); assertThat( source.finalInt ).isEqualTo( 10 ); assertThat( source.normalInt ).isEqualTo( 4 ); assertThat( source.finalList ).containsOnly( 1, 2, 3 ); assertThat( source.normalList ).containsOnly( 10, 11, 12 ); assertThat( source.getPrivateFinalList() ).containsOnly( 3, 4, 5, 10, 11, 12 ); // 23 is appended on the target getter assertThat( source.fieldOnlyWithGetter ).isEqualTo( 2023 ); } }
FieldsMappingTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ObjectsHashCodePrimitiveTest.java
{ "start": 4926, "end": 5203 }
class ____ { void f() { double x = 3; int y = Objects.hashCode(x); } } """) .addOutputLines( "Test.java", """ import java.util.Objects;
Test
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inject/ScopeAnnotationOnInterfaceOrAbstractClassTest.java
{ "start": 1825, "end": 1932 }
interface ____ has scoping annotation. */ // BUG: Diagnostic contains: remove @Singleton public
interface
java
apache__camel
test-infra/camel-test-infra-azure-common/src/main/java/org/apache/camel/test/infra/azure/common/services/AzureServices.java
{ "start": 877, "end": 1039 }
class ____ { public static final int BLOB_SERVICE = 10000; public static final int QUEUE_SERVICE = 10001; private AzureServices() { } }
AzureServices
java
spring-projects__spring-boot
module/spring-boot-micrometer-observation/src/main/java/org/springframework/boot/micrometer/observation/autoconfigure/ObservationRegistryCustomizer.java
{ "start": 1005, "end": 1209 }
interface ____<T extends ObservationRegistry> { /** * Customize the given {@code registry}. * @param registry the registry to customize */ void customize(T registry); }
ObservationRegistryCustomizer
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/clusterframework/ContaineredTaskManagerParameters.java
{ "start": 1245, "end": 3941 }
class ____ implements java.io.Serializable { private static final long serialVersionUID = -3096987654278064670L; /** Environment variables to add to the Java process. */ private final HashMap<String, String> taskManagerEnv; private final TaskExecutorProcessSpec taskExecutorProcessSpec; public ContaineredTaskManagerParameters( TaskExecutorProcessSpec taskExecutorProcessSpec, HashMap<String, String> taskManagerEnv) { this.taskExecutorProcessSpec = taskExecutorProcessSpec; this.taskManagerEnv = taskManagerEnv; } // ------------------------------------------------------------------------ public TaskExecutorProcessSpec getTaskExecutorProcessSpec() { return taskExecutorProcessSpec; } public Map<String, String> taskManagerEnv() { return taskManagerEnv; } // ------------------------------------------------------------------------ @Override public String toString() { return "TaskManagerParameters {" + "taskExecutorProcessSpec=" + taskExecutorProcessSpec + ", taskManagerEnv=" + taskManagerEnv + '}'; } // ------------------------------------------------------------------------ // Factory // ------------------------------------------------------------------------ /** * Computes the parameters to be used to start a TaskManager Java process. * * @param config The Flink configuration. * @param taskExecutorProcessSpec The resource specifics of the task executor. * @return The parameters to start the TaskManager processes with. */ public static ContaineredTaskManagerParameters create( Configuration config, TaskExecutorProcessSpec taskExecutorProcessSpec) { // obtain the additional environment variables from the configuration final HashMap<String, String> envVars = new HashMap<>(); final String prefix = ResourceManagerOptions.CONTAINERIZED_TASK_MANAGER_ENV_PREFIX; for (String key : config.keySet()) { if (key.startsWith(prefix) && key.length() > prefix.length()) { // remove prefix String envVarKey = key.substring(prefix.length()); envVars.put(envVarKey, config.getString(key, null)); } } // set JAVA_HOME config.getOptional(CoreOptions.FLINK_JAVA_HOME) .ifPresent(javaHome -> envVars.put(ENV_JAVA_HOME, javaHome)); // done return new ContaineredTaskManagerParameters(taskExecutorProcessSpec, envVars); } }
ContaineredTaskManagerParameters
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/HdfsFileStatus.java
{ "start": 1890, "end": 2035 }
class ____ HdfsFileStatus instances. Note default values for * parameters. */ @InterfaceAudience.Private @InterfaceStability.Unstable
for
java
spring-projects__spring-boot
core/spring-boot-testcontainers/src/test/java/org/springframework/boot/testcontainers/lifecycle/TestcontainersStartupTests.java
{ "start": 1293, "end": 6128 }
class ____ { private static final String PROPERTY = TestcontainersStartup.PROPERTY; private final AtomicInteger counter = new AtomicInteger(); @Test void startSingleStartsOnlyOnce() { TestStartable startable = new TestStartable(); assertThat(startable.startCount).isZero(); TestcontainersStartup.start(startable); assertThat(startable.startCount).isOne(); TestcontainersStartup.start(startable); assertThat(startable.startCount).isOne(); } @Test void startWhenSquentialStartsSequentially() { List<TestStartable> startables = createTestStartables(100); TestcontainersStartup.SEQUENTIAL.start(startables); for (int i = 0; i < startables.size(); i++) { assertThat(startables.get(i).getIndex()).isEqualTo(i); assertThat(startables.get(i).getThreadName()).isEqualTo(Thread.currentThread().getName()); } } @Test void startWhenSquentialStartsOnlyOnce() { List<TestStartable> startables = createTestStartables(10); for (int i = 0; i < startables.size(); i++) { assertThat(startables.get(i).getStartCount()).isZero(); } TestcontainersStartup.SEQUENTIAL.start(startables); for (int i = 0; i < startables.size(); i++) { assertThat(startables.get(i).getStartCount()).isOne(); } TestcontainersStartup.SEQUENTIAL.start(startables); for (int i = 0; i < startables.size(); i++) { assertThat(startables.get(i).getStartCount()).isOne(); } } @Test void startWhenParallelStartsInParallel() { List<TestStartable> startables = createTestStartables(100); TestcontainersStartup.PARALLEL.start(startables); assertThat(startables.stream().map(TestStartable::getThreadName)).hasSizeGreaterThan(1); } @Test void startWhenParallelStartsOnlyOnce() { List<TestStartable> startables = createTestStartables(10); for (int i = 0; i < startables.size(); i++) { assertThat(startables.get(i).getStartCount()).isZero(); } TestcontainersStartup.PARALLEL.start(startables); for (int i = 0; i < startables.size(); i++) { assertThat(startables.get(i).getStartCount()).isOne(); } TestcontainersStartup.PARALLEL.start(startables); for (int i = 0; i < startables.size(); i++) { assertThat(startables.get(i).getStartCount()).isOne(); } } @Test void startWhenParallelStartsDependenciesOnlyOnce() { List<TestStartable> dependencies = createTestStartables(10); TestStartable first = new TestStartable(dependencies); TestStartable second = new TestStartable(dependencies); List<TestStartable> startables = List.of(first, second); assertThat(first.getStartCount()).isZero(); assertThat(second.getStartCount()).isZero(); for (int i = 0; i < startables.size(); i++) { assertThat(dependencies.get(i).getStartCount()).isZero(); } TestcontainersStartup.PARALLEL.start(startables); assertThat(first.getStartCount()).isOne(); assertThat(second.getStartCount()).isOne(); for (int i = 0; i < startables.size(); i++) { assertThat(dependencies.get(i).getStartCount()).isOne(); } TestcontainersStartup.PARALLEL.start(startables); assertThat(first.getStartCount()).isOne(); assertThat(second.getStartCount()).isOne(); for (int i = 0; i < startables.size(); i++) { assertThat(dependencies.get(i).getStartCount()).isOne(); } } @Test void getWhenNoPropertyReturnsDefault() { MockEnvironment environment = new MockEnvironment(); assertThat(TestcontainersStartup.get(environment)).isEqualTo(TestcontainersStartup.SEQUENTIAL); } @Test void getWhenPropertyReturnsBasedOnValue() { MockEnvironment environment = new MockEnvironment(); assertThat(TestcontainersStartup.get(environment.withProperty(PROPERTY, "SEQUENTIAL"))) .isEqualTo(TestcontainersStartup.SEQUENTIAL); assertThat(TestcontainersStartup.get(environment.withProperty(PROPERTY, "sequential"))) .isEqualTo(TestcontainersStartup.SEQUENTIAL); assertThat(TestcontainersStartup.get(environment.withProperty(PROPERTY, "SEQuenTIaL"))) .isEqualTo(TestcontainersStartup.SEQUENTIAL); assertThat(TestcontainersStartup.get(environment.withProperty(PROPERTY, "S-E-Q-U-E-N-T-I-A-L"))) .isEqualTo(TestcontainersStartup.SEQUENTIAL); assertThat(TestcontainersStartup.get(environment.withProperty(PROPERTY, "parallel"))) .isEqualTo(TestcontainersStartup.PARALLEL); } @Test void getWhenUnknownPropertyThrowsException() { MockEnvironment environment = new MockEnvironment(); assertThatIllegalArgumentException() .isThrownBy(() -> TestcontainersStartup.get(environment.withProperty(PROPERTY, "bad"))) .withMessage("Unknown 'spring.testcontainers.beans.startup' property value 'bad'"); } private List<TestStartable> createTestStartables(int size) { List<TestStartable> testStartables = new ArrayList<>(size); for (int i = 0; i < size; i++) { testStartables.add(new TestStartable()); } return testStartables; } private
TestcontainersStartupTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/tableperclass/TablePerClassInheritanceWithAbstractRootTest.java
{ "start": 1329, "end": 5176 }
class ____ { @Test public void basicTest(SessionFactoryScope scope) { final EntityPersister customerDescriptor = scope.getSessionFactory() .getMappingMetamodel() .findEntityDescriptor( Customer.class ); final EntityPersister domesticCustomerDescriptor = scope.getSessionFactory() .getMappingMetamodel() .findEntityDescriptor( DomesticCustomer.class ); final EntityPersister foreignCustomerDescriptor = scope.getSessionFactory() .getMappingMetamodel() .findEntityDescriptor( ForeignCustomer.class ); assert customerDescriptor instanceof UnionSubclassEntityPersister; assert customerDescriptor.isTypeOrSuperType( customerDescriptor ); assert !customerDescriptor.isTypeOrSuperType( domesticCustomerDescriptor ); assert !customerDescriptor.isTypeOrSuperType( foreignCustomerDescriptor ); assert domesticCustomerDescriptor instanceof UnionSubclassEntityPersister; assert domesticCustomerDescriptor.isTypeOrSuperType( customerDescriptor ); assert domesticCustomerDescriptor.isTypeOrSuperType( domesticCustomerDescriptor ); assert !domesticCustomerDescriptor.isTypeOrSuperType( foreignCustomerDescriptor ); assert foreignCustomerDescriptor instanceof UnionSubclassEntityPersister; assert foreignCustomerDescriptor.isTypeOrSuperType( customerDescriptor ); assert !foreignCustomerDescriptor.isTypeOrSuperType( domesticCustomerDescriptor ); assert foreignCustomerDescriptor.isTypeOrSuperType( foreignCustomerDescriptor ); } @Test public void rootQueryExecutionTest(SessionFactoryScope scope) { scope.inTransaction( session -> { { // [name, taxId, vat] final List<Customer> results = session.createQuery( "select c from Customer c", Customer.class ).list(); assertThat( results.size(), is( 2 ) ); for ( Customer result : results ) { if ( result.getId() == 1 ) { assertThat( result, instanceOf( DomesticCustomer.class ) ); final DomesticCustomer customer = (DomesticCustomer) result; assertThat( customer.getName(), is( "domestic" ) ); assertThat( ( customer ).getTaxId(), is( "123" ) ); } else { assertThat( result.getId(), is( 2 ) ); final ForeignCustomer customer = (ForeignCustomer) result; assertThat( customer.getName(), is( "foreign" ) ); assertThat( ( customer ).getVat(), is( "987" ) ); } } } } ); } @Test public void subclassQueryExecutionTest(SessionFactoryScope scope) { scope.inTransaction( session -> { { final DomesticCustomer result = session.createQuery( "select c from DomesticCustomer c", DomesticCustomer.class ).uniqueResult(); assertThat( result, notNullValue() ); assertThat( result.getId(), is( 1 ) ); assertThat( result.getName(), is( "domestic" ) ); assertThat( result.getTaxId(), is( "123" ) ); } { final ForeignCustomer result = session.createQuery( "select c from ForeignCustomer c", ForeignCustomer.class ).uniqueResult(); assertThat( result, notNullValue() ); assertThat( result.getId(), is( 2 ) ); assertThat( result.getName(), is( "foreign" ) ); assertThat( result.getVat(), is( "987" ) ); } } ); } @BeforeEach public void createTestData(SessionFactoryScope scope) { scope.inTransaction( session -> { session.persist( new DomesticCustomer( 1, "domestic", "123" ) ); session.persist( new ForeignCustomer( 2, "foreign", "987" ) ); } ); } @AfterEach public void cleanupTestData(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Entity(name = "Customer") @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public static abstract
TablePerClassInheritanceWithAbstractRootTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/NestedEmbeddedWitnNotOptionalManyToOneTest.java
{ "start": 1945, "end": 2505 }
class ____ { @Id private Integer id; private String name; @Embedded private FirstEmbeddable embeddedAttribute; public TestEntity() { } public TestEntity(Integer id, String name, FirstEmbeddable embeddedAttribute) { this.id = id; this.name = name; this.embeddedAttribute = embeddedAttribute; } public Integer getId() { return id; } public String getName() { return name; } public FirstEmbeddable getEmbeddedAttribute() { return embeddedAttribute; } } @Entity(name = "ChildEntity") public static
TestEntity