language stringclasses 1
value | repo stringclasses 60
values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/common/state/ListStateDescriptorTest.java | {
"start": 1463,
"end": 4834
} | class ____ {
@Test
void testListStateDescriptor() throws Exception {
TypeSerializer<String> serializer =
new KryoSerializer<>(String.class, new SerializerConfigImpl());
ListStateDescriptor<String> descr = new ListStateDescriptor<>("testName", serializer);
assertThat(descr.getName()).isEqualTo("testName");
assertThat(descr.getSerializer()).isNotNull();
assertThat(descr.getSerializer()).isInstanceOf(ListSerializer.class);
assertThat(descr.getElementSerializer()).isNotNull();
assertThat(descr.getElementSerializer()).isEqualTo(serializer);
ListStateDescriptor<String> copy = CommonTestUtils.createCopySerializable(descr);
assertThat(copy.getName()).isEqualTo("testName");
assertThat(copy.getSerializer()).isNotNull();
assertThat(copy.getSerializer()).isInstanceOf(ListSerializer.class);
assertThat(copy.getElementSerializer()).isNotNull();
assertThat(copy.getElementSerializer()).isEqualTo(serializer);
}
@Test
void testHashCodeEquals() throws Exception {
final String name = "testName";
ListStateDescriptor<String> original = new ListStateDescriptor<>(name, String.class);
ListStateDescriptor<String> same = new ListStateDescriptor<>(name, String.class);
ListStateDescriptor<String> sameBySerializer =
new ListStateDescriptor<>(name, StringSerializer.INSTANCE);
// test that hashCode() works on state descriptors with initialized and uninitialized
// serializers
assertThat(same).hasSameHashCodeAs(original);
assertThat(sameBySerializer).hasSameHashCodeAs(original);
assertThat(same).isEqualTo(original);
assertThat(sameBySerializer).isEqualTo(original);
// equality with a clone
ListStateDescriptor<String> clone = CommonTestUtils.createCopySerializable(original);
assertThat(clone).isEqualTo(original);
// equality with an initialized
clone.initializeSerializerUnlessSet(new ExecutionConfig());
assertThat(clone).isEqualTo(original);
original.initializeSerializerUnlessSet(new ExecutionConfig());
assertThat(same).isEqualTo(original);
}
/**
* FLINK-6775.
*
* <p>Tests that the returned serializer is duplicated. This allows to share the state
* descriptor.
*/
@Test
void testSerializerDuplication() {
// we need a serializer that actually duplicates for testing (a stateful one)
// we use Kryo here, because it meets these conditions
TypeSerializer<String> statefulSerializer =
new KryoSerializer<>(String.class, new SerializerConfigImpl());
ListStateDescriptor<String> descr = new ListStateDescriptor<>("foobar", statefulSerializer);
TypeSerializer<String> serializerA = descr.getElementSerializer();
TypeSerializer<String> serializerB = descr.getElementSerializer();
// check that the retrieved serializers are not the same
assertThat(serializerB).isNotSameAs(serializerA);
TypeSerializer<List<String>> listSerializerA = descr.getSerializer();
TypeSerializer<List<String>> listSerializerB = descr.getSerializer();
assertThat(listSerializerB).isNotSameAs(listSerializerA);
}
}
| ListStateDescriptorTest |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/TestContextAnnotationUtils.java | {
"start": 20033,
"end": 22153
} | class ____ an inner class.
Predicate<Class<?>> searchEnclosingClass = ClassUtils::isInnerClass;
NestedTestConfiguration nestedTestConfiguration =
findMergedAnnotation(clazz, NestedTestConfiguration.class, searchEnclosingClass);
return (nestedTestConfiguration != null ? nestedTestConfiguration.value() : getDefaultEnclosingConfigurationMode());
}
private static EnclosingConfiguration getDefaultEnclosingConfigurationMode() {
EnclosingConfiguration defaultConfigurationMode = defaultEnclosingConfigurationMode;
if (defaultConfigurationMode == null) {
String value = SpringProperties.getProperty(NestedTestConfiguration.ENCLOSING_CONFIGURATION_PROPERTY_NAME);
EnclosingConfiguration enclosingConfigurationMode = EnclosingConfiguration.from(value);
defaultConfigurationMode =
(enclosingConfigurationMode != null ? enclosingConfigurationMode : EnclosingConfiguration.INHERIT);
defaultEnclosingConfigurationMode = defaultConfigurationMode;
}
return defaultConfigurationMode;
}
private static void assertNonEmptyAnnotationTypeArray(Class<?>[] annotationTypes, String message) {
if (ObjectUtils.isEmpty(annotationTypes)) {
throw new IllegalArgumentException(message);
}
for (Class<?> clazz : annotationTypes) {
if (!Annotation.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException("Array elements must be of type Annotation");
}
}
}
/**
* Descriptor for an {@link Annotation}, including the {@linkplain
* #getDeclaringClass() class} on which the annotation is <em>declared</em>
* as well as the {@linkplain #getAnnotation() merged annotation} instance.
* <p>If the annotation is used as a meta-annotation, the <em>root declaring
* class</em> is not directly annotated with the annotation but rather
* indirectly via a composed annotation.
* <p>Given the following example, if we are searching for the {@code @Transactional}
* annotation <em>on</em> the {@code TransactionalTests} class, then the
* properties of the {@code AnnotationDescriptor} would be as follows.
* <ul>
* <li>rootDeclaringClass: {@code TransactionalTests} | is |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/CreationTimestampTest.java | {
"start": 613,
"end": 1045
} | class ____ {
@Test
public void test(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
//tag::mapping-generated-CreationTimestamp-persist-example[]
Event dateEvent = new Event();
entityManager.persist(dateEvent);
//end::mapping-generated-CreationTimestamp-persist-example[]
});
}
//tag::mapping-generated-provided-creation-ex1[]
@Entity(name = "Event")
public static | CreationTimestampTest |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/Spr8954Tests.java | {
"start": 3184,
"end": 3283
} | class ____ {
@Bean FooFactoryBean foo() {
return new FooFactoryBean();
}
}
static | FooConfig |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NativeQueryResultTypeAutoDiscoveryTest.java | {
"start": 19547,
"end": 19764
} | class ____ extends TestedEntity<BigDecimal> {
@Column(precision = 50, scale = 15)
public BigDecimal getTestedProperty() {
return testedProperty;
}
}
@Entity(name = "decimalEntity")
public static | NumericEntity |
java | apache__camel | components/camel-paho-mqtt5/src/main/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5Message.java | {
"start": 996,
"end": 1569
} | class ____ extends DefaultMessage {
private transient MqttMessage mqttMessage;
public PahoMqtt5Message(CamelContext camelContext, MqttMessage mqttMessage) {
super(camelContext);
this.mqttMessage = mqttMessage;
}
public MqttMessage getMqttMessage() {
return mqttMessage;
}
public void setMqttMessage(MqttMessage mqttMessage) {
this.mqttMessage = mqttMessage;
}
@Override
public PahoMqtt5Message newInstance() {
return new PahoMqtt5Message(getCamelContext(), mqttMessage);
}
}
| PahoMqtt5Message |
java | apache__flink | flink-core/src/main/java/org/apache/flink/configuration/PipelineOptions.java | {
"start": 1512,
"end": 12456
} | class ____ {
/** The job name used for printing and logging. */
public static final ConfigOption<String> NAME =
key("pipeline.name")
.stringType()
.noDefaultValue()
.withDescription("The job name used for printing and logging.");
/**
* A list of jar files that contain the user-defined function (UDF) classes and all classes used
* from within the UDFs.
*/
public static final ConfigOption<List<String>> JARS =
key("pipeline.jars")
.stringType()
.asList()
.noDefaultValue()
.withDescription(
"A semicolon-separated list of the jars to package with the job jars to be sent to the"
+ " cluster. These have to be valid paths.");
/**
* A list of URLs that are added to the classpath of each user code classloader of the program.
* Paths must specify a protocol (e.g. file://) and be accessible on all nodes
*/
public static final ConfigOption<List<String>> CLASSPATHS =
key("pipeline.classpaths")
.stringType()
.asList()
.noDefaultValue()
.withDescription(
"A semicolon-separated list of the classpaths to package with the job jars to be sent to"
+ " the cluster. These have to be valid URLs.");
public static final ConfigOption<Boolean> AUTO_GENERATE_UIDS =
key("pipeline.auto-generate-uids")
.booleanType()
.defaultValue(true)
.withDescription(
Description.builder()
.text(
"When auto-generated UIDs are disabled, users are forced to manually specify UIDs on DataStream applications.")
.linebreak()
.linebreak()
.text(
"It is highly recommended that users specify UIDs before deploying to"
+ " production since they are used to match state in savepoints to operators"
+ " in a job. Because auto-generated ID's are likely to change when modifying"
+ " a job, specifying custom IDs allow an application to evolve over time"
+ " without discarding state.")
.build());
public static final ConfigOption<Duration> AUTO_WATERMARK_INTERVAL =
key("pipeline.auto-watermark-interval")
.durationType()
.defaultValue(Duration.ofMillis(200))
.withDescription(
"The interval of the automatic watermark emission. Watermarks are used throughout"
+ " the streaming system to keep track of the progress of time. They are used, for example,"
+ " for time based windowing.");
public static final ConfigOption<ClosureCleanerLevel> CLOSURE_CLEANER_LEVEL =
key("pipeline.closure-cleaner-level")
.enumType(ClosureCleanerLevel.class)
.defaultValue(ClosureCleanerLevel.RECURSIVE)
.withDescription("Configures the mode in which the closure cleaner works.");
public static final ConfigOption<Boolean> FORCE_AVRO =
key("pipeline.force-avro")
.booleanType()
.defaultValue(false)
.withDescription(
Description.builder()
.text(
"Forces Flink to use the Apache Avro serializer for POJOs.")
.linebreak()
.linebreak()
.text(
"Important: Make sure to include the %s module.",
code("flink-avro"))
.build());
public static final ConfigOption<Boolean> FORCE_KRYO =
key("pipeline.force-kryo")
.booleanType()
.defaultValue(false)
.withDescription(
"If enabled, forces TypeExtractor to use Kryo serializer for POJOS even though we could"
+ " analyze as POJO. In some cases this might be preferable. For example, when using interfaces"
+ " with subclasses that cannot be analyzed as POJO.");
public static final ConfigOption<Boolean> FORCE_KRYO_AVRO =
key("pipeline.force-kryo-avro")
.booleanType()
.noDefaultValue()
.withDescription(
Description.builder()
.text(
"Forces Flink to register avro classes in kryo serializer.")
.linebreak()
.linebreak()
.text(
"Important: Make sure to include the flink-avro module."
+ " Otherwise, nothing will be registered. For backward compatibility,"
+ " the default value is empty to conform to the behavior of the older version."
+ " That is, always register avro with kryo, and if flink-avro is not in the class"
+ " path, register a dummy serializer. In Flink-2.0, we will set the default value to true.")
.build());
public static final ConfigOption<Boolean> GENERIC_TYPES =
key("pipeline.generic-types")
.booleanType()
.defaultValue(true)
.withDescription(
Description.builder()
.text(
"If the use of generic types is disabled, Flink will throw an %s whenever it encounters"
+ " a data type that would go through Kryo for serialization.",
code("UnsupportedOperationException"))
.linebreak()
.linebreak()
.text(
"Disabling generic types can be helpful to eagerly find and eliminate the use of types"
+ " that would go through Kryo serialization during runtime. Rather than checking types"
+ " individually, using this option will throw exceptions eagerly in the places where generic"
+ " types are used.")
.linebreak()
.linebreak()
.text(
"We recommend to use this option only during development and pre-production"
+ " phases, not during actual production use. The application program and/or the input data may be"
+ " such that new, previously unseen, types occur at some point. In that case, setting this option"
+ " would cause the program to fail.")
.build());
public static final ConfigOption<Map<String, String>> GLOBAL_JOB_PARAMETERS =
key("pipeline.global-job-parameters")
.mapType()
.noDefaultValue()
.withDescription(
"Register a custom, serializable user configuration object. The configuration can be "
+ " accessed in operators");
public static final ConfigOption<Map<String, String>> PARALLELISM_OVERRIDES =
key("pipeline.jobvertex-parallelism-overrides")
.mapType()
.defaultValue(Collections.emptyMap())
.withDescription(
"A parallelism override map (jobVertexId -> parallelism) which will be used to update"
+ " the parallelism of the corresponding job vertices of submitted JobGraphs.");
public static final ConfigOption<Integer> MAX_PARALLELISM =
key("pipeline.max-parallelism")
.intType()
.defaultValue(-1)
.withDescription(
"The program-wide maximum parallelism used for operators which haven't specified a"
+ " maximum parallelism. The maximum parallelism specifies the upper limit for dynamic scaling and"
+ " the number of key groups used for partitioned state."
+ " Changing the value explicitly when recovery from original job will lead to state incompatibility."
+ " Must be less than or equal to 32768.");
public static final ConfigOption<Boolean> OBJECT_REUSE =
key("pipeline.object-reuse")
.booleanType()
.defaultValue(false)
.withDescription(
"When enabled objects that Flink internally uses for deserialization and passing"
+ " data to user-code functions will be reused. Keep in mind that this can lead to bugs when the"
+ " user-code function of an operation is not aware of this behaviour.");
public static final ConfigOption<List<String>> SERIALIZATION_CONFIG =
key("pipeline.serialization-config")
.stringType()
.asList()
.noDefaultValue()
.withDescription(
Description.builder()
.text(
"List of pairs of | PipelineOptions |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TestInstanceFactoryTests.java | {
"start": 27393,
"end": 27769
} | class ____ implements TestInstanceFactory {
@Override
public Object createTestInstance(TestInstanceFactoryContext factoryContext, ExtensionContext extensionContext) {
throw new RuntimeException("boom!");
}
}
/**
* This does not actually create a proxy. Rather, it simulates what
* a proxy-based implementation might do, by loading the | ExplosiveTestInstanceFactory |
java | FasterXML__jackson-core | src/main/java/tools/jackson/core/base/GeneratorBase.java | {
"start": 633,
"end": 17424
} | class ____ extends JsonGenerator
{
public final static int SURR1_FIRST = 0xD800;
public final static int SURR1_LAST = 0xDBFF;
public final static int SURR2_FIRST = 0xDC00;
public final static int SURR2_LAST = 0xDFFF;
// // // Constants for validation messages
protected final static String WRITE_BINARY = "write a binary value";
protected final static String WRITE_BOOLEAN = "write a boolean value";
protected final static String WRITE_NULL = "write a null";
protected final static String WRITE_NUMBER = "write a number";
protected final static String WRITE_RAW = "write a raw (unencoded) value";
protected final static String WRITE_STRING = "write a string";
/**
* This value is the limit of scale allowed for serializing {@link java.math.BigDecimal}
* in "plain" (non-engineering) notation; intent is to prevent asymmetric
* attack whereupon simple eng-notation with big scale is used to generate
* huge "plain" serialization. See [core#315] for details.
*/
protected final static int MAX_BIG_DECIMAL_SCALE = 9999;
/*
/**********************************************************************
/* Default capabilities
/**********************************************************************
*/
/**
* Default set of {@link StreamWriteCapability}ies that may be used as
* basis for format-specific readers (or as bogus instance if non-null
* set needs to be passed).
*/
protected final static JacksonFeatureSet<StreamWriteCapability> DEFAULT_WRITE_CAPABILITIES
= JacksonFeatureSet.fromDefaults(StreamWriteCapability.values());
/**
* Default set of {@link StreamWriteCapability}ies for typical textual formats,
* to use either as-is, or as a base with possible differences.
*/
protected final static JacksonFeatureSet<StreamWriteCapability> DEFAULT_TEXTUAL_WRITE_CAPABILITIES
= DEFAULT_WRITE_CAPABILITIES.with(StreamWriteCapability.CAN_WRITE_FORMATTED_NUMBERS);
/**
* Default set of {@link StreamWriteCapability}ies for typical binary formats,
* to use either as-is, or as a base with possible differences.
*/
protected final static JacksonFeatureSet<StreamWriteCapability> DEFAULT_BINARY_WRITE_CAPABILITIES
= DEFAULT_WRITE_CAPABILITIES.with(StreamWriteCapability.CAN_WRITE_BINARY_NATIVELY);
/*
/**********************************************************************
/* Configuration
/**********************************************************************
*/
/**
* Context object used both to pass some initial settings and to allow
* triggering of Object serialization through generator.
*
* @since 3.0
*/
protected final ObjectWriteContext _objectWriteContext;
/**
* Low-level I/O context used mostly for buffer recycling.
*/
protected final IOContext _ioContext;
/**
* Constraints to use for this generator.
*/
protected final StreamWriteConstraints _streamWriteConstraints;
/**
* Bit flag composed of bits that indicate which
* {@link tools.jackson.core.StreamWriteFeature}s
* are enabled.
*/
protected int _streamWriteFeatures;
/*
/**********************************************************************
/* State
/**********************************************************************
*/
/**
* Flag that indicates whether generator is closed or not. Gets
* set when it is closed by an explicit call
* ({@link #close}).
*/
protected boolean _closed;
/*
/**********************************************************************
/* Life-cycle
/**********************************************************************
*/
protected GeneratorBase(ObjectWriteContext writeCtxt, IOContext ioCtxt,
int streamWriteFeatures) {
super();
_objectWriteContext = writeCtxt;
_ioContext = ioCtxt;
_streamWriteConstraints = ioCtxt.streamWriteConstraints();
_streamWriteFeatures = streamWriteFeatures;
}
/*
/**********************************************************************
/* Configuration access
/**********************************************************************
*/
@Override
public final boolean isEnabled(StreamWriteFeature f) {
return (_streamWriteFeatures & f.getMask()) != 0;
}
@Override
public final int streamWriteFeatures() {
return _streamWriteFeatures;
}
// public int formatWriteFeatures();
@Override
public final JsonGenerator configure(StreamWriteFeature f, boolean state) {
if (state) {
_streamWriteFeatures |= f.getMask();
} else {
_streamWriteFeatures &= ~f.getMask();
}
return this;
}
@Override
public final StreamWriteConstraints streamWriteConstraints() {
return _streamWriteConstraints;
}
@Override
public boolean has(StreamWriteCapability capability) {
return streamWriteCapabilities().isEnabled(capability);
}
/*
/**********************************************************************
/* Public API, accessors
/**********************************************************************
*/
// public Object currentValue();
// public void assignCurrentValue(Object v);
// public TokenStreamContext getOutputContext();
@Override public ObjectWriteContext objectWriteContext() { return _objectWriteContext; }
/**
* Accessor for use by {@code jackson-core} itself (tests in particular).
*
* @return {@link IOContext} in use by this generator
*/
public IOContext ioContext() {
return _ioContext;
}
/*
/**********************************************************************
/* Public API, write methods, structural
/**********************************************************************
*/
//public JsonGenerator writeStartArray()
//public JsonGenerator writeEndArray()
//public JsonGenerator writeStartObject()
//public JsonGenerator writeEndObject()
@Override
public JsonGenerator writeStartArray(Object forValue, int size) throws JacksonException {
return writeStartArray(forValue);
}
@Override
public JsonGenerator writeStartObject(Object forValue, int size) throws JacksonException
{
return writeStartObject(forValue);
}
/*
/**********************************************************************
/* Public API, write methods, textual
/**********************************************************************
*/
@Override
public JsonGenerator writeName(SerializableString name) throws JacksonException {
return writeName(name.getValue());
}
//public abstract JsonGenerator writeString(String text);
//public abstract JsonGenerator writeString(char[] text, int offset, int len);
@Override
public JsonGenerator writeString(Reader reader, int len) throws JacksonException {
// Let's implement this as "unsupported" to make it easier to add new parser impls
return _reportUnsupportedOperation();
}
//public abstract JsonGenerator writeRaw(String text);
//public abstract JsonGenerator writeRaw(char[] text, int offset, int len);
@Override
public JsonGenerator writeString(SerializableString text) throws JacksonException {
return writeString(text.getValue());
}
@Override public JsonGenerator writeRawValue(String text) throws JacksonException {
_verifyValueWrite("write raw value");
return writeRaw(text);
}
@Override public JsonGenerator writeRawValue(String text, int offset, int len) throws JacksonException {
_verifyValueWrite("write raw value");
return writeRaw(text, offset, len);
}
@Override public JsonGenerator writeRawValue(char[] text, int offset, int len) throws JacksonException {
_verifyValueWrite("write raw value");
return writeRaw(text, offset, len);
}
@Override public JsonGenerator writeRawValue(SerializableString text) throws JacksonException {
_verifyValueWrite("write raw value");
return writeRaw(text);
}
@Override
public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength) throws JacksonException {
// Let's implement this as "unsupported" to make it easier to add new parser impls
_reportUnsupportedOperation();
return 0;
}
/*
/**********************************************************************
/* Public API, write methods, primitive
/**********************************************************************
*/
// Not implemented at this level, added as placeholders
/*
public abstract void writeNumber(int i)
public abstract void writeNumber(long l)
public abstract void writeNumber(double d)
public abstract void writeNumber(float f)
public abstract void writeNumber(BigDecimal dec)
public abstract void writeBoolean(boolean state)
public abstract void writeNull()
*/
/*
/**********************************************************************
/* Public API, write methods, POJOs, trees
/**********************************************************************
*/
@Override
public JsonGenerator writePOJO(Object value) throws JacksonException {
if (value == null) {
// important: call method that does check value write:
writeNull();
} else {
// We are NOT to call _verifyValueWrite here, because that will be
// done when actual serialization of POJO occurs. If we did call it,
// state would advance causing exception later on
_objectWriteContext.writeValue(this, value);
}
return this;
}
@Override
public JsonGenerator writeTree(TreeNode rootNode) throws JacksonException {
// As with 'writeObject()', we are not to check if write would work
if (rootNode == null) {
writeNull();
} else {
_objectWriteContext.writeTree(this, rootNode);
}
return this;
}
/*
/**********************************************************************
/* Public API, low-level output handling
/**********************************************************************
*/
// @Override public abstract void flush();
@Override
public boolean isClosed() { return _closed; }
@Override
public void close() {
if (!_closed) {
try {
_closeInput();
} catch (IOException e) {
throw _wrapIOFailure(e);
} finally {
_releaseBuffers();
_ioContext.close();
_closed = true;
}
}
}
/*
/**********************************************************************
/* Package methods for this, sub-classes
/**********************************************************************
*/
protected abstract void _closeInput() throws IOException;
/**
* Method called to release any buffers generator may be holding,
* once generator is being closed.
*/
protected abstract void _releaseBuffers();
/**
* Method called before trying to write a value (scalar or structured),
* to verify that this is legal in current output state, as well as to
* output separators if and as necessary.
*
* @param typeMsg Additional message used for generating exception message
* if value output is NOT legal in current generator output state.
*
* @throws JacksonException if there is a problem in trying to write a value
*/
protected abstract void _verifyValueWrite(String typeMsg) throws JacksonException;
/**
* Overridable factory method called to instantiate an appropriate {@link PrettyPrinter}
* for case of "just use the default one", when default pretty printer handling enabled.
*
* @return Instance of "default" pretty printer to use
*/
protected PrettyPrinter _constructDefaultPrettyPrinter() {
return new DefaultPrettyPrinter();
}
/**
* Helper method used to serialize a {@link java.math.BigDecimal} as a String,
* for serialization, taking into account configuration settings
*
* @param value BigDecimal value to convert to String
*
* @return String representation of {@code value}
*
* @throws JacksonException if there is a problem serializing value as String
*/
protected String _asString(BigDecimal value) throws JacksonException {
if (StreamWriteFeature.WRITE_BIGDECIMAL_AS_PLAIN.enabledIn(_streamWriteFeatures)) {
// 24-Aug-2016, tatu: [core#315] prevent possible DoS vector
int scale = value.scale();
if ((scale < -MAX_BIG_DECIMAL_SCALE) || (scale > MAX_BIG_DECIMAL_SCALE)) {
_reportError(String.format(
"Attempt to write plain `java.math.BigDecimal` (see JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN) with illegal scale (%d): needs to be between [-%d, %d]",
scale, MAX_BIG_DECIMAL_SCALE, MAX_BIG_DECIMAL_SCALE));
}
return value.toPlainString();
}
return value.toString();
}
/*
/**********************************************************************
/* UTF-8 related helper method(s)
/**********************************************************************
*/
protected final int _decodeSurrogate(int surr1, int surr2) throws JacksonException
{
// First is known to be valid, but how about the other?
if (surr2 < SURR2_FIRST || surr2 > SURR2_LAST) {
String msg = String.format(
"Incomplete surrogate pair: first char 0x%04X, second 0x%04X", surr1, surr2);
_reportError(msg);
}
return (surr1 << 10) + surr2 + UTF8Writer.SURROGATE_BASE;
}
/*
/**********************************************************************
/* Helper methods: input parameter validation
/**********************************************************************
*/
protected void _checkRangeBoundsForByteArray(byte[] data, int offset, int len)
throws JacksonException
{
if (data == null) {
_reportArgumentError("Invalid `byte[]` argument: `null`");
}
final int dataLen = data.length;
final int end = offset+len;
// Note: we are checking that:
//
// !(offset < 0)
// !(len < 0)
// !((offset + len) < 0) // int overflow!
// !((offset + len) > dataLen) == !((datalen - (offset+len)) < 0)
// All can be optimized by OR'ing and checking for negative:
int anyNegs = offset | len | end | (dataLen - end);
if (anyNegs < 0) {
_reportArgumentError(String.format(
"Invalid 'offset' (%d) and/or 'len' (%d) arguments for `byte[]` of length %d",
offset, len, dataLen));
}
}
protected void _checkRangeBoundsForCharArray(char[] data, int offset, int len)
throws JacksonException
{
if (data == null) {
_reportArgumentError("Invalid `char[]` argument: `null`");
}
final int dataLen = data.length;
final int end = offset+len;
// Note: we are checking same things as with other bounds-checks
int anyNegs = offset | len | end | (dataLen - end);
if (anyNegs < 0) {
_reportArgumentError(String.format(
"Invalid 'offset' (%d) and/or 'len' (%d) arguments for `char[]` of length %d",
offset, len, dataLen));
}
}
protected void _checkRangeBoundsForString(String data, int offset, int len)
throws JacksonException
{
if (data == null) {
_reportArgumentError("Invalid `String` argument: `null`");
}
final int dataLen = data.length();
final int end = offset+len;
// Note: we are checking same things as with other bounds-checks
int anyNegs = offset | len | end | (dataLen - end);
if (anyNegs < 0) {
_reportArgumentError(String.format(
"Invalid 'offset' (%d) and/or 'len' (%d) arguments for `String` of length %d",
offset, len, dataLen));
}
}
/*
/**********************************************************************
/* Helper methods: error reporting
/**********************************************************************
*/
protected void _throwInternal() { VersionUtil.throwInternal(); }
}
| GeneratorBase |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/data/DoubleArrayBlock.java | {
"start": 871,
"end": 8334
} | class ____ extends AbstractArrayBlock implements DoubleBlock {
static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(DoubleArrayBlock.class);
private final DoubleArrayVector vector;
DoubleArrayBlock(
double[] values,
int positionCount,
int[] firstValueIndexes,
BitSet nulls,
MvOrdering mvOrdering,
BlockFactory blockFactory
) {
this(
new DoubleArrayVector(values, firstValueIndexes == null ? positionCount : firstValueIndexes[positionCount], blockFactory),
positionCount,
firstValueIndexes,
nulls,
mvOrdering
);
}
private DoubleArrayBlock(
DoubleArrayVector vector, // stylecheck
int positionCount,
int[] firstValueIndexes,
BitSet nulls,
MvOrdering mvOrdering
) {
super(positionCount, firstValueIndexes, nulls, mvOrdering);
this.vector = vector;
assert firstValueIndexes == null
? vector.getPositionCount() == getPositionCount()
: firstValueIndexes[getPositionCount()] == vector.getPositionCount();
}
static DoubleArrayBlock readArrayBlock(BlockFactory blockFactory, BlockStreamInput in) throws IOException {
final SubFields sub = new SubFields(blockFactory, in);
DoubleArrayVector vector = null;
boolean success = false;
try {
vector = DoubleArrayVector.readArrayVector(sub.vectorPositions(), in, blockFactory);
var block = new DoubleArrayBlock(vector, sub.positionCount, sub.firstValueIndexes, sub.nullsMask, sub.mvOrdering);
blockFactory.adjustBreaker(block.ramBytesUsed() - vector.ramBytesUsed() - sub.bytesReserved);
success = true;
return block;
} finally {
if (success == false) {
Releasables.close(vector);
blockFactory.adjustBreaker(-sub.bytesReserved);
}
}
}
void writeArrayBlock(StreamOutput out) throws IOException {
writeSubFields(out);
vector.writeArrayVector(vector.getPositionCount(), out);
}
@Override
public DoubleVector asVector() {
return null;
}
@Override
public double getDouble(int valueIndex) {
return vector.getDouble(valueIndex);
}
@Override
public DoubleBlock filter(int... positions) {
try (var builder = blockFactory().newDoubleBlockBuilder(positions.length)) {
for (int pos : positions) {
if (isNull(pos)) {
builder.appendNull();
continue;
}
int valueCount = getValueCount(pos);
int first = getFirstValueIndex(pos);
if (valueCount == 1) {
builder.appendDouble(getDouble(first));
} else {
builder.beginPositionEntry();
for (int c = 0; c < valueCount; c++) {
builder.appendDouble(getDouble(first + c));
}
builder.endPositionEntry();
}
}
return builder.mvOrdering(mvOrdering()).build();
}
}
@Override
public DoubleBlock keepMask(BooleanVector mask) {
if (getPositionCount() == 0) {
incRef();
return this;
}
if (mask.isConstant()) {
if (mask.getBoolean(0)) {
incRef();
return this;
}
return (DoubleBlock) blockFactory().newConstantNullBlock(getPositionCount());
}
try (DoubleBlock.Builder builder = blockFactory().newDoubleBlockBuilder(getPositionCount())) {
// TODO if X-ArrayBlock used BooleanVector for it's null mask then we could shuffle references here.
for (int p = 0; p < getPositionCount(); p++) {
if (false == mask.getBoolean(p)) {
builder.appendNull();
continue;
}
int valueCount = getValueCount(p);
if (valueCount == 0) {
builder.appendNull();
continue;
}
int start = getFirstValueIndex(p);
if (valueCount == 1) {
builder.appendDouble(getDouble(start));
continue;
}
int end = start + valueCount;
builder.beginPositionEntry();
for (int i = start; i < end; i++) {
builder.appendDouble(getDouble(i));
}
builder.endPositionEntry();
}
return builder.build();
}
}
@Override
public ReleasableIterator<DoubleBlock> lookup(IntBlock positions, ByteSizeValue targetBlockSize) {
return new DoubleLookup(this, positions, targetBlockSize);
}
@Override
public ElementType elementType() {
return ElementType.DOUBLE;
}
@Override
public DoubleBlock expand() {
if (firstValueIndexes == null) {
incRef();
return this;
}
if (nullsMask == null) {
vector.incRef();
return vector.asBlock();
}
// The following line is correct because positions with multi-values are never null.
int expandedPositionCount = vector.getPositionCount();
long bitSetRamUsedEstimate = Math.max(nullsMask.size(), BlockRamUsageEstimator.sizeOfBitSet(expandedPositionCount));
blockFactory().adjustBreaker(bitSetRamUsedEstimate);
DoubleArrayBlock expanded = new DoubleArrayBlock(
vector,
expandedPositionCount,
null,
shiftNullsToExpandedPositions(),
MvOrdering.DEDUPLICATED_AND_SORTED_ASCENDING
);
blockFactory().adjustBreaker(expanded.ramBytesUsedOnlyBlock() - bitSetRamUsedEstimate);
// We need to incRef after adjusting any breakers, otherwise we might leak the vector if the breaker trips.
vector.incRef();
return expanded;
}
private long ramBytesUsedOnlyBlock() {
return BASE_RAM_BYTES_USED + BlockRamUsageEstimator.sizeOf(firstValueIndexes) + BlockRamUsageEstimator.sizeOfBitSet(nullsMask);
}
@Override
public long ramBytesUsed() {
return ramBytesUsedOnlyBlock() + vector.ramBytesUsed();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof DoubleBlock that) {
return DoubleBlock.equals(this, that);
}
return false;
}
@Override
public int hashCode() {
return DoubleBlock.hash(this);
}
@Override
public String toString() {
return getClass().getSimpleName()
+ "[positions="
+ getPositionCount()
+ ", mvOrdering="
+ mvOrdering()
+ ", vector="
+ vector
+ ']';
}
@Override
public void allowPassingToDifferentDriver() {
vector.allowPassingToDifferentDriver();
}
@Override
public BlockFactory blockFactory() {
return vector.blockFactory();
}
@Override
public void closeInternal() {
blockFactory().adjustBreaker(-ramBytesUsedOnlyBlock());
Releasables.closeExpectNoException(vector);
}
}
| DoubleArrayBlock |
java | junit-team__junit5 | junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/discovery/predicates/TestClassPredicates.java | {
"start": 1850,
"end": 1956
} | class ____ a JUnit Jupiter test class.
*
* @since 5.13
*/
@API(status = INTERNAL, since = "5.13")
public | is |
java | quarkusio__quarkus | extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/management/ManagementWithJksTest.java | {
"start": 2931,
"end": 3690
} | class ____ implements Handler<RoutingContext> {
@Override
public void handle(RoutingContext rc) {
Assertions.assertThat(rc.request().connection().isSsl()).isTrue();
Assertions.assertThat(rc.request().isSSL()).isTrue();
Assertions.assertThat(rc.request().connection().sslSession()).isNotNull();
rc.response().end("ssl");
}
}
@Test
public void testSslWithJks() {
RestAssured.given()
.trustStore(new File("target/certs/ssl-management-interface-test-truststore.jks"), "secret")
.get("https://localhost:9001/management/my-route")
.then().statusCode(200).body(Matchers.equalTo("ssl"));
}
@Singleton
static | MyHandler |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_3600/Issue3682.java | {
"start": 397,
"end": 1392
} | class ____ {
@JSONField(name = "/")
private String hash;
}
static final String SOURCE = "{\n" +
" \"jsonrpc\": \"2.0\",\n" +
" \"result\": {\n" +
" \"Version\": 0,\n" +
" \"To\": \"t1iceld4fv44xgjqfcx5lwz45pubheu3c7c2nmlua\",\n" +
" \"From\": \"t152xual7ze57jnnioucuv4lmtxarewtzhkqojboy\",\n" +
" \"Nonce\": 4,\n" +
" \"Value\": \"9999999938462317355\",\n" +
" \"GasLimit\": 609960,\n" +
" \"GasFeeCap\": \"101083\",\n" +
" \"GasPremium\": \"100029\",\n" +
" \"Method\": 0,\n" +
" \"Params\": null,\n" +
" \"CID\": {\n" +
" \"/\": \"bafy2bzacedgpr5pmkvu4rkq26uv4hidpfrn3gdvtgkp3hpxss3bgmodrgqtk6\"\n" +
" }\n" +
" },\n" +
" \"id\": 1\n" +
"}";
}
| Cid |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/enrich/EnrichPolicy.java | {
"start": 11524,
"end": 15032
} | class ____ implements Writeable, ToXContentFragment {
static final ParseField NAME = new ParseField("name");
@SuppressWarnings("unchecked")
static final ConstructingObjectParser<NamedPolicy, String> PARSER = new ConstructingObjectParser<>(
"named_policy",
false,
(args, policyType) -> new NamedPolicy(
(String) args[0],
new EnrichPolicy(
policyType,
(QuerySource) args[1],
(List<String>) args[2],
(String) args[3],
(List<String>) args[4],
(String) args[5]
)
)
);
static {
PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME);
declareCommonConstructorParsingOptions(PARSER);
}
private final String name;
private final EnrichPolicy policy;
public NamedPolicy(String name, EnrichPolicy policy) {
this.name = name;
this.policy = policy;
}
public NamedPolicy(StreamInput in) throws IOException {
name = in.readString();
policy = new EnrichPolicy(in);
}
public String getName() {
return name;
}
public EnrichPolicy getPolicy() {
return policy;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
policy.writeTo(out);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(policy.type);
{
builder.field(NAME.getPreferredName(), name);
policy.toInnerXContent(builder, params);
}
builder.endObject();
return builder;
}
public static NamedPolicy fromXContent(XContentParser parser) throws IOException {
Token token = parser.currentToken();
if (token != Token.START_OBJECT) {
token = parser.nextToken();
}
if (token != Token.START_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "unexpected token");
}
token = parser.nextToken();
if (token != Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "unexpected token");
}
String policyType = parser.currentName();
token = parser.nextToken();
if (token != Token.START_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "unexpected token");
}
NamedPolicy policy = PARSER.parse(parser, policyType);
token = parser.nextToken();
if (token != Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "unexpected token");
}
return policy;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NamedPolicy that = (NamedPolicy) o;
return name.equals(that.name) && policy.equals(that.policy);
}
@Override
public int hashCode() {
return Objects.hash(name, policy);
}
}
}
| NamedPolicy |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/builder/RouteTemplateStreamCacheTest.java | {
"start": 1100,
"end": 2464
} | class ____ {
@Test
public void testRouteTemplateStreamCache() throws Exception {
try (DefaultCamelContext context = new DefaultCamelContext()) {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
routeTemplate("myTemplate")
.templateParameter("foo")
.templateParameter("bar")
.templateParameter("mask")
.route()
.noStreamCaching()
.messageHistory()
.logMask("{{mask}}")
.from("direct:{{foo}}")
.to("mock:{{bar}}");
}
});
context.addRouteFromTemplate("myId", "myTemplate", mapOf("foo", "start", "bar", "result", "mask", "true"));
context.start();
assertThat(context.getRoutes()).allSatisfy(r -> {
assertThat(r).isInstanceOfSatisfying(DefaultRoute.class, dr -> {
assertThat(dr.isStreamCaching()).isFalse();
assertThat(dr.isMessageHistory()).isTrue();
assertThat(dr.isLogMask()).isTrue();
});
});
}
}
}
| RouteTemplateStreamCacheTest |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/util/context/Context5Test.java | {
"start": 1054,
"end": 10441
} | class ____ {
Context5 c = new Context5(1, "A", 2, "B", 3, "C",
4, "D", 5, "E");
@Test
public void replaceKey1NewContext() throws Exception {
Context put = c.put(1, "foo");
assertThat(put)
.isInstanceOf(Context5.class)
.isNotSameAs(c);
assertThat(put.stream().map(Map.Entry::getKey))
.containsExactly(1, 2, 3, 4, 5);
assertThat(put.stream().map(Map.Entry::getValue))
.containsExactly("foo", "B", "C", "D", "E");
}
@Test
public void replaceKey2NewContext() {
Context put = c.put(2, "foo");
assertThat(put)
.isInstanceOf(Context5.class)
.isNotSameAs(c);
assertThat(put.stream().map(Map.Entry::getKey))
.containsExactly(1, 2, 3, 4, 5);
assertThat(put.stream().map(Map.Entry::getValue))
.containsExactly("A", "foo", "C", "D", "E");
}
@Test
public void replaceKey3NewContext() {
Context put = c.put(3, "foo");
assertThat(put)
.isInstanceOf(Context5.class)
.isNotSameAs(c);
assertThat(put.stream().map(Map.Entry::getKey))
.containsExactly(1, 2, 3, 4, 5);
assertThat(put.stream().map(Map.Entry::getValue))
.containsExactly("A", "B", "foo", "D", "E");
}
@Test
public void replaceKey4NewContext() {
Context put = c.put(4, "foo");
assertThat(put)
.isInstanceOf(Context5.class)
.isNotSameAs(c);
assertThat(put.stream().map(Map.Entry::getKey))
.containsExactly(1, 2, 3, 4, 5);
assertThat(put.stream().map(Map.Entry::getValue))
.containsExactly("A", "B", "C", "foo", "E");
}
@Test
public void replaceKey5NewContext() {
Context put = c.put(5, "foo");
assertThat(put)
.isInstanceOf(Context5.class)
.isNotSameAs(c);
assertThat(put.stream().map(Map.Entry::getKey))
.containsExactly(1, 2, 3, 4, 5);
assertThat(put.stream().map(Map.Entry::getValue))
.containsExactly("A", "B", "C", "D", "foo");
}
@Test
public void putDifferentKeyContextN() throws Exception {
Context put = c.put(6, "Abis");
assertThat(put)
.isInstanceOf(ContextN.class);
assertThat(put.stream().map(Map.Entry::getKey))
.containsExactly(1, 2, 3, 4, 5, 6);
assertThat(put.stream().map(Map.Entry::getValue))
.containsExactly("A", "B", "C", "D", "E", "Abis");
}
@Test
public void hasKey() throws Exception {
assertThat(c.hasKey(1)).as("hasKey(1)").isTrue();
assertThat(c.hasKey(2)).as("hasKey(2)").isTrue();
assertThat(c.hasKey(3)).as("hasKey(3)").isTrue();
assertThat(c.hasKey(4)).as("hasKey(4)").isTrue();
assertThat(c.hasKey(5)).as("hasKey(5)").isTrue();
assertThat(c.hasKey(6)).as("hasKey(6)").isFalse();
}
@Test
public void removeKeys() {
assertThat(c.delete(1))
.as("delete(1)")
.isInstanceOf(Context4.class)
.has(keyValue(2, "B"))
.has(keyValue(3, "C"))
.has(keyValue(4, "D"))
.has(keyValue(5, "E"))
.doesNotHave(key(1));
assertThat(c.delete(2))
.as("delete(2)")
.isInstanceOf(Context4.class)
.has(keyValue(1, "A"))
.has(keyValue(3, "C"))
.has(keyValue(4, "D"))
.has(keyValue(5, "E"))
.doesNotHave(key(2));
assertThat(c.delete(3))
.as("delete(3)")
.isInstanceOf(Context4.class)
.has(keyValue(1, "A"))
.has(keyValue(2, "B"))
.has(keyValue(4, "D"))
.has(keyValue(5, "E"))
.doesNotHave(key(3));
assertThat(c.delete(4))
.as("delete(4)")
.isInstanceOf(Context4.class)
.has(keyValue(1, "A"))
.has(keyValue(2, "B"))
.has(keyValue(3, "C"))
.has(keyValue(5, "E"))
.doesNotHave(key(4));
assertThat(c.delete(5))
.as("delete(5)")
.isInstanceOf(Context4.class)
.has(keyValue(1, "A"))
.has(keyValue(2, "B"))
.has(keyValue(3, "C"))
.has(keyValue(4, "D"))
.doesNotHave(key(5));
assertThat(c.delete(6)).isSameAs(c);
}
@Test
public void get() {
assertThat((String) c.get(1)).isEqualTo("A");
assertThat((String) c.get(2)).isEqualTo("B");
assertThat((String) c.get(3)).isEqualTo("C");
assertThat((String) c.get(4)).isEqualTo("D");
assertThat((String) c.get(5)).isEqualTo("E");
}
@Test
public void getUnknown() throws Exception {
assertThatExceptionOfType(NoSuchElementException.class)
.isThrownBy(() -> c.get(6))
.withMessage("Context does not contain key: 6");
}
@Test
public void getUnknownWithDefault() throws Exception {
assertThat(c.getOrDefault("peeka", "boo")).isEqualTo("boo");
}
@Test
public void getUnknownWithDefaultNull() throws Exception {
Object def = null;
assertThat(c.getOrDefault("peeka", def)).isNull();
}
@Test
public void stream() throws Exception {
assertThat(c.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)))
.hasSize(5)
.containsOnlyKeys(1, 2, 3, 4, 5)
.containsValues("A", "B", "C", "D", "E");
}
@Test
void forEach() {
Map<Object, Object> items = new HashMap<>();
c.forEach(items::put);
assertThat(items)
.hasSize(5)
.containsEntry(1, "A")
.containsEntry(2, "B")
.containsEntry(3, "C")
.containsEntry(4, "D")
.containsEntry(5, "E");
}
@Test
void forEachThrows() {
Map<Object, Object> items = new HashMap<>();
BiConsumer<Object, Object> action = (key, value) -> {
if (key.equals(2)) {
throw new RuntimeException("Boom!");
}
items.put(key, value);
};
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> c.forEach(action))
.withMessage("Boom!");
assertThat(items)
.hasSize(1)
.containsOnlyKeys(1)
.containsValues("A");
}
@Test
public void string() throws Exception {
assertThat(c.toString()).isEqualTo("Context5{1=A, 2=B, 3=C, 4=D, 5=E}");
}
@Test
public void ofApi() {
Date d = new Date();
assertThat(Context.of("test", 12, "value", true,
123, 456L, true, false, d, "today"))
.isInstanceOf(Context5.class)
.hasToString("Context5{test=12, value=true, 123=456, true=false, " + d + "=today}");
}
@Test
public void putAllOf() {
Context m = Context.of("A", 1, "B", 2, "C", 3);
Context put = c.putAll(m.readOnly());
assertThat(put).isInstanceOf(ContextN.class);
assertThat(put.stream().map(Map.Entry::getKey))
.containsExactlyInAnyOrder(1, 2, 3, 4, 5, "A", "B", "C");
}
@Test
public void putAllReplaces() {
Context m = Context.of(c.key1, "replaced", "A", 1);
Context put = c.putAll(m.readOnly());
assertThat(put).isInstanceOf(ContextN.class)
.hasToString("ContextN{1=replaced, 2=B, 3=C, 4=D, 5=E, A=1}");
}
@Test
public void putAllOfEmpty() {
Context m = Context.empty();
Context put = c.putAll(m.readOnly());
assertThat(put).isSameAs(c);
}
@Test
public void putNonNullWithNull() {
Context put = c.putNonNull("putNonNull", null);
assertThat(put).isSameAs(c);
}
@Test
public void putNonNullWithValue() {
Context put = c.putNonNull("putNonNull", "value");
assertThat(put.getOrEmpty("putNonNull")).contains("value");
}
@Test
public void size() {
assertThat(c.size()).isEqualTo(5);
}
@Test
public void putAllSelfIntoEmpty() {
CoreContext initial = new Context0();
Context result = ((CoreContext) c).putAllInto(initial);
assertThat(result).isNotSameAs(initial)
.isNotSameAs(c);
assertThat(result.stream()).containsExactlyElementsOf(c.stream().collect(Collectors.toList()));
}
@Test
public void putAllSelfIntoContextN() {
CoreContext initial = new ContextN(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6);
Context5 self = new Context5("A", 1, "B", 2, "C", 3, "D", 4, "E", 5);
Context result = self.putAllInto(initial);
assertThat(result).isNotSameAs(initial)
.isNotSameAs(c);
assertThat(result.stream().map(String::valueOf))
.containsExactly("1=1", "2=2", "3=3", "4=4", "5=5", "6=6", "A=1", "B=2", "C=3", "D=4", "E=5");
}
@Test
public void unsafePutAllIntoShouldReplace() {
ContextN ctx = new ContextN(Collections.emptyMap());
ctx.accept(1, "VALUE1");
ctx.accept(2, "VALUE2");
ctx.accept(3, "VALUE3");
ctx.accept(4, "VALUE4");
ctx.accept(5, "VALUE5");
ctx.accept("extra", "value");
Context5 self = new Context5(1, "REPLACED1", 2, "REPLACED2",
3, "REPLACED3", 4, "REPLACED4", 5, "REPLACED5");
self.unsafePutAllInto(ctx);
assertThat(ctx)
.containsEntry(1, "REPLACED1")
.containsEntry(2, "REPLACED2")
.containsEntry(3, "REPLACED3")
.containsEntry(4, "REPLACED4")
.containsEntry(5, "REPLACED5")
.containsEntry("extra", "value")
.hasSize(6);
}
@Test
void putAllMap() {
Map<Object, Object> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
Context put = c.putAllMap(map);
assertThat(put).isInstanceOf(ContextN.class)
.hasToString("ContextN{1=A, 2=B, 3=C, 4=D, 5=E, A=1, B=2, C=3}");
}
@Test
void putAllMapEmpty() {
Context put = c.putAllMap(Collections.emptyMap());
assertThat(put).isSameAs(c);
}
@Test
void putAllMapNullKey() {
assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> c.putAllMap(Collections.singletonMap(null, "oops")));
}
@Test
void putAllMapNullValue() {
assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> c.putAllMap(Collections.singletonMap("A", null)));
}
@Test
void putAllMapReplaces() {
Map<Object, Object> map = new HashMap<>();
map.put(c.key1, "replaced");
map.put("A", 1);
Context put = c.putAllMap(map);
assertThat(put).isInstanceOf(ContextN.class)
.hasToString("ContextN{1=replaced, 2=B, 3=C, 4=D, 5=E, A=1}");
}
}
| Context5Test |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/ordered/OrderByTest.java | {
"start": 940,
"end": 3582
} | class ____ {
@AfterEach
public void tearDonw(SessionFactoryScope scope){
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
@SuppressWarnings("unchecked")
public void testOrderBy(SessionFactoryScope scope) {
scope.inTransaction(
sess -> {
Search s = new Search( "Hibernate" );
s.getSearchResults().add( "jboss.com" );
s.getSearchResults().add( "hibernate.org" );
s.getSearchResults().add( "HiA" );
sess.persist( s );
sess.flush();
sess.clear();
CriteriaBuilder criteriaBuilder = sess.getCriteriaBuilder();
CriteriaQuery<Search> criteria = criteriaBuilder.createQuery( Search.class );
criteria.from( Search.class );
s = sess.createQuery( criteria ).uniqueResult();
// s = (Search) sess.createCriteria( Search.class ).uniqueResult();
assertFalse( Hibernate.isInitialized( s.getSearchResults() ) );
Iterator iter = s.getSearchResults().iterator();
assertThat( iter.next(), is( "HiA" ) );
assertThat( iter.next(), is( "hibernate.org" ) );
assertThat( iter.next(), is( "jboss.com" ) );
assertFalse( iter.hasNext() );
sess.clear();
criteria = criteriaBuilder.createQuery( Search.class );
criteria.from( Search.class ).fetch( "searchResults", JoinType.LEFT );
s = sess.createQuery( criteria ).uniqueResult();
// s = (Search) sess.createCriteria( Search.class )
// .setFetchMode( "searchResults", FetchMode.JOIN )
// .uniqueResult();
assertTrue( Hibernate.isInitialized( s.getSearchResults() ) );
iter = s.getSearchResults().iterator();
assertThat( iter.next(), is( "HiA" ) );
assertThat( iter.next(), is( "hibernate.org" ) );
assertThat( iter.next(), is( "jboss.com" ) );
assertFalse( iter.hasNext() );
sess.clear();
s = (Search) sess.createQuery( "from Search s left join fetch s.searchResults" )
.uniqueResult();
assertTrue( Hibernate.isInitialized( s.getSearchResults() ) );
iter = s.getSearchResults().iterator();
assertThat( iter.next(), is( "HiA" ) );
assertThat( iter.next(), is( "hibernate.org" ) );
assertThat( iter.next(), is( "jboss.com" ) );
assertFalse( iter.hasNext() );
/*sess.clear();
s = (Search) sess.createCriteria(Search.class).uniqueResult();
assertFalse( Hibernate.isInitialized( s.getSearchResults() ) );
iter = sess.createFilter( s.getSearchResults(), "").iterate();
assertEquals( iter.next(), "HiA" );
assertEquals( iter.next(), "hibernate.org" );
assertEquals( iter.next(), "jboss.com" );
assertFalse( iter.hasNext() );*/
sess.remove( s );
}
);
}
}
| OrderByTest |
java | apache__logging-log4j2 | log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/ThreadLocalVsPoolBenchmark.java | {
"start": 4160,
"end": 4421
} | class ____ extends StringBuilderPool {
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int MPMC_REQUIRED_MIN_CAPACITY = 2;
// Putting the under-provisioned instance to a wrapper | JcPool |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/java/ClosureCleanerTest.java | {
"start": 11267,
"end": 11734
} | class ____ implements MapCreator, Serializable {
private int add = 0;
SerializableMapCreator(int add) {
this.add = add;
}
@Override
public MapFunction<Integer, Integer> getMap() {
return new MapFunction<Integer, Integer>() {
@Override
public Integer map(Integer value) throws Exception {
return value + add;
}
};
}
}
@SuppressWarnings("serial")
| SerializableMapCreator |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/domain/misc/CustomBeanWrapperFactory.java | {
"start": 916,
"end": 1232
} | class ____ implements ObjectWrapperFactory {
@Override
public boolean hasWrapperFor(Object object) {
return object instanceof Author;
}
@Override
public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
return new CustomBeanWrapper(metaObject, object);
}
}
| CustomBeanWrapperFactory |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_2164/Issue2164Mapper.java | {
"start": 362,
"end": 680
} | interface ____ {
Issue2164Mapper INSTANCE = Mappers.getMapper( Issue2164Mapper.class );
@Mapping(target = "value", qualifiedByName = "truncate2")
Target map(BigDecimal value);
@Named( "truncate2" )
default String truncate2(String in) {
return in.substring( 0, 2 );
}
| Issue2164Mapper |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/BasicTestEntity1.java | {
"start": 371,
"end": 1739
} | class ____ {
@Id
@GeneratedValue
private Integer id;
@Audited
private String str1;
@Audited
private long long1;
public BasicTestEntity1() {
}
public BasicTestEntity1(String str1, long long1) {
this.str1 = str1;
this.long1 = long1;
}
public BasicTestEntity1(Integer id, String str1, long long1) {
this.id = id;
this.str1 = str1;
this.long1 = long1;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStr1() {
return str1;
}
public void setStr1(String str1) {
this.str1 = str1;
}
public long getLong1() {
return long1;
}
public void setLong1(long long1) {
this.long1 = long1;
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof BasicTestEntity1) ) {
return false;
}
BasicTestEntity1 that = (BasicTestEntity1) o;
if ( long1 != that.long1 ) {
return false;
}
if ( id != null ? !id.equals( that.id ) : that.id != null ) {
return false;
}
if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) {
return false;
}
return true;
}
public int hashCode() {
int result;
result = (id != null ? id.hashCode() : 0);
result = 31 * result + (str1 != null ? str1.hashCode() : 0);
result = 31 * result + (int) (long1 ^ (long1 >>> 32));
return result;
}
}
| BasicTestEntity1 |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NetworkTopologyServlet.java | {
"start": 1797,
"end": 6252
} | class ____ extends DfsServlet {
public static final String SERVLET_NAME = "topology";
public static final String PATH_SPEC = "/topology";
protected static final String FORMAT_JSON = "json";
protected static final String FORMAT_TEXT = "text";
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
final ServletContext context = getServletContext();
String format = parseAcceptHeader(request);
if (FORMAT_TEXT.equals(format)) {
response.setContentType("text/plain; charset=UTF-8");
} else if (FORMAT_JSON.equals(format)) {
response.setContentType("application/json; charset=UTF-8");
}
NameNode nn = NameNodeHttpServer.getNameNodeFromContext(context);
BlockManager bm = nn.getNamesystem().getBlockManager();
List<Node> leaves = bm.getDatanodeManager().getNetworkTopology()
.getLeaves(NodeBase.ROOT);
try (PrintStream out = new PrintStream(
response.getOutputStream(), false, "UTF-8")) {
printTopology(out, leaves, format);
} catch (Throwable t) {
String errMsg = "Print network topology failed. "
+ StringUtils.stringifyException(t);
response.sendError(HttpServletResponse.SC_GONE, errMsg);
throw new IOException(errMsg);
} finally {
response.getOutputStream().close();
}
}
/**
* Display each rack and the nodes assigned to that rack, as determined
* by the NameNode, in a hierarchical manner. The nodes and racks are
* sorted alphabetically.
*
* @param stream print stream
* @param leaves leaves nodes under base scope
* @param format the response format
*/
protected void printTopology(PrintStream stream, List<Node> leaves,
String format) throws BadFormatException, IOException {
if (leaves.isEmpty()) {
stream.print("No DataNodes");
return;
}
// Build a map of rack -> nodes
Map<String, TreeSet<String>> tree = new HashMap<>();
for(Node dni : leaves) {
String location = dni.getNetworkLocation();
String name = dni.getName();
tree.putIfAbsent(location, new TreeSet<>());
tree.get(location).add(name);
}
// Sort the racks (and nodes) alphabetically, display in order
ArrayList<String> racks = new ArrayList<>(tree.keySet());
Collections.sort(racks);
if (FORMAT_JSON.equals(format)) {
printJsonFormat(stream, tree, racks);
} else if (FORMAT_TEXT.equals(format)) {
printTextFormat(stream, tree, racks);
} else {
throw new BadFormatException("Bad format: " + format);
}
}
protected void printJsonFormat(PrintStream stream, Map<String,
TreeSet<String>> tree, ArrayList<String> racks) throws IOException {
JsonFactory dumpFactory = new JsonFactory();
JsonGenerator dumpGenerator = dumpFactory.createGenerator(stream);
dumpGenerator.writeStartArray();
for(String r : racks) {
dumpGenerator.writeStartObject();
dumpGenerator.writeFieldName(r);
TreeSet<String> nodes = tree.get(r);
dumpGenerator.writeStartArray();
for(String n : nodes) {
dumpGenerator.writeStartObject();
dumpGenerator.writeStringField("ip", n);
String hostname = NetUtils.getHostNameOfIP(n);
if(hostname != null) {
dumpGenerator.writeStringField("hostname", hostname);
}
dumpGenerator.writeEndObject();
}
dumpGenerator.writeEndArray();
dumpGenerator.writeEndObject();
}
dumpGenerator.writeEndArray();
dumpGenerator.flush();
if (!dumpGenerator.isClosed()) {
dumpGenerator.close();
}
}
protected void printTextFormat(PrintStream stream, Map<String,
TreeSet<String>> tree, ArrayList<String> racks) {
for(String r : racks) {
stream.println("Rack: " + r);
TreeSet<String> nodes = tree.get(r);
for(String n : nodes) {
stream.print(" " + n);
String hostname = NetUtils.getHostNameOfIP(n);
if(hostname != null) {
stream.print(" (" + hostname + ")");
}
stream.println();
}
stream.println();
}
}
@VisibleForTesting
protected static String parseAcceptHeader(HttpServletRequest request) {
String format = request.getHeader(HttpHeaders.ACCEPT);
return format != null && format.contains(FORMAT_JSON) ?
FORMAT_JSON : FORMAT_TEXT;
}
public static | NetworkTopologyServlet |
java | google__gson | gson/src/main/java/com/google/gson/Strictness.java | {
"start": 767,
"end": 1031
} | enum ____ {
/** Allow large deviations from the JSON specification. */
LENIENT,
/** Allow certain small deviations from the JSON specification for legacy reasons. */
LEGACY_STRICT,
/** Strict compliance with the JSON specification. */
STRICT
}
| Strictness |
java | apache__logging-log4j2 | log4j-1.2-api/src/main/java/org/apache/log4j/helpers/PatternParser.java | {
"start": 19882,
"end": 20221
} | class ____ extends NamedPatternConverter {
CategoryPatternConverter(final FormattingInfo formattingInfo, final int precision) {
super(formattingInfo, precision);
}
String getFullyQualifiedName(final LoggingEvent event) {
return event.getLoggerName();
}
}
}
| CategoryPatternConverter |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/naming/NamingFactory.java | {
"start": 837,
"end": 2243
} | class ____ {
/**
* Create a new naming service.
*
* @param serverList server list
* @return new naming service
* @throws NacosException nacos exception
*/
public static NamingService createNamingService(String serverList) throws NacosException {
try {
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
Constructor constructor = driverImplClass.getConstructor(String.class);
return (NamingService) constructor.newInstance(serverList);
} catch (Throwable e) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, e);
}
}
/**
* Create a new naming service.
*
* @param properties naming service properties
* @return new naming service
* @throws NacosException nacos exception
*/
public static NamingService createNamingService(Properties properties) throws NacosException {
try {
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
Constructor constructor = driverImplClass.getConstructor(Properties.class);
return (NamingService) constructor.newInstance(properties);
} catch (Throwable e) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, e);
}
}
}
| NamingFactory |
java | netty__netty | microbench/src/main/java/io/netty/microbench/channel/DefaultChannelIdBenchmark.java | {
"start": 1527,
"end": 1915
} | class ____ extends AbstractMicrobenchmark {
@Param({ "false", "true" })
private boolean noUnsafe;
@Setup(Level.Trial)
public void setup() {
System.setProperty("io.netty.noUnsafe", Boolean.valueOf(noUnsafe).toString());
}
@Benchmark
public DefaultChannelId newInstance() {
return DefaultChannelId.newInstance();
}
}
| DefaultChannelIdBenchmark |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ser/TestRootType.java | {
"start": 1481,
"end": 1611
} | class ____ {
public int a = 3;
}
// [databind#412]
@JsonPropertyOrder({ "uuid", "type" })
static | WithRootName |
java | spring-projects__spring-boot | module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java | {
"start": 7298,
"end": 8134
} | class ____ implements ApplicationListener<ClassPathChangedEvent> {
private static final Log logger = LogFactory.getLog(RestartingClassPathChangeChangedEventListener.class);
private final FileSystemWatcherFactory fileSystemWatcherFactory;
RestartingClassPathChangeChangedEventListener(FileSystemWatcherFactory fileSystemWatcherFactory) {
this.fileSystemWatcherFactory = fileSystemWatcherFactory;
}
@Override
public void onApplicationEvent(ClassPathChangedEvent event) {
if (event.isRestartRequired()) {
logger.info(LogMessage.format("Restarting due to %s", event.overview()));
logger.debug(LogMessage.format("Change set: %s", event.getChangeSet()));
Restarter.getInstance().restart(new FileWatchingFailureHandler(this.fileSystemWatcherFactory));
}
}
}
}
| RestartingClassPathChangeChangedEventListener |
java | apache__camel | components/camel-iec60870/src/main/java/org/apache/camel/component/iec60870/server/ServerProducer.java | {
"start": 1011,
"end": 2586
} | class ____ extends DefaultProducer {
private final ServerEndpoint endpoint;
private final ServerInstance server;
public ServerProducer(final ServerEndpoint endpoint, final ServerInstance server) {
super(endpoint);
this.endpoint = endpoint;
this.server = server;
}
@Override
public void process(final Exchange exchange) throws Exception {
final Value<?> value = mapToCommand(exchange);
this.server.notifyValue(this.endpoint.getAddress(), value);
}
private Value<?> mapToCommand(final Exchange exchange) {
final Object body = exchange.getIn().getBody();
if (body instanceof Value<?>) {
return (Value<?>) body;
}
if (body instanceof Float || body instanceof Double) {
return Value.ok(((Number) body).floatValue());
}
if (body instanceof Boolean) {
return Value.ok((Boolean) body);
}
if (body instanceof Short || body instanceof Byte || body instanceof Integer || body instanceof Long) {
return convertToShort(((Number) body).longValue());
}
throw new IllegalArgumentException("Unable to map body to a value: " + body);
}
private Value<?> convertToShort(final long value) {
if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
throw new IllegalArgumentException(
String.format("Value must be between %s and %s", Short.MIN_VALUE, Short.MAX_VALUE));
}
return Value.ok((short) value);
}
}
| ServerProducer |
java | apache__logging-log4j2 | log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedTest.java | {
"start": 1361,
"end": 2849
} | class ____ {
private static final String DIR = "target/threaded";
private static final String CONFIG = "log4j-threaded.xml";
private static final int LOOP_CNT = 25;
private static final int THREADS = 4;
private static final AtomicInteger counter = new AtomicInteger(0);
private static final LoggerContextRule context = new LoggerContextRule(CONFIG);
private final Logger logger = context.getLogger(ThreadedTest.class.getName());
private volatile Level lvl = Level.DEBUG;
// this would look pretty sweet with lambdas
@ClassRule
public static RuleChain chain = RuleChain.outerRule((base, description) -> new Statement() {
@Override
public void evaluate() throws Throwable {
deleteDir();
try {
base.evaluate();
} finally {
deleteDir();
}
}
})
.around(context);
@Test
void testDeadlock() throws Exception {
final ExecutorService pool = Executors.newFixedThreadPool(THREADS * 2);
final State state = new State();
for (int count = 0; count < THREADS; ++count) {
pool.execute(new LoggingRunnable(state));
pool.execute(new StateSettingRunnable(state));
}
Thread.sleep(250);
pool.shutdown();
System.out.println("Counter = " + counter);
}
public | ThreadedTest |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/connector/source/lib/NumberSequenceSourceTest.java | {
"start": 1767,
"end": 4535
} | class ____ {
@Test
void testReaderCheckpoints() throws Exception {
final long from = 177;
final long mid = 333;
final long to = 563;
final long elementsPerCycle = (to - from) / 3;
final TestingReaderOutput<Long> out = new TestingReaderOutput<>();
SourceReader<Long, NumberSequenceSource.NumberSequenceSplit> reader = createReader();
reader.addSplits(
Arrays.asList(
new NumberSequenceSource.NumberSequenceSplit("split-1", from, mid),
new NumberSequenceSource.NumberSequenceSplit("split-2", mid + 1, to)));
long remainingInCycle = elementsPerCycle;
while (reader.pollNext(out) != InputStatus.END_OF_INPUT) {
if (--remainingInCycle <= 0) {
remainingInCycle = elementsPerCycle;
// checkpoint
List<NumberSequenceSource.NumberSequenceSplit> splits = reader.snapshotState(1L);
// re-create and restore
reader = createReader();
if (splits.isEmpty()) {
reader.notifyNoMoreSplits();
} else {
reader.addSplits(splits);
}
}
}
final List<Long> result = out.getEmittedRecords();
validateSequence(result, from, to);
}
private static void validateSequence(
final List<Long> sequence, final long from, final long to) {
if (sequence.size() != to - from + 1) {
failSequence(sequence, from, to);
}
long nextExpected = from;
for (Long next : sequence) {
if (next != nextExpected++) {
failSequence(sequence, from, to);
}
}
}
private static void failSequence(final List<Long> sequence, final long from, final long to) {
fail(
String.format(
"Expected: A sequence [%d, %d], but found: sequence (size %d) : %s",
from, to, sequence.size(), sequence));
}
private static SourceReader<Long, NumberSequenceSource.NumberSequenceSplit> createReader() {
// the arguments passed in the source constructor matter only to the enumerator
return new NumberSequenceSource(0L, 0L).createReader(new DummyReaderContext());
}
// ------------------------------------------------------------------------
// test utils / mocks
//
// the "flink-connector-test-utils module has proper mocks and utils,
// but cannot be used here, because it would create a cyclic dependency.
// ------------------------------------------------------------------------
private static final | NumberSequenceSourceTest |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_2145/Issue2145Mapper.java | {
"start": 469,
"end": 795
} | interface ____ {
Issue2145Mapper INSTANCE = Mappers.getMapper( Issue2145Mapper.class );
@Mapping(target = "nested", source = "value")
Target map(Source source);
default Nested map(String in) {
Nested nested = new Nested();
nested.setValue( in );
return nested;
}
| Issue2145Mapper |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/common/util/MockBigArrays.java | {
"start": 2160,
"end": 13150
} | class ____ extends BigArrays {
private static final Logger logger = LogManager.getLogger(MockBigArrays.class);
/**
* Error message thrown by {@link BigArrays} produced with {@link MockBigArrays#MockBigArrays(PageCacheRecycler, ByteSizeValue)}.
*/
public static final String ERROR_MESSAGE = "over test limit";
/**
* Assert that a function returning a {@link Releasable} runs to completion
* when allocated a breaker with that breaks when it uses more than {@code max}
* bytes <strong>and</strong> that the function doesn't leak any
* {@linkplain BigArray}s if it is given a breaker that allows fewer bytes.
*/
public static void assertFitsIn(ByteSizeValue max, Function<BigArrays, Releasable> run) {
long maxBytes = 0;
long prevLimit = 0;
while (true) {
ByteSizeValue limit = ByteSizeValue.ofBytes(maxBytes);
MockBigArrays bigArrays = new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), limit);
Releasable r = null;
try {
r = run.apply(bigArrays);
} catch (CircuitBreakingException e) {
if (maxBytes >= max.getBytes()) {
throw new AssertionError("required more than " + maxBytes + " bytes");
}
prevLimit = maxBytes;
maxBytes = Math.min(max.getBytes(), maxBytes + Math.max(1, max.getBytes() / 10));
continue;
}
Releasables.close(r);
logger.info(
"First successfully built using less than {} and more than {}",
ByteSizeValue.ofBytes(maxBytes),
ByteSizeValue.ofBytes(prevLimit)
);
return;
}
}
/**
* Tracking allocations is useful when debugging a leak but shouldn't be enabled by default as this would also be very costly
* since it creates a new Exception every time a new array is created.
*/
private static final boolean TRACK_ALLOCATIONS = false;
private static final ConcurrentMap<Object, Object> ACQUIRED_ARRAYS = new ConcurrentHashMap<>();
public static void ensureAllArraysAreReleased() throws Exception {
final Map<Object, Object> masterCopy = new HashMap<>(ACQUIRED_ARRAYS);
if (masterCopy.isEmpty() == false) {
// not empty, we might be executing on a shared cluster that keeps on obtaining
// and releasing arrays, lets make sure that after a reasonable timeout, all master
// copy (snapshot) have been released
try {
assertBusy(() -> assertTrue(Sets.haveEmptyIntersection(masterCopy.keySet(), ACQUIRED_ARRAYS.keySet())));
} catch (AssertionError ex) {
masterCopy.keySet().retainAll(ACQUIRED_ARRAYS.keySet());
ACQUIRED_ARRAYS.keySet().removeAll(masterCopy.keySet()); // remove all existing master copy we will report on
if (masterCopy.isEmpty() == false) {
Iterator<Object> causes = masterCopy.values().iterator();
Object firstCause = causes.next();
RuntimeException exception = new RuntimeException(
masterCopy.size() + " arrays have not been released",
firstCause instanceof Throwable ? (Throwable) firstCause : null
);
while (causes.hasNext()) {
Object cause = causes.next();
if (cause instanceof Throwable) {
exception.addSuppressed((Throwable) cause);
}
}
if (TRACK_ALLOCATIONS) {
for (Object allocation : masterCopy.values()) {
exception.addSuppressed((Throwable) allocation);
}
}
throw exception;
}
}
}
}
private final Random random;
private final PageCacheRecycler recycler;
private final CircuitBreakerService breakerService;
/**
* Create {@linkplain BigArrays} with a configured limit.
*/
public MockBigArrays(PageCacheRecycler recycler, ByteSizeValue limit) {
this(recycler, mock(CircuitBreakerService.class), true);
when(breakerService.getBreaker(CircuitBreaker.REQUEST)).thenReturn(new LimitedBreaker(CircuitBreaker.REQUEST, limit));
}
/**
* Create {@linkplain BigArrays} with a provided breaker service. The breaker is not enable by default.
*/
public MockBigArrays(PageCacheRecycler recycler, CircuitBreakerService breakerService) {
this(recycler, breakerService, false);
}
/**
* Create {@linkplain BigArrays} with a provided breaker service. The breaker can be enabled with the
* {@code checkBreaker} flag.
*/
public MockBigArrays(PageCacheRecycler recycler, CircuitBreakerService breakerService, boolean checkBreaker) {
super(recycler, breakerService, CircuitBreaker.REQUEST, checkBreaker);
this.recycler = recycler;
this.breakerService = breakerService;
long seed;
try {
seed = SeedUtils.parseSeed(RandomizedContext.current().getRunnerSeedAsString());
} catch (IllegalStateException e) { // rest tests don't run randomized and have no context
seed = 0;
}
random = new Random(seed);
}
@Override
public BigArrays withCircuitBreaking() {
return new MockBigArrays(this.recycler, this.breakerService, true);
}
@Override
public BigArrays withBreakerService(CircuitBreakerService breakerService) {
return new MockBigArrays(this.recycler, breakerService, this.shouldCheckBreaker());
}
@Override
public ByteArray newByteArray(long size, boolean clearOnResize) {
final ByteArrayWrapper array = new ByteArrayWrapper(super.newByteArray(size, clearOnResize), clearOnResize);
if (clearOnResize == false) {
array.randomizeContent(0, size);
}
return array;
}
@Override
public ByteArray resize(ByteArray array, long size) {
ByteArrayWrapper arr = (ByteArrayWrapper) array;
final long originalSize = arr.size();
array = super.resize(arr.in, size);
ACQUIRED_ARRAYS.remove(arr);
if (array instanceof ByteArrayWrapper) {
arr = (ByteArrayWrapper) array;
} else {
arr = new ByteArrayWrapper(array, arr.clearOnResize);
}
if (arr.clearOnResize == false) {
arr.randomizeContent(originalSize, size);
}
return arr;
}
@Override
public IntArray newIntArray(long size, boolean clearOnResize) {
final IntArrayWrapper array = new IntArrayWrapper(super.newIntArray(size, clearOnResize), clearOnResize);
if (clearOnResize == false) {
array.randomizeContent(0, size);
}
return array;
}
@Override
public IntArray resize(IntArray array, long size) {
IntArrayWrapper arr = (IntArrayWrapper) array;
final long originalSize = arr.size();
array = super.resize(arr.in, size);
ACQUIRED_ARRAYS.remove(arr);
if (array instanceof IntArrayWrapper) {
arr = (IntArrayWrapper) array;
} else {
arr = new IntArrayWrapper(array, arr.clearOnResize);
}
if (arr.clearOnResize == false) {
arr.randomizeContent(originalSize, size);
}
return arr;
}
@Override
public LongArray newLongArray(long size, boolean clearOnResize) {
final LongArrayWrapper array = new LongArrayWrapper(super.newLongArray(size, clearOnResize), clearOnResize);
if (clearOnResize == false) {
array.randomizeContent(0, size);
}
return array;
}
@Override
public LongArray resize(LongArray array, long size) {
LongArrayWrapper arr = (LongArrayWrapper) array;
final long originalSize = arr.size();
array = super.resize(arr.in, size);
ACQUIRED_ARRAYS.remove(arr);
if (array instanceof LongArrayWrapper) {
arr = (LongArrayWrapper) array;
} else {
arr = new LongArrayWrapper(array, arr.clearOnResize);
}
if (arr.clearOnResize == false) {
arr.randomizeContent(originalSize, size);
}
return arr;
}
@Override
public FloatArray newFloatArray(long size, boolean clearOnResize) {
final FloatArrayWrapper array = new FloatArrayWrapper(super.newFloatArray(size, clearOnResize), clearOnResize);
if (clearOnResize == false) {
array.randomizeContent(0, size);
}
return array;
}
@Override
public FloatArray resize(FloatArray array, long size) {
FloatArrayWrapper arr = (FloatArrayWrapper) array;
final long originalSize = arr.size();
array = super.resize(arr.in, size);
ACQUIRED_ARRAYS.remove(arr);
if (array instanceof FloatArrayWrapper) {
arr = (FloatArrayWrapper) array;
} else {
arr = new FloatArrayWrapper(array, arr.clearOnResize);
}
if (arr.clearOnResize == false) {
arr.randomizeContent(originalSize, size);
}
return arr;
}
@Override
public DoubleArray newDoubleArray(long size, boolean clearOnResize) {
final DoubleArrayWrapper array = new DoubleArrayWrapper(super.newDoubleArray(size, clearOnResize), clearOnResize);
if (clearOnResize == false) {
array.randomizeContent(0, size);
}
return array;
}
@Override
public DoubleArray resize(DoubleArray array, long size) {
DoubleArrayWrapper arr = (DoubleArrayWrapper) array;
final long originalSize = arr.size();
array = super.resize(arr.in, size);
ACQUIRED_ARRAYS.remove(arr);
if (array instanceof DoubleArrayWrapper) {
arr = (DoubleArrayWrapper) array;
} else {
arr = new DoubleArrayWrapper(array, arr.clearOnResize);
}
if (arr.clearOnResize == false) {
arr.randomizeContent(originalSize, size);
}
return arr;
}
@Override
public <T> ObjectArray<T> newObjectArray(long size) {
return new ObjectArrayWrapper<>(super.<T>newObjectArray(size));
}
@Override
public <T> ObjectArray<T> resize(ObjectArray<T> array, long size) {
ObjectArrayWrapper<T> arr = (ObjectArrayWrapper<T>) array;
array = super.resize(arr.in, size);
ACQUIRED_ARRAYS.remove(arr);
if (array instanceof ObjectArrayWrapper) {
arr = (ObjectArrayWrapper<T>) array;
} else {
arr = new ObjectArrayWrapper<>(array);
}
return arr;
}
private abstract static | MockBigArrays |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/deftyping/TestDefaultForScalars.java | {
"start": 938,
"end": 1151
} | class ____ {
public long key;
}
// Basic `ObjectWrapper` from base uses delegating ctor, won't work well; should
// figure out why, but until then we'll use separate impl
protected static | Data |
java | apache__camel | components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/feature/AbstractDataFormatFeature.java | {
"start": 1301,
"end": 1355
} | class ____ the data format feature
*/
public abstract | for |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/azureopenai/completion/AzureOpenAiCompletionModelTests.java | {
"start": 918,
"end": 5652
} | class ____ extends ESTestCase {
public void testOverrideWith_UpdatedTaskSettings_OverridesUser() {
var resource = "resource";
var deploymentId = "deployment";
var apiVersion = "api version";
var apiKey = "api key";
var entraId = "entra id";
var inferenceEntityId = "inference entity id";
var user = "user";
var userOverride = "user override";
var model = createCompletionModel(resource, deploymentId, apiVersion, user, apiKey, entraId, inferenceEntityId);
var requestTaskSettingsMap = taskSettingsMap(userOverride);
var overriddenModel = AzureOpenAiCompletionModel.of(model, requestTaskSettingsMap);
assertThat(
overriddenModel,
equalTo(createCompletionModel(resource, deploymentId, apiVersion, userOverride, apiKey, entraId, inferenceEntityId))
);
}
public void testOverrideWith_EmptyMap_OverridesNothing() {
var model = createCompletionModel("resource", "deployment", "api version", "user", "api key", "entra id", "inference entity id");
var requestTaskSettingsMap = Map.<String, Object>of();
var overriddenModel = AzureOpenAiCompletionModel.of(model, requestTaskSettingsMap);
assertThat(overriddenModel, sameInstance(model));
}
public void testOverrideWith_NullMap_OverridesNothing() {
var model = createCompletionModel("resource", "deployment", "api version", "user", "api key", "entra id", "inference entity id");
var overriddenModel = AzureOpenAiCompletionModel.of(model, null);
assertThat(overriddenModel, sameInstance(model));
}
public void testOverrideWith_UpdatedServiceSettings_OverridesApiVersion() {
var resource = "resource";
var deploymentId = "deployment";
var apiKey = "api key";
var user = "user";
var entraId = "entra id";
var inferenceEntityId = "inference entity id";
var apiVersion = "api version";
var updatedApiVersion = "updated api version";
var updatedServiceSettings = new AzureOpenAiCompletionServiceSettings(resource, deploymentId, updatedApiVersion, null);
var model = createCompletionModel(resource, deploymentId, apiVersion, user, apiKey, entraId, inferenceEntityId);
var overriddenModel = new AzureOpenAiCompletionModel(model, updatedServiceSettings);
assertThat(
overriddenModel,
is(createCompletionModel(resource, deploymentId, updatedApiVersion, user, apiKey, entraId, inferenceEntityId))
);
}
public void testBuildUriString() throws URISyntaxException {
var resource = "resource";
var deploymentId = "deployment";
var apiKey = "api key";
var user = "user";
var entraId = "entra id";
var inferenceEntityId = "inference entity id";
var apiVersion = "2024";
var model = createCompletionModel(resource, deploymentId, apiVersion, user, apiKey, entraId, inferenceEntityId);
assertThat(
model.buildUriString().toString(),
is("https://resource.openai.azure.com/openai/deployments/deployment/chat/completions?api-version=2024")
);
}
public static AzureOpenAiCompletionModel createModelWithRandomValues() {
return createCompletionModel(
randomAlphaOfLength(10),
randomAlphaOfLength(10),
randomAlphaOfLength(10),
randomAlphaOfLength(10),
randomAlphaOfLength(10),
randomAlphaOfLength(10),
randomAlphaOfLength(10)
);
}
public static AzureOpenAiCompletionModel createCompletionModel(
String resourceName,
String deploymentId,
String apiVersion,
String user,
@Nullable String apiKey,
@Nullable String entraId,
String inferenceEntityId
) {
var secureApiKey = apiKey != null ? new SecureString(apiKey.toCharArray()) : null;
var secureEntraId = entraId != null ? new SecureString(entraId.toCharArray()) : null;
return new AzureOpenAiCompletionModel(
inferenceEntityId,
TaskType.COMPLETION,
"service",
new AzureOpenAiCompletionServiceSettings(resourceName, deploymentId, apiVersion, null),
new AzureOpenAiCompletionTaskSettings(user),
new AzureOpenAiSecretSettings(secureApiKey, secureEntraId)
);
}
private Map<String, Object> taskSettingsMap(String user) {
Map<String, Object> taskSettingsMap = new HashMap<>();
taskSettingsMap.put(AzureOpenAiServiceFields.USER, user);
return taskSettingsMap;
}
}
| AzureOpenAiCompletionModelTests |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/runtime/operators/sink/committables/CommittableCollector.java | {
"start": 1900,
"end": 9252
} | class ____<CommT> {
/** Mapping of checkpoint id to {@link CheckpointCommittableManagerImpl}. */
private final NavigableMap<Long, CheckpointCommittableManagerImpl<CommT>>
checkpointCommittables;
private final SinkCommitterMetricGroup metricGroup;
public CommittableCollector(SinkCommitterMetricGroup metricGroup) {
this(new TreeMap<>(), metricGroup);
}
/** For deep-copy. */
CommittableCollector(
Map<Long, CheckpointCommittableManagerImpl<CommT>> checkpointCommittables,
SinkCommitterMetricGroup metricGroup) {
this.checkpointCommittables = new TreeMap<>(checkNotNull(checkpointCommittables));
this.metricGroup = metricGroup;
this.metricGroup.setCurrentPendingCommittablesGauge(this::getNumPending);
}
private int getNumPending() {
return checkpointCommittables.values().stream()
.mapToInt(m -> (int) m.getPendingRequests().count())
.sum();
}
/**
* Creates a {@link CommittableCollector} based on the current runtime information. This method
* should be used for to instantiate a collector for all Sink V2.
*
* @param metricGroup storing the committable metrics
* @param <CommT> type of the committable
* @return {@link CommittableCollector}
*/
public static <CommT> CommittableCollector<CommT> of(SinkCommitterMetricGroup metricGroup) {
return new CommittableCollector<>(metricGroup);
}
/**
* Creates a {@link CommittableCollector} for a list of committables. This method is mainly used
* to create a collector from the state of Sink V1.
*
* @param committables list of committables
* @param metricGroup storing the committable metrics
* @param <CommT> type of committables
* @return {@link CommittableCollector}
*/
static <CommT> CommittableCollector<CommT> ofLegacy(
List<CommT> committables, SinkCommitterMetricGroup metricGroup) {
CommittableCollector<CommT> committableCollector = new CommittableCollector<>(metricGroup);
// add a checkpoint with the lowest checkpoint id, this will be merged into the next
// checkpoint data, subtask id is arbitrary
CommittableSummary<CommT> summary =
new CommittableSummary<>(
0,
1,
InitContext.INITIAL_CHECKPOINT_ID,
committables.size(),
committables.size(),
0);
committableCollector.addSummary(summary);
committables.forEach(
c -> {
final CommittableWithLineage<CommT> committableWithLineage =
new CommittableWithLineage<>(c, InitContext.INITIAL_CHECKPOINT_ID, 0);
committableCollector.addCommittable(committableWithLineage);
});
return committableCollector;
}
/**
* Adds a {@link CommittableMessage} to the collector to hold it until emission.
*
* @param message either {@link CommittableSummary} or {@link CommittableWithLineage}
*/
public void addMessage(CommittableMessage<CommT> message) {
if (message instanceof CommittableSummary) {
addSummary((CommittableSummary<CommT>) message);
} else if (message instanceof CommittableWithLineage) {
addCommittable((CommittableWithLineage<CommT>) message);
}
}
/**
* Returns all {@link CheckpointCommittableManager} until the requested checkpoint id.
*
* @param checkpointId counter
* @return collection of {@link CheckpointCommittableManager}
*/
public Collection<? extends CheckpointCommittableManager<CommT>> getCheckpointCommittablesUpTo(
long checkpointId) {
return new ArrayList<>(checkpointCommittables.headMap(checkpointId, true).values());
}
/**
* Returns whether all {@link CheckpointCommittableManager} currently hold by the collector are
* either committed or failed.
*
* @return state of the {@link CheckpointCommittableManager}
*/
public boolean isFinished() {
return checkpointCommittables.values().stream()
.allMatch(CheckpointCommittableManagerImpl::isFinished);
}
/**
* Merges all information from an external collector into this collector.
*
* <p>This method is important during recovery from existing state.
*
* @param cc other {@link CommittableCollector}
*/
public void merge(CommittableCollector<CommT> cc) {
for (Entry<Long, CheckpointCommittableManagerImpl<CommT>> checkpointEntry :
cc.checkpointCommittables.entrySet()) {
checkpointCommittables.merge(
checkpointEntry.getKey(),
checkpointEntry.getValue(),
CheckpointCommittableManagerImpl::merge);
}
}
/**
* Returns a new committable collector that deep copies all internals.
*
* @return {@link CommittableCollector}
*/
public CommittableCollector<CommT> copy() {
return new CommittableCollector<>(
checkpointCommittables.entrySet().stream()
.map(e -> Tuple2.of(e.getKey(), e.getValue().copy()))
.collect(Collectors.toMap((t) -> t.f0, (t) -> t.f1)),
metricGroup);
}
Collection<CheckpointCommittableManagerImpl<CommT>> getCheckpointCommittables() {
return checkpointCommittables.values();
}
private void addSummary(CommittableSummary<CommT> summary) {
checkpointCommittables
.computeIfAbsent(
summary.getCheckpointIdOrEOI(),
key -> CheckpointCommittableManagerImpl.forSummary(summary, metricGroup))
.addSummary(summary);
}
private void addCommittable(CommittableWithLineage<CommT> committable) {
getCheckpointCommittables(committable).addCommittable(committable);
}
private CheckpointCommittableManagerImpl<CommT> getCheckpointCommittables(
CommittableMessage<CommT> committable) {
CheckpointCommittableManagerImpl<CommT> committables =
this.checkpointCommittables.get(committable.getCheckpointIdOrEOI());
return checkNotNull(committables, "Unknown checkpoint for %s", committable);
}
/** Removes the manager for a specific checkpoint and all it's metadata. */
public void remove(CheckpointCommittableManager<CommT> manager) {
checkpointCommittables.remove(manager.getCheckpointId());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CommittableCollector<?> that = (CommittableCollector<?>) o;
return Objects.equals(checkpointCommittables, that.checkpointCommittables);
}
@Override
public int hashCode() {
return Objects.hashCode(checkpointCommittables);
}
@Override
public String toString() {
return "CommittableCollector{" + "checkpointCommittables=" + checkpointCommittables + '}';
}
}
| CommittableCollector |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/load/ResourceDecoder.java | {
"start": 194,
"end": 395
} | interface ____ decoding resources.
*
* @param <T> The type the resource will be decoded from (File, InputStream etc).
* @param <Z> The type of the decoded resource (Bitmap, Drawable etc).
*/
public | for |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/vector/CosineSimilarityTests.java | {
"start": 871,
"end": 1706
} | class ____ extends AbstractVectorSimilarityFunctionTestCase {
public CosineSimilarityTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) {
super(testCaseSupplier);
}
@Override
public String getBaseEvaluatorName() {
return CosineSimilarity.class.getSimpleName();
}
@ParametersFactory
public static Iterable<Object[]> parameters() {
return similarityParameters(CosineSimilarity.class.getSimpleName(), CosineSimilarity.SIMILARITY_FUNCTION);
}
protected EsqlCapabilities.Cap capability() {
return EsqlCapabilities.Cap.COSINE_VECTOR_SIMILARITY_FUNCTION;
}
@Override
protected Expression build(Source source, List<Expression> args) {
return new CosineSimilarity(source, args.get(0), args.get(1));
}
}
| CosineSimilarityTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/refaster/UClassIdentTest.java | {
"start": 2233,
"end": 2676
} | class ____
inliner.addImport("package.Exception");
assertInlines("Exception", UClassIdent.create("package.Exception"));
// Will import "anotherPackage.Exception" due to conflicts
assertInlines("anotherPackage.Exception", UClassIdent.create("anotherPackage.Exception"));
new EqualsTester()
.addEqualityGroup(inliner.getImportsToAdd(), ImmutableSet.of("package.Exception"))
.testEquals();
// Test nested | names |
java | square__retrofit | retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/AsyncTest.java | {
"start": 1588,
"end": 1749
} | class ____ {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final TestRule pluginsReset = new RxJavaPluginsResetRule();
| AsyncTest |
java | mockito__mockito | mockito-core/src/test/java/org/mockitousage/stubbing/StubbingReturnsSelfTest.java | {
"start": 3512,
"end": 3969
} | class ____ {
private HttpBuilder builder;
public HttpRequesterWithHeaders(HttpBuilder builder) {
this.builder = builder;
}
public String request(String uri) {
return builder.withUrl(uri)
.withHeader("Content-type: application/json")
.withHeader("Authorization: Bearer")
.request();
}
}
private static | HttpRequesterWithHeaders |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/event/internal/PostDeleteEventListenerStandardImpl.java | {
"start": 577,
"end": 1197
} | class ____ implements PostDeleteEventListener, CallbackRegistryConsumer {
private CallbackRegistry callbackRegistry;
@Override
public void injectCallbackRegistry(CallbackRegistry callbackRegistry) {
this.callbackRegistry = callbackRegistry;
}
@Override
public void onPostDelete(PostDeleteEvent event) {
Object entity = event.getEntity();
callbackRegistry.postRemove( entity );
}
@Override
public boolean requiresPostCommitHandling(EntityPersister persister) {
return callbackRegistry.hasRegisteredCallbacks( persister.getMappedClass(), CallbackType.POST_REMOVE );
}
}
| PostDeleteEventListenerStandardImpl |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/asm/Opcodes.java | {
"start": 10092,
"end": 12232
} | class ____ extends StuffVisitor {
* @Override public void visitOldStuff(int arg, ...) {
* super.visitOldStuff(arg, ...);
* [ do user stuff ]
* }
* }
* </pre>
*
* <p>and, here again, whether visitNewStuff or visitOldStuff is called, 'do stuff', 'do other
* stuff' and 'do user stuff' will be executed, in this order (exercise left to the reader).
*
* <h1>Notes</h1>
*
* <ul>
* <li>the SOURCE_DEPRECATED flag is set only if 'api' is API_OLD, just before calling
* visitNewStuff. By hypothesis, this method is not overridden by the user. Therefore, user
* classes can never see this flag. Only ASM subclasses must take care of extracting the
* actual argument value by clearing the source flags.
* <li>because the SOURCE_DEPRECATED flag is immediately cleared in the caller, the caller can
* call visitOldStuff or visitNewStuff (in 'do stuff' and 'do user stuff') on a delegate
* visitor without any risks (breaking the redirection logic, "leaking" the flag, etc).
* <li>all the scenarios discussed above are unit tested in MethodVisitorTest.
* </ul>
*/
int SOURCE_DEPRECATED = 0x100;
int SOURCE_MASK = SOURCE_DEPRECATED;
// Java ClassFile versions (the minor version is stored in the 16 most significant bits, and the
// major version in the 16 least significant bits).
int V1_1 = 3 << 16 | 45;
int V1_2 = 0 << 16 | 46;
int V1_3 = 0 << 16 | 47;
int V1_4 = 0 << 16 | 48;
int V1_5 = 0 << 16 | 49;
int V1_6 = 0 << 16 | 50;
int V1_7 = 0 << 16 | 51;
int V1_8 = 0 << 16 | 52;
int V9 = 0 << 16 | 53;
int V10 = 0 << 16 | 54;
int V11 = 0 << 16 | 55;
int V12 = 0 << 16 | 56;
int V13 = 0 << 16 | 57;
int V14 = 0 << 16 | 58;
int V15 = 0 << 16 | 59;
int V16 = 0 << 16 | 60;
int V17 = 0 << 16 | 61;
int V18 = 0 << 16 | 62;
int V19 = 0 << 16 | 63;
int V20 = 0 << 16 | 64;
int V21 = 0 << 16 | 65;
int V22 = 0 << 16 | 66;
int V23 = 0 << 16 | 67;
int V24 = 0 << 16 | 68;
int V25 = 0 << 16 | 69;
int V26 = 0 << 16 | 70;
/**
* Version flag indicating that the | UserStuffVisitor |
java | quarkusio__quarkus | independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/bcextensions/StereotypeInfoImpl.java | {
"start": 267,
"end": 1624
} | class ____ implements StereotypeInfo {
private final org.jboss.jandex.IndexView jandexIndex;
private final org.jboss.jandex.MutableAnnotationOverlay annotationOverlay;
private final io.quarkus.arc.processor.StereotypeInfo arcStereotype;
StereotypeInfoImpl(org.jboss.jandex.IndexView jandexIndex, org.jboss.jandex.MutableAnnotationOverlay annotationOverlay,
io.quarkus.arc.processor.StereotypeInfo arcStereotype) {
this.jandexIndex = jandexIndex;
this.annotationOverlay = annotationOverlay;
this.arcStereotype = arcStereotype;
}
@Override
public ScopeInfo defaultScope() {
return new ScopeInfoImpl(jandexIndex, annotationOverlay, arcStereotype.getDefaultScope());
}
@Override
public Collection<AnnotationInfo> interceptorBindings() {
return arcStereotype.getInterceptorBindings()
.stream()
.map(it -> (AnnotationInfo) new AnnotationInfoImpl(jandexIndex, annotationOverlay, it))
.toList();
}
@Override
public boolean isAlternative() {
return arcStereotype.isAlternative();
}
@Override
public Integer priority() {
return arcStereotype.getAlternativePriority();
}
@Override
public boolean isNamed() {
return arcStereotype.isNamed();
}
}
| StereotypeInfoImpl |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/capabilities/TelemetryAware.java | {
"start": 572,
"end": 706
} | class ____.
*/
default String telemetryLabel() {
return getClass().getSimpleName().toUpperCase(Locale.ROOT);
}
}
| name |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/ElasticsearchExceptionTests.java | {
"start": 76929,
"end": 78914
} | class ____ extends ElasticsearchException {
Exception4xx(String message) {
super(message);
}
@Override
public RestStatus status() {
return RestStatus.BAD_REQUEST;
}
}
public void testExceptionTypeHeader() throws IOException {
var e = new Exception5xx("some exception");
assertThat(e.getHttpHeaderKeys(), hasItem(ElasticsearchException.EXCEPTION_TYPE_HEADER));
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
e.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
String expected = """
{
"type": "exception5xx",
"reason": "some exception"
}""";
assertEquals(XContentHelper.stripWhitespace(expected), Strings.toString(builder));
}
public void testHttpHeaders() throws IOException {
var e = new ElasticsearchException("some exception");
e.addHttpHeader("My-Header", "value");
assertThat(e.getHttpHeaderKeys(), hasItem("My-Header"));
assertThat(e.getHttpHeader("My-Header"), equalTo(List.of("value")));
assertThat(e.getHttpHeaders(), hasEntry("My-Header", List.of("value")));
// ensure http headers are not written to response body
}
public void testNoExceptionTypeHeaderOn4xx() throws IOException {
var e = new Exception4xx("some exception");
assertThat(e.getHttpHeaderKeys(), not(hasItem(ElasticsearchException.EXCEPTION_TYPE_HEADER)));
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
e.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
String expected = """
{
"type": "exception4xx",
"reason": "some exception"
}""";
assertEquals(XContentHelper.stripWhitespace(expected), Strings.toString(builder));
}
}
| Exception4xx |
java | google__dagger | javatests/dagger/internal/codegen/ComponentProcessorTest.java | {
"start": 13993,
"end": 14280
} | class ____ {}");
Source testModule = CompilerTests.javaSource("test.TestModule",
"package test;",
"",
"import dagger.Module;",
"",
"@Module(includes = {DepModule.class, AlwaysIncluded.class})",
"final | AlwaysIncluded |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestWriteBlockGetsBlockLengthHint.java | {
"start": 1485,
"end": 2587
} | class ____ {
static final long DEFAULT_BLOCK_LENGTH = 1024;
static final long EXPECTED_BLOCK_LENGTH = DEFAULT_BLOCK_LENGTH * 2;
@Test
public void blockLengthHintIsPropagated() throws IOException {
final String METHOD_NAME = GenericTestUtils.getMethodName();
final Path path = new Path("/" + METHOD_NAME + ".dat");
Configuration conf = new HdfsConfiguration();
FsDatasetChecker.setFactory(conf);
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, DEFAULT_BLOCK_LENGTH);
conf.setInt(DFSConfigKeys.DFS_DATANODE_SCAN_PERIOD_HOURS_KEY, -1);
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
try {
cluster.waitActive();
// FsDatasetChecker#createRbw asserts during block creation if the test
// fails.
DFSTestUtil.createFile(
cluster.getFileSystem(),
path,
4096, // Buffer size.
EXPECTED_BLOCK_LENGTH,
EXPECTED_BLOCK_LENGTH,
(short) 1,
0x1BAD5EED);
} finally {
cluster.shutdown();
}
}
static | TestWriteBlockGetsBlockLengthHint |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchingInheritanceTest.java | {
"start": 1648,
"end": 2028
} | class ____ {
@Id
private Long id;
private String name;
public EntityBase() {
}
public EntityBase(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
@Entity(name = "Cheese")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public static | EntityBase |
java | alibaba__nacos | client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java | {
"start": 1118,
"end": 2392
} | class ____ {
@Test
void testGetHostByRandomWeightNull() {
assertNull(Balancer.getHostByRandomWeight(null));
assertNull(Balancer.getHostByRandomWeight(new ArrayList<>()));
}
@Test
void testGetHostByRandomWeight() {
List<Instance> list = new ArrayList<>();
Instance instance1 = new Instance();
list.add(instance1);
final Instance actual = Balancer.getHostByRandomWeight(list);
assertEquals(instance1, actual);
}
@Test
void testSelectHost() {
List<Instance> hosts = new ArrayList<>();
Instance instance1 = new Instance();
hosts.add(instance1);
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setHosts(hosts);
final Instance actual = Balancer.RandomByWeight.selectHost(serviceInfo);
assertEquals(instance1, actual);
}
@Test
void testSelectHostEmpty() {
Throwable exception = assertThrows(IllegalStateException.class, () -> {
ServiceInfo serviceInfo = new ServiceInfo();
Balancer.RandomByWeight.selectHost(serviceInfo);
});
assertTrue(exception.getMessage().contains("no host to srv for serviceInfo: null"));
}
} | BalancerTest |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/proxy/jdbc/NClobProxy.java | {
"start": 686,
"end": 761
} | interface ____ extends ClobProxy, NClob {
NClob getRawNClob();
}
| NClobProxy |
java | apache__camel | components/camel-aws/camel-aws2-mq/src/main/java/org/apache/camel/component/aws2/mq/client/MQ2InternalClient.java | {
"start": 998,
"end": 1198
} | interface ____ {
/**
* Returns an MQ client after a factory method determines which one to return.
*
* @return MqClient MqClient
*/
MqClient getMqClient();
}
| MQ2InternalClient |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java | {
"start": 5847,
"end": 6058
} | class ____ {
private final String value;
ExampleBean() {
this.value = "new";
}
ExampleBean(String value) {
this.value = value;
}
String getValue() {
return this.value;
}
}
}
| ExampleBean |
java | netty__netty | handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java | {
"start": 969,
"end": 1049
} | class ____ {@link JdkApplicationProtocolNegotiator} classes to inherit from.
*/
| for |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/ClassTemplateInvocationTests.java | {
"start": 61045,
"end": 61155
} | class ____ {
@Test
void test() {
fail("should not be called");
}
static | InvalidZeroInvocationTestCase |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/OptimizableOperator.java | {
"start": 807,
"end": 1139
} | interface ____ operator in Reactor which adds contracts around subscription
* optimizations:
* <ul>
* <li>looping instead of recursive subscribes, via {@link #subscribeOrReturn(CoreSubscriber)} and
* {@link #nextOptimizableSource()}</li>
* </ul>
*
* @param <IN> the {@link CoreSubscriber} data type
* @since 3.3.0
*/
| of |
java | apache__logging-log4j2 | log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/PatternLayoutComparisonBenchmark.java | {
"start": 1908,
"end": 4854
} | class ____ {
static final String STR = "AB!(%087936DZYXQWEIOP$#^~-=/><nb"; // length=32
static final LogEvent LOG4J2EVENT = createLog4j2Event();
private static final Charset CHARSET_DEFAULT = Charset.defaultCharset();
private static final String LOG4JPATTERN = "%d %5p [%t] %c{1} %X{transactionId} - %m%n";
private final PatternLayout LOG4J2_PATTERN_LAYOUT =
PatternLayout.createLayout(LOG4JPATTERN, null, null, null, CHARSET_DEFAULT, false, true, null, null);
private static LogEvent createLog4j2Event() {
final Marker marker = null;
final String fqcn = "com.mycom.myproject.mypackage.MyClass";
final Level level = Level.DEBUG;
final Message message = new SimpleMessage(STR);
final Throwable t = null;
final StringMap mdc = null;
final ContextStack ndc = null;
final String threadName = null;
final StackTraceElement location = null;
final long timestamp = 12345678;
return Log4jLogEvent.newBuilder() //
.setLoggerName("name(ignored)") //
.setMarker(marker) //
.setLoggerFqcn(fqcn) //
.setLevel(level) //
.setMessage(message) //
.setThrown(t) //
.setContextData(mdc) //
.setContextStack(ndc) //
.setThreadName(threadName) //
.setSource(location) //
.setTimeMillis(timestamp) //
.build();
}
// Logback
private static final String LOGBACKPATTERN = "%d %5p [%t] %c{0} %X{transactionId} - %m%n";
private final PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
private final LoggerContext context = new LoggerContext();
private final Logger logger = context.getLogger(PatternLayoutComparisonBenchmark.class);
private final ILoggingEvent LOGBACKEVENT = makeLoggingEvent(STR);
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
@Setup
public void setUp() throws IOException {
patternLayoutEncoder.setPattern(LOGBACKPATTERN);
patternLayoutEncoder.setContext(context);
patternLayoutEncoder.start();
((ch.qos.logback.classic.PatternLayout) patternLayoutEncoder.getLayout()).setOutputPatternAsHeader(false);
}
ILoggingEvent makeLoggingEvent(final String message) {
return new LoggingEvent(
PatternLayoutComparisonBenchmark.class.getName(),
logger,
ch.qos.logback.classic.Level.DEBUG,
message,
null,
null);
}
@Benchmark
public byte[] logback() throws IOException {
baos.reset();
return patternLayoutEncoder.encode(LOGBACKEVENT);
}
@Benchmark
public byte[] log4j2() {
return LOG4J2_PATTERN_LAYOUT.toByteArray(LOG4J2EVENT);
}
}
| PatternLayoutComparisonBenchmark |
java | elastic__elasticsearch | build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/toolchain/JavaToolChainResolverPlugin.java | {
"start": 709,
"end": 1338
} | class ____ implements Plugin<Settings> {
@Inject
protected abstract JavaToolchainResolverRegistry getToolchainResolverRegistry();
public void apply(Settings settings) {
settings.getPlugins().apply("jvm-toolchain-management");
JavaToolchainResolverRegistry registry = getToolchainResolverRegistry();
registry.register(OracleOpenJdkToolchainResolver.class);
registry.register(EarlyAccessCatalogJdkToolchainResolver.class);
registry.register(AdoptiumJdkToolchainResolver.class);
registry.register(ArchivedOracleJdkToolchainResolver.class);
}
}
| JavaToolChainResolverPlugin |
java | elastic__elasticsearch | x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/rest/action/RestMonitoringMigrateAlertsAction.java | {
"start": 1124,
"end": 2229
} | class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(POST, "/_monitoring/migrate/alerts"));
}
@Override
public String getName() {
return "monitoring_migrate_alerts";
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
MonitoringMigrateAlertsRequest migrateRequest = new MonitoringMigrateAlertsRequest();
return channel -> client.execute(MonitoringMigrateAlertsAction.INSTANCE, migrateRequest, getRestBuilderListener(channel));
}
static RestBuilderListener<MonitoringMigrateAlertsResponse> getRestBuilderListener(RestChannel channel) {
return new RestBuilderListener<>(channel) {
@Override
public RestResponse buildResponse(MonitoringMigrateAlertsResponse response, XContentBuilder builder) throws Exception {
return new RestResponse(RestStatus.OK, response.toXContent(builder, ToXContent.EMPTY_PARAMS));
}
};
}
}
| RestMonitoringMigrateAlertsAction |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/vector/VectorWritables.java | {
"start": 612,
"end": 688
} | class ____ {
private VectorWritables() {
// Utility | VectorWritables |
java | dropwizard__dropwizard | dropwizard-benchmarks/src/main/java/io/dropwizard/benchmarks/jersey/SelfValidatingBenchmark.java | {
"start": 1136,
"end": 1727
} | class ____ {
@ValidationMethod
public boolean isValid1(String param1) {
return true;
}
@ValidationMethod
public boolean isValid2(String param1, int param2) {
return true;
}
@ValidationMethod(message = "invalid1")
public boolean isInvalid1(String param1) {
return false;
}
@ValidationMethod(message = "invalid2")
public boolean isInvalid2(String param1, int param2) {
return false;
}
}
@SelfValidating
public static | ValidationMethodUser |
java | apache__camel | components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpProducerFileExistAppendIT.java | {
"start": 1081,
"end": 2350
} | class ____ extends FtpServerTestSupport {
private static final boolean ON_WINDOWS = System.getProperty("os.name").startsWith("Windows");
private String getFtpUrl() {
return "ftp://admin@localhost:{{ftp.server.port}}/exist?password=admin&delay=2000&noop=true&fileExist=Append";
}
@BeforeEach
public void sendMessages() {
template.sendBodyAndHeader(getFtpUrl(), "Hello World\n", Exchange.FILE_NAME, "hello.txt");
}
@Test
public void testAppend() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
String expectBody = "Hello World\nBye World";
if (ON_WINDOWS) {
expectBody = "Hello World\r\nBye World";
}
mock.expectedBodiesReceived(expectBody);
mock.expectedFileExists(service.ftpFile("exist/hello.txt"), expectBody);
template.sendBodyAndHeader(getFtpUrl(), "Bye World", Exchange.FILE_NAME, "hello.txt");
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from(getFtpUrl()).to("mock:result");
}
};
}
}
| FtpProducerFileExistAppendIT |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/tvf/operator/UnalignedWindowTableFunctionOperator.java | {
"start": 21732,
"end": 23298
} | class ____
implements NamespaceAggsHandleFunctionBase<TimeWindow> {
private final IllegalStateException thrown =
new IllegalStateException(
"The function should not be called in DummyWindowAggregator");
@Override
public void open(StateDataViewStore store) throws Exception {}
@Override
public void setAccumulators(TimeWindow namespace, RowData accumulators) throws Exception {
throw thrown;
}
@Override
public void accumulate(RowData inputRow) throws Exception {
throw thrown;
}
@Override
public void retract(RowData inputRow) throws Exception {
throw thrown;
}
@Override
public void merge(TimeWindow namespace, RowData otherAcc) throws Exception {
throw thrown;
}
@Override
public RowData createAccumulators() throws Exception {
throw thrown;
}
@Override
public RowData getAccumulators() throws Exception {
throw thrown;
}
@Override
public void cleanup(TimeWindow namespace) throws Exception {
throw thrown;
}
@Override
public void close() throws Exception {}
}
@VisibleForTesting
public Counter getNumLateRecordsDropped() {
return numLateRecordsDropped;
}
@VisibleForTesting
public Gauge<Long> getWatermarkLatency() {
return watermarkLatency;
}
}
| DummyWindowAggregator |
java | apache__camel | components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/annotation/ConfigureTest.java | {
"start": 1527,
"end": 1793
} | class ____ {
@EndpointInject("mock:out")
MockEndpoint mock;
@EndpointInject("direct:in")
ProducerTemplate template;
@Configure
protected void configure(MainConfigurationProperties configuration) {
// Add the configuration | ConfigureTest |
java | apache__logging-log4j2 | log4j-jpa/src/main/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextStackAttributeConverter.java | {
"start": 1548,
"end": 2331
} | class ____ implements AttributeConverter<ThreadContext.ContextStack, String> {
@Override
public String convertToDatabaseColumn(final ThreadContext.ContextStack contextStack) {
if (contextStack == null) {
return null;
}
final StringBuilder builder = new StringBuilder();
for (final String value : contextStack.asList()) {
if (builder.length() > 0) {
builder.append('\n');
}
builder.append(value);
}
return builder.toString();
}
@Override
public ThreadContext.ContextStack convertToEntityAttribute(final String s) {
throw new UnsupportedOperationException("Log events can only be persisted, not extracted.");
}
}
| ContextStackAttributeConverter |
java | spring-projects__spring-framework | spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransport.java | {
"start": 5880,
"end": 6836
} | class ____ implements RequestCallback {
private final HttpHeaders headers;
private final @Nullable String body;
public XhrRequestCallback(HttpHeaders headers) {
this(headers, null);
}
public XhrRequestCallback(HttpHeaders headers, @Nullable String body) {
this.headers = headers;
this.body = body;
}
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
request.getHeaders().putAll(this.headers);
if (this.body != null) {
if (request instanceof StreamingHttpOutputMessage streamingOutputMessage) {
streamingOutputMessage.setBody(outputStream ->
StreamUtils.copy(this.body, SockJsFrame.CHARSET, outputStream));
}
else {
StreamUtils.copy(this.body, SockJsFrame.CHARSET, request.getBody());
}
}
}
}
/**
* Splits the body of an HTTP response into SockJS frames and delegates those
* to an {@link XhrClientSockJsSession}.
*/
private | XhrRequestCallback |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomInstantRevEntity.java | {
"start": 976,
"end": 2086
} | class ____ {
@Id
@GeneratedValue(generator = "EnversTestingRevisionGenerator")
@RevisionNumber
private int customId;
@RevisionTimestamp
private Instant instantTimestamp;
public int getCustomId() {
return customId;
}
public void setCustomId(int customId) {
this.customId = customId;
}
public Instant getInstantTimestamp() {
return instantTimestamp;
}
public void setInstantTimestamp(Instant instantTimestamp) {
this.instantTimestamp = instantTimestamp;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
CustomInstantRevEntity that = (CustomInstantRevEntity) o;
if ( customId != that.customId ) {
return false;
}
if ( instantTimestamp != null ? !instantTimestamp.equals( that.instantTimestamp ) : that.instantTimestamp != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = customId;
result = 31 * result + (instantTimestamp != null ? instantTimestamp.hashCode() : 0);
return result;
}
}
| CustomInstantRevEntity |
java | apache__camel | components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/WordpressComponent.java | {
"start": 1239,
"end": 3215
} | class ____ extends HealthCheckComponent {
private static final String OP_SEPARATOR = ":";
@Metadata(description = "Wordpress configuration")
private WordpressConfiguration configuration;
public WordpressComponent() {
this(new WordpressConfiguration());
}
public WordpressComponent(WordpressConfiguration configuration) {
this.configuration = configuration;
}
public WordpressComponent(CamelContext camelContext) {
super(camelContext);
this.configuration = new WordpressConfiguration();
}
public WordpressConfiguration getConfiguration() {
return configuration;
}
public void setConfiguration(WordpressConfiguration configuration) {
this.configuration = configuration;
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
if (configuration != null) {
// TODO: Better to make WordpressConfiguration cloneable
Map<String, Object> properties = new HashMap<>();
BeanIntrospection beanIntrospection = PluginHelper.getBeanIntrospection(getCamelContext());
beanIntrospection.getProperties(configuration, properties, null, false);
properties.forEach(parameters::putIfAbsent);
}
WordpressConfiguration config = new WordpressConfiguration();
WordpressEndpoint endpoint = new WordpressEndpoint(uri, this, config);
discoverOperations(endpoint, remaining);
setProperties(endpoint, parameters);
setProperties(config, parameters);
return endpoint;
}
private void discoverOperations(WordpressEndpoint endpoint, String remaining) {
final String[] operations = remaining.split(OP_SEPARATOR);
endpoint.setOperation(operations[0]);
if (operations.length > 1) {
endpoint.setOperationDetail(operations[1]);
}
}
}
| WordpressComponent |
java | apache__camel | components/camel-pqc/src/test/java/org/apache/camel/component/pqc/PQCFRODOGenerateEncapsulationAESTest.java | {
"start": 1630,
"end": 4781
} | class ____ extends CamelTestSupport {
@EndpointInject("mock:sign")
protected MockEndpoint resultSign;
@Produce("direct:sign")
protected ProducerTemplate templateSign;
@EndpointInject("mock:verify")
protected MockEndpoint resultVerify;
public PQCFRODOGenerateEncapsulationAESTest() throws NoSuchAlgorithmException {
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:sign").to("pqc:keyenc?operation=generateSecretKeyEncapsulation&symmetricKeyAlgorithm=AES")
.to("mock:sign")
.to("pqc:keyenc?operation=extractSecretKeyEncapsulation&symmetricKeyAlgorithm=AES").to("mock:verify");
}
};
}
@BeforeAll
public static void startup() throws Exception {
Security.addProvider(new BouncyCastleProvider());
Security.addProvider(new BouncyCastlePQCProvider());
}
@Test
void testSignAndVerify() throws Exception {
resultSign.expectedMessageCount(1);
resultVerify.expectedMessageCount(1);
templateSign.sendBody("Hello");
resultSign.assertIsSatisfied();
assertNotNull(resultSign.getExchanges().get(0).getMessage().getBody(SecretKeyWithEncapsulation.class));
assertEquals(PQCSymmetricAlgorithms.AES.getAlgorithm(),
resultSign.getExchanges().get(0).getMessage().getBody(SecretKeyWithEncapsulation.class).getAlgorithm());
SecretKeyWithEncapsulation secEncrypted
= resultSign.getExchanges().get(0).getMessage().getBody(SecretKeyWithEncapsulation.class);
assertNotNull(resultVerify.getExchanges().get(0).getMessage().getBody(SecretKeyWithEncapsulation.class));
assertEquals(PQCSymmetricAlgorithms.AES.getAlgorithm(),
resultVerify.getExchanges().get(0).getMessage().getBody(SecretKeyWithEncapsulation.class).getAlgorithm());
SecretKeyWithEncapsulation secEncryptedExtracted
= resultVerify.getExchanges().get(0).getMessage().getBody(SecretKeyWithEncapsulation.class);
assertTrue(Arrays.areEqual(secEncrypted.getEncoded(), secEncryptedExtracted.getEncoded()));
}
@BindToRegistry("Keypair")
public KeyPair setKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(PQCKeyEncapsulationAlgorithms.FRODO.getAlgorithm(),
PQCKeyEncapsulationAlgorithms.FRODO.getBcProvider());
kpg.initialize(FrodoParameterSpec.frodokem976aes, new SecureRandom());
KeyPair kp = kpg.generateKeyPair();
return kp;
}
@BindToRegistry("KeyGenerator")
public KeyGenerator setKeyGenerator()
throws NoSuchAlgorithmException, NoSuchProviderException {
KeyGenerator kg = KeyGenerator.getInstance(PQCKeyEncapsulationAlgorithms.FRODO.getAlgorithm(),
PQCKeyEncapsulationAlgorithms.FRODO.getBcProvider());
return kg;
}
}
| PQCFRODOGenerateEncapsulationAESTest |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringSeconds_create_Test.java | {
"start": 1274,
"end": 2731
} | class ____ {
@Test
void should_create_error_message_for_LocalTime() {
// GIVEN
ErrorMessageFactory factory = shouldBeEqualIgnoringSeconds(LocalTime.of(12, 0, 1), LocalTime.of(12, 0, 2));
// WHEN
String message = factory.create(new TestDescription("Test"), new StandardRepresentation());
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" 12:00:01%n" +
"to have same hour and minute as:%n" +
" 12:00:02%n" +
"but had not."));
}
@Test
void should_create_error_message_for_OffsetTime() {
// GIVEN
ErrorMessageFactory factory = shouldBeEqualIgnoringSeconds(OffsetTime.of(12, 0, 1, 0, ZoneOffset.UTC),
OffsetTime.of(12, 0, 2, 0, ZoneOffset.UTC));
// WHEN
String message = factory.create(new TestDescription("Test"), new StandardRepresentation());
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" 12:00:01Z%n" +
"to have same hour and minute as:%n" +
" 12:00:02Z%n" +
"but had not."));
}
}
| ShouldBeEqualIgnoringSeconds_create_Test |
java | quarkusio__quarkus | integration-tests/hibernate-search-orm-elasticsearch/src/main/java/io/quarkus/it/hibernate/search/orm/elasticsearch/propertyaccess/PropertyAccessTestResource.java | {
"start": 751,
"end": 7745
} | class ____ {
@Inject
EntityManager entityManager;
@Inject
SearchSession searchSession;
@Inject
UserTransaction transaction;
@GET
@Path("/private-field")
@Produces(MediaType.TEXT_PLAIN)
public String testPrivateFieldAccess() {
long id = 1L;
String value = "foo";
inTransaction(() -> assertThat(searchSession.search(PrivateFieldAccessEntity.class)
.where(f -> f.match().field("property")
.matching(value))
.fetchAllHits())
.isEmpty());
// While indexing, HSearch will read the entity property by calling a synthetic getter
inTransaction(() -> entityManager.persist(new PrivateFieldAccessEntity(id, value)));
inTransaction(() -> assertThat(searchSession.search(PrivateFieldAccessEntity.class)
.where(f -> f.match().field("property")
.matching(value))
.fetchAllHits())
.hasSize(1));
return "OK";
}
@GET
@Path("/private-field-lazy-init")
@Produces(MediaType.TEXT_PLAIN)
public String testPrivateFieldAccessLazyInitialization() {
long id = 2L;
String value = "bar";
inTransaction(() -> assertThat(searchSession.search(PrivateFieldAccessEntity.class)
.where(f -> f.match().field("property")
.matching(value))
.fetchAllHits())
.isEmpty());
inTransaction(() -> entityManager.persist(new PrivateFieldAccessEntity(id, value)));
inTransaction(() -> {
// "otherProperty" has no value in the index...
assertThat(searchSession.search(PrivateFieldAccessEntity.class)
.where(f -> f.match().field("otherProperty")
.matching(value))
.fetchAllHits())
.isEmpty();
// but "property" has.
assertThat(searchSession.search(PrivateFieldAccessEntity.class)
.where(f -> f.match().field("property")
.matching(value))
.fetchAllHits())
.hasSize(1);
});
// While indexing, HSearch will read the entity property by calling a synthetic getter,
// ensuring that it gets initialized automatically
inTransaction(() -> {
PrivateFieldAccessEntity entity = entityManager.getReference(PrivateFieldAccessEntity.class, id);
// The entity is not initialized
assertThat(entity)
.returns(false, e -> Hibernate.isPropertyInitialized(e, "property"))
.returns(false, e -> Hibernate.isPropertyInitialized(e, "otherProperty"));
// We update "otherProperty"
entity.setOtherProperty(value);
// Consequently, "otherProperty" is initialized,
// but "property" (which is in a different @LazyGroup) still isn't.
assertThat(entity)
.returns(false, e -> Hibernate.isPropertyInitialized(e, "property"));
});
inTransaction(() -> {
// "otherProperty" was updated in the index...
assertThat(searchSession.search(PrivateFieldAccessEntity.class)
.where(f -> f.match().field("otherProperty")
.matching(value))
.fetchAllHits())
.hasSize(1);
// and "property" still has a value, proving that it was lazily initialized upon indexing.
assertThat(searchSession.search(PrivateFieldAccessEntity.class)
.where(f -> f.match().field("property")
.matching(value))
.fetchAllHits())
.hasSize(1);
});
return "OK";
}
@GET
@Path("/method")
@Produces(MediaType.TEXT_PLAIN)
public String testMethodAccess() {
long id = 1L;
String value = "foo";
inTransaction(() -> assertThat(searchSession.search(MethodAccessEntity.class)
.where(f -> f.match().field("property")
.matching(value))
.fetchAllHits())
.isEmpty());
// While indexing, HSearch will read the entity property through its getter method
inTransaction(() -> entityManager.persist(new MethodAccessEntity(id, value)));
inTransaction(() -> assertThat(searchSession.search(MethodAccessEntity.class)
.where(f -> f.match().field("property")
.matching(value))
.fetchAllHits())
.hasSize(1));
return "OK";
}
@GET
@Path("/transient-method")
@Produces(MediaType.TEXT_PLAIN)
public String testTransientMethodAccess() {
long id = 1L;
String value1 = "foo1";
String value2 = "foo2";
inTransaction(() -> {
assertThat(searchSession.search(TransientMethodAccessEntity.class)
.where(f -> f.match().field("property")
.matching(value1))
.fetchAllHits())
.isEmpty();
assertThat(searchSession.search(TransientMethodAccessEntity.class)
.where(f -> f.match().field("property")
.matching(value2))
.fetchAllHits())
.isEmpty();
});
// While indexing, HSearch will read the (@Transient) entity property through its getter method
inTransaction(() -> entityManager.persist(new TransientMethodAccessEntity(id, value1, value2)));
inTransaction(() -> {
assertThat(searchSession.search(TransientMethodAccessEntity.class)
.where(f -> f.match().field("property")
.matching(value1))
.fetchAllHits())
.hasSize(1);
assertThat(searchSession.search(TransientMethodAccessEntity.class)
.where(f -> f.match().field("property")
.matching(value2))
.fetchAllHits())
.hasSize(1);
});
return "OK";
}
private void inTransaction(Runnable runnable) {
try {
transaction.begin();
try {
runnable.run();
transaction.commit();
} catch (Throwable t) {
try {
transaction.rollback();
} catch (RuntimeException e2) {
t.addSuppressed(e2);
}
throw t;
}
} catch (NotSupportedException | SystemException | RollbackException | HeuristicMixedException
| HeuristicRollbackException e) {
throw new IllegalStateException(e);
}
}
}
| PropertyAccessTestResource |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/ProactiveAuthCompletionExceptionHandlerTest.java | {
"start": 905,
"end": 2461
} | class ____ {
private static final String AUTHENTICATION_COMPLETION_EX = "AuthenticationCompletionException";
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest().setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(TestIdentityProvider.class, TestIdentityController.class,
CustomAuthCompletionExceptionHandler.class)
.addAsResource(new StringAsset("quarkus.http.auth.form.enabled=true\n"), "application.properties");
}
});
@BeforeAll
public static void setup() {
TestIdentityController.resetRoles().add("a d m i n", "a d m i n", "a d m i n");
}
@Test
public void testAuthCompletionExMapper() {
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
RestAssured
.given()
.filter(new CookieFilter())
.redirects().follow(false)
.when()
.formParam("j_username", "a d m i n")
.formParam("j_password", "a d m i n")
.cookie("quarkus-redirect-location", "https://quarkus.io/guides")
.post("/j_security_check")
.then()
.assertThat()
.statusCode(401)
.body(Matchers.equalTo(AUTHENTICATION_COMPLETION_EX));
}
@ApplicationScoped
public static final | ProactiveAuthCompletionExceptionHandlerTest |
java | netty__netty | codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2UnknownFrame.java | {
"start": 841,
"end": 3833
} | class ____ extends DefaultByteBufHolder implements Http2UnknownFrame {
private final byte frameType;
private final Http2Flags flags;
private Http2FrameStream stream;
public DefaultHttp2UnknownFrame(byte frameType, Http2Flags flags) {
this(frameType, flags, Unpooled.EMPTY_BUFFER);
}
public DefaultHttp2UnknownFrame(byte frameType, Http2Flags flags, ByteBuf data) {
super(data);
this.frameType = frameType;
this.flags = flags;
}
@Override
public Http2FrameStream stream() {
return stream;
}
@Override
public DefaultHttp2UnknownFrame stream(Http2FrameStream stream) {
this.stream = stream;
return this;
}
@Override
public byte frameType() {
return frameType;
}
@Override
public Http2Flags flags() {
return flags;
}
@Override
public String name() {
return "UNKNOWN";
}
@Override
public DefaultHttp2UnknownFrame copy() {
return replace(content().copy());
}
@Override
public DefaultHttp2UnknownFrame duplicate() {
return replace(content().duplicate());
}
@Override
public DefaultHttp2UnknownFrame retainedDuplicate() {
return replace(content().retainedDuplicate());
}
@Override
public DefaultHttp2UnknownFrame replace(ByteBuf content) {
return new DefaultHttp2UnknownFrame(frameType, flags, content).stream(stream);
}
@Override
public DefaultHttp2UnknownFrame retain() {
super.retain();
return this;
}
@Override
public DefaultHttp2UnknownFrame retain(int increment) {
super.retain(increment);
return this;
}
@Override
public String toString() {
return StringUtil.simpleClassName(this) + "(frameType=" + frameType + ", stream=" + stream +
", flags=" + flags + ", content=" + contentToString() + ')';
}
@Override
public DefaultHttp2UnknownFrame touch() {
super.touch();
return this;
}
@Override
public DefaultHttp2UnknownFrame touch(Object hint) {
super.touch(hint);
return this;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof DefaultHttp2UnknownFrame)) {
return false;
}
DefaultHttp2UnknownFrame other = (DefaultHttp2UnknownFrame) o;
Http2FrameStream otherStream = other.stream();
return (stream == otherStream || otherStream != null && otherStream.equals(stream))
&& flags.equals(other.flags())
&& frameType == other.frameType()
&& super.equals(other);
}
@Override
public int hashCode() {
int hash = super.hashCode();
hash = hash * 31 + frameType;
hash = hash * 31 + flags.hashCode();
if (stream != null) {
hash = hash * 31 + stream.hashCode();
}
return hash;
}
}
| DefaultHttp2UnknownFrame |
java | spring-projects__spring-security | saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson/Saml2PostAuthenticationRequestMixin.java | {
"start": 1093,
"end": 1464
} | class ____ in serialize/deserialize
* {@link Saml2PostAuthenticationRequest}.
*
* @author Sebastien Deleuze
* @author Ulrich Grave
* @since 7.0
* @see Saml2JacksonModule
* @see SecurityJacksonModules
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE)
| helps |
java | elastic__elasticsearch | x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/rest/RestForgetFollowerAction.java | {
"start": 825,
"end": 1919
} | class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(POST, "/{index}/_ccr/forget_follower"));
}
@Override
public String getName() {
return "forget_follower_action";
}
@Override
protected RestChannelConsumer prepareRequest(final RestRequest restRequest, final NodeClient client) throws IOException {
final Request request = createRequest(restRequest, restRequest.param("index"));
return channel -> client.execute(ForgetFollowerAction.INSTANCE, request, new RestToXContentListener<>(channel));
}
private static Request createRequest(final RestRequest restRequest, final String leaderIndex) throws IOException {
try (XContentParser parser = restRequest.contentOrSourceParamParser()) {
Request request = Request.fromXContent(parser, leaderIndex);
if (restRequest.hasParam("timeout")) {
request.timeout(restRequest.paramAsTime("timeout", null));
}
return request;
}
}
}
| RestForgetFollowerAction |
java | apache__camel | dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java | {
"start": 16144,
"end": 17330
} | class ____ extends YamlDeserializerSupport {
private ModelDeserializers() {
}
@YamlType(
nodes = "asn1",
inline = true,
types = org.apache.camel.model.dataformat.ASN1DataFormat.class,
order = org.apache.camel.dsl.yaml.common.YamlDeserializerResolver.ORDER_LOWEST - 1,
displayName = "ASN.1 File",
description = "Encode and decode data structures using Abstract Syntax Notation One (ASN.1).",
deprecated = false,
properties = {
@YamlProperty(name = "id", type = "string", description = "The id of this node", displayName = "Id"),
@YamlProperty(name = "unmarshalType", type = "string", description = "Class to use when unmarshalling.", displayName = "Unmarshal Type"),
@YamlProperty(name = "usingIterator", type = "boolean", defaultValue = "false", description = "If the asn1 file has more than one entry, the setting this option to true, allows working with the splitter EIP, to split the data using an iterator in a streaming mode.", displayName = "Using Iterator")
}
)
public static | ModelDeserializers |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java | {
"start": 99202,
"end": 99918
} | class ____ {
@Autowired
MockWebServer web;
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
String issuerOne = this.web.url("/issuerOne").toString();
String issuerTwo = this.web.url("/issuerTwo").toString();
JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = JwtIssuerAuthenticationManagerResolver
.fromTrustedIssuers(issuerOne, issuerTwo);
// @formatter:off
http
.oauth2ResourceServer((server) -> server
.authenticationManagerResolver(authenticationManagerResolver))
.anonymous(AbstractHttpConfigurer::disable);
return http.build();
// @formatter:on
}
}
@Configuration
@EnableWebSecurity
static | MultipleIssuersConfig |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/utils/ChildFirstClassLoader.java | {
"start": 1266,
"end": 4716
} | class ____ extends URLClassLoader {
static {
ClassLoader.registerAsParallelCapable();
}
/**
* @param classPath Class path string
* @param parent The parent classloader. If the required class / resource cannot be found in the given classPath,
* this classloader will be used to find the class / resource.
*/
public ChildFirstClassLoader(String classPath, ClassLoader parent) {
super(classpathToURLs(classPath), parent);
}
private static URL[] classpathToURLs(String classPath) {
ArrayList<URL> urls = new ArrayList<>();
for (String path : classPath.split(File.pathSeparator)) {
if (path.trim().isEmpty())
continue;
File file = new File(path);
try {
if (path.endsWith("/*")) {
File parent = new File(new File(file.getCanonicalPath()).getParent());
if (parent.isDirectory()) {
File[] files = parent.listFiles((dir, name) -> {
String lower = name.toLowerCase(Locale.ROOT);
return lower.endsWith(".jar") || lower.endsWith(".zip");
});
if (files != null) {
for (File jarFile : files) {
urls.add(jarFile.getCanonicalFile().toURI().toURL());
}
}
}
} else if (file.exists()) {
urls.add(file.getCanonicalFile().toURI().toURL());
}
} catch (IOException e) {
throw new KafkaException(e);
}
}
return urls.toArray(new URL[0]);
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> c = findLoadedClass(name);
if (c == null) {
try {
c = findClass(name);
} catch (ClassNotFoundException e) {
// Try parent
c = super.loadClass(name, false);
}
}
if (resolve)
resolveClass(c);
return c;
}
}
@Override
public URL getResource(String name) {
URL url = findResource(name);
if (url == null) {
// try parent
url = super.getResource(name);
}
return url;
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
Enumeration<URL> urls1 = findResources(name);
Enumeration<URL> urls2 = getParent() != null ? getParent().getResources(name) : null;
return new Enumeration<>() {
@Override
public boolean hasMoreElements() {
return (urls1 != null && urls1.hasMoreElements()) || (urls2 != null && urls2.hasMoreElements());
}
@Override
public URL nextElement() {
if (urls1 != null && urls1.hasMoreElements())
return urls1.nextElement();
if (urls2 != null && urls2.hasMoreElements())
return urls2.nextElement();
throw new NoSuchElementException();
}
};
}
}
| ChildFirstClassLoader |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalIsNullTest.java | {
"start": 185,
"end": 483
} | class ____ extends TestCase {
public void test_null() throws Exception {
assertEquals(false, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? is null", 0));
assertEquals(true, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? is null", (Object) null));
}
}
| EvalIsNullTest |
java | elastic__elasticsearch | modules/lang-expression/src/main/java/org/elasticsearch/script/expression/ReplaceableConstDoubleValues.java | {
"start": 708,
"end": 1029
} | class ____ extends DoubleValues {
private double value = 0;
void setValue(double value) {
this.value = value;
}
@Override
public double doubleValue() {
return value;
}
@Override
public boolean advanceExact(int doc) {
return true;
}
}
| ReplaceableConstDoubleValues |
java | spring-projects__spring-security | oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/support/OAuth2WebClientHttpServiceGroupConfigurerTests.java | {
"start": 1629,
"end": 3108
} | class ____ {
@Mock
private OAuth2AuthorizedClientManager authoriedClientManager;
@Mock
private HttpServiceGroupConfigurer.Groups<WebClient.Builder> groups;
@Captor
ArgumentCaptor<HttpServiceGroupConfigurer.ProxyFactoryCallback> forProxyFactory;
@Mock
private HttpServiceProxyFactory.Builder factoryBuilder;
@Captor
private ArgumentCaptor<HttpServiceGroupConfigurer.ClientCallback<WebClient.Builder>> configureClient;
@Mock
private WebClient.Builder clientBuilder;
@Test
void configureGroupsConfigureProxyFactory() {
OAuth2WebClientHttpServiceGroupConfigurer configurer = OAuth2WebClientHttpServiceGroupConfigurer
.from(this.authoriedClientManager);
configurer.configureGroups(this.groups);
verify(this.groups).forEachProxyFactory(this.forProxyFactory.capture());
this.forProxyFactory.getValue().withProxyFactory(null, this.factoryBuilder);
verify(this.factoryBuilder).httpRequestValuesProcessor(ClientRegistrationIdProcessor.DEFAULT_INSTANCE);
}
@Test
void configureGroupsConfigureClient() {
OAuth2WebClientHttpServiceGroupConfigurer configurer = OAuth2WebClientHttpServiceGroupConfigurer
.from(this.authoriedClientManager);
configurer.configureGroups(this.groups);
verify(this.groups).forEachClient(this.configureClient.capture());
this.configureClient.getValue().withClient(null, this.clientBuilder);
verify(this.clientBuilder).filter(any(ExchangeFilterFunction.class));
}
}
| OAuth2WebClientHttpServiceGroupConfigurerTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/RxReturnValueIgnoredTest.java | {
"start": 1386,
"end": 1573
} | class ____<T> {}
""" //
)
.addSourceLines(
"rx1/Completable.java",
"""
package rx;
public | Single |
java | micronaut-projects__micronaut-core | http-client/src/main/java/io/micronaut/http/client/netty/Pool40.java | {
"start": 1845,
"end": 2100
} | class ____ of various mutator methods (e.g. {@link #addPendingRequest}) that
* may be called concurrently and in a reentrant fashion (e.g. inside {@link #openNewConnection}).
* These mutator methods update their respective fields and then mark this | consists |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/snapshots/ShardSnapshotStatusWireSerializationTests.java | {
"start": 934,
"end": 6172
} | class ____ extends AbstractWireSerializingTestCase<SnapshotsInProgress.ShardSnapshotStatus> {
@Override
protected Writeable.Reader<SnapshotsInProgress.ShardSnapshotStatus> instanceReader() {
return SnapshotsInProgress.ShardSnapshotStatus::readFrom;
}
@Override
protected SnapshotsInProgress.ShardSnapshotStatus createTestInstance() {
final SnapshotsInProgress.ShardState shardState = randomFrom(SnapshotsInProgress.ShardState.values());
final String nodeId = randomAlphaOfLength(5);
if (shardState == SnapshotsInProgress.ShardState.QUEUED) {
return SnapshotsInProgress.ShardSnapshotStatus.UNASSIGNED_QUEUED;
} else if (shardState == SnapshotsInProgress.ShardState.SUCCESS) {
return SnapshotsInProgress.ShardSnapshotStatus.success(nodeId, randomShardSnapshotResult());
} else {
final String reason = shardState.failed() ? randomAlphaOfLength(10) : null;
return new SnapshotsInProgress.ShardSnapshotStatus(nodeId, shardState, ShardGeneration.newGeneration(), reason);
}
}
@Override
protected SnapshotsInProgress.ShardSnapshotStatus mutateInstance(SnapshotsInProgress.ShardSnapshotStatus instance) {
if (instance.state() == SnapshotsInProgress.ShardState.QUEUED) {
assert instance == SnapshotsInProgress.ShardSnapshotStatus.UNASSIGNED_QUEUED;
return randomValueOtherThanMany(i -> i.state() == SnapshotsInProgress.ShardState.QUEUED, this::createTestInstance);
}
final SnapshotsInProgress.ShardState newState = randomFrom(SnapshotsInProgress.ShardState.values());
if (newState == SnapshotsInProgress.ShardState.QUEUED) {
return SnapshotsInProgress.ShardSnapshotStatus.UNASSIGNED_QUEUED;
} else if (newState == SnapshotsInProgress.ShardState.SUCCESS) {
if (instance.state() == SnapshotsInProgress.ShardState.SUCCESS) {
assert instance.shardSnapshotResult() != null;
if (randomBoolean()) {
return SnapshotsInProgress.ShardSnapshotStatus.success(
randomAlphaOfLength(11 - instance.nodeId().length()),
instance.shardSnapshotResult()
);
} else {
return SnapshotsInProgress.ShardSnapshotStatus.success(
instance.nodeId(),
ShardSnapshotResultWireSerializationTests.mutateShardSnapshotResult(instance.shardSnapshotResult())
);
}
} else {
return SnapshotsInProgress.ShardSnapshotStatus.success(instance.nodeId(), randomShardSnapshotResult());
}
} else if (newState.failed() && instance.state().failed() && randomBoolean()) {
return new SnapshotsInProgress.ShardSnapshotStatus(
instance.nodeId(),
newState,
instance.generation(),
randomAlphaOfLength(15 - instance.reason().length())
);
} else {
final String reason = newState.failed() ? randomAlphaOfLength(10) : null;
if (newState != instance.state() && randomBoolean()) {
return new SnapshotsInProgress.ShardSnapshotStatus(instance.nodeId(), newState, instance.generation(), reason);
} else if (randomBoolean()) {
return new SnapshotsInProgress.ShardSnapshotStatus(
randomAlphaOfLength(11 - instance.nodeId().length()),
newState,
instance.generation(),
reason
);
} else {
return new SnapshotsInProgress.ShardSnapshotStatus(
instance.nodeId(),
newState,
randomValueOtherThan(instance.generation(), ShardGeneration::newGeneration),
reason
);
}
}
}
@Override
protected void assertEqualInstances(
SnapshotsInProgress.ShardSnapshotStatus expectedInstance,
SnapshotsInProgress.ShardSnapshotStatus newInstance
) {
if (newInstance.state() == SnapshotsInProgress.ShardState.QUEUED) {
assertSame(newInstance, expectedInstance);
} else {
assertNotSame(newInstance, expectedInstance);
}
assertThat(expectedInstance, Matchers.equalTo(newInstance));
assertEquals(expectedInstance.hashCode(), newInstance.hashCode());
}
public void testToString() {
final SnapshotsInProgress.ShardSnapshotStatus testInstance = createTestInstance();
if (testInstance.nodeId() != null) {
assertThat(testInstance.toString(), containsString(testInstance.nodeId()));
}
if (testInstance.generation() != null) {
assertThat(testInstance.toString(), containsString(testInstance.generation().toString()));
}
if (testInstance.state() == SnapshotsInProgress.ShardState.SUCCESS) {
assertThat(testInstance.toString(), containsString(testInstance.shardSnapshotResult().toString()));
}
}
}
| ShardSnapshotStatusWireSerializationTests |
java | apache__flink | flink-clients/src/test/java/org/apache/flink/client/cli/CliFrontendPackageProgramTest.java | {
"start": 2258,
"end": 11028
} | class ____ {
private CliFrontend frontend;
@BeforeAll
static void init() {
CliFrontendTestUtils.pipeSystemOutToNull();
}
@AfterAll
static void shutdown() {
CliFrontendTestUtils.restoreSystemOut();
}
@BeforeEach
void setup() {
final Configuration configuration = new Configuration();
frontend = new CliFrontend(configuration, Collections.singletonList(new DefaultCLI()));
}
@Test
void testNonExistingJarFile() {
ProgramOptions programOptions = mock(ProgramOptions.class);
when(programOptions.getJarFilePath()).thenReturn("/some/none/existing/path");
assertThatThrownBy(() -> frontend.buildProgram(programOptions))
.isInstanceOf(FileNotFoundException.class);
}
@Test
void testFileNotJarFile() {
ProgramOptions programOptions = mock(ProgramOptions.class);
when(programOptions.getJarFilePath()).thenReturn(getNonJarFilePath());
when(programOptions.getProgramArgs()).thenReturn(new String[0]);
when(programOptions.getSavepointRestoreSettings())
.thenReturn(SavepointRestoreSettings.none());
assertThatThrownBy(() -> frontend.buildProgram(programOptions))
.isInstanceOf(ProgramInvocationException.class);
}
@Test
void testVariantWithExplicitJarAndArgumentsOption() throws Exception {
String[] arguments = {
"--classpath",
"file:///tmp/foo",
"--classpath",
"file:///tmp/bar",
"-j",
getTestJarPath(),
"-a",
"--debug",
"true",
"arg1",
"arg2"
};
URL[] classpath = new URL[] {new URL("file:///tmp/foo"), new URL("file:///tmp/bar")};
String[] reducedArguments = new String[] {"--debug", "true", "arg1", "arg2"};
CommandLine commandLine =
CliFrontendParser.parse(CliFrontendParser.RUN_OPTIONS, arguments, true);
ProgramOptions programOptions = ProgramOptions.create(commandLine);
assertThat(programOptions.getJarFilePath()).isEqualTo(getTestJarPath());
assertThat(programOptions.getClasspaths().toArray()).isEqualTo(classpath);
assertThat(programOptions.getProgramArgs()).isEqualTo(reducedArguments);
PackagedProgram prog = frontend.buildProgram(programOptions);
assertThat(prog.getArguments()).isEqualTo(reducedArguments);
assertThat(prog.getMainClassName()).isEqualTo(TEST_JAR_MAIN_CLASS);
}
@Test
void testVariantWithExplicitJarAndNoArgumentsOption() throws Exception {
String[] arguments = {
"--classpath",
"file:///tmp/foo",
"--classpath",
"file:///tmp/bar",
"-j",
getTestJarPath(),
"--debug",
"true",
"arg1",
"arg2"
};
URL[] classpath = new URL[] {new URL("file:///tmp/foo"), new URL("file:///tmp/bar")};
String[] reducedArguments = new String[] {"--debug", "true", "arg1", "arg2"};
CommandLine commandLine =
CliFrontendParser.parse(CliFrontendParser.RUN_OPTIONS, arguments, true);
ProgramOptions programOptions = ProgramOptions.create(commandLine);
assertThat(programOptions.getJarFilePath()).isEqualTo(getTestJarPath());
assertThat(programOptions.getClasspaths().toArray()).isEqualTo(classpath);
assertThat(programOptions.getProgramArgs()).isEqualTo(reducedArguments);
PackagedProgram prog = frontend.buildProgram(programOptions);
assertThat(prog.getArguments()).isEqualTo(reducedArguments);
assertThat(prog.getMainClassName()).isEqualTo(TEST_JAR_MAIN_CLASS);
}
@Test
void testValidVariantWithNoJarAndNoArgumentsOption() throws Exception {
String[] arguments = {
"--classpath",
"file:///tmp/foo",
"--classpath",
"file:///tmp/bar",
getTestJarPath(),
"--debug",
"true",
"arg1",
"arg2"
};
URL[] classpath = new URL[] {new URL("file:///tmp/foo"), new URL("file:///tmp/bar")};
String[] reducedArguments = {"--debug", "true", "arg1", "arg2"};
CommandLine commandLine =
CliFrontendParser.parse(CliFrontendParser.RUN_OPTIONS, arguments, true);
ProgramOptions programOptions = ProgramOptions.create(commandLine);
assertThat(programOptions.getJarFilePath()).isEqualTo(getTestJarPath());
assertThat(programOptions.getClasspaths().toArray()).isEqualTo(classpath);
assertThat(programOptions.getProgramArgs()).isEqualTo(reducedArguments);
PackagedProgram prog = frontend.buildProgram(programOptions);
assertThat(prog.getArguments()).isEqualTo(reducedArguments);
assertThat(prog.getMainClassName()).isEqualTo(TEST_JAR_MAIN_CLASS);
}
@Test
void testNoJarNoArgumentsAtAll() {
assertThatThrownBy(() -> frontend.run(new String[0])).isInstanceOf(CliArgsException.class);
}
@Test
void testNonExistingFileWithArguments() throws Exception {
String[] arguments = {
"--classpath",
"file:///tmp/foo",
"--classpath",
"file:///tmp/bar",
"/some/none/existing/path",
"--debug",
"true",
"arg1",
"arg2"
};
URL[] classpath = new URL[] {new URL("file:///tmp/foo"), new URL("file:///tmp/bar")};
String[] reducedArguments = {"--debug", "true", "arg1", "arg2"};
CommandLine commandLine =
CliFrontendParser.parse(CliFrontendParser.RUN_OPTIONS, arguments, true);
ProgramOptions programOptions = ProgramOptions.create(commandLine);
assertThat(programOptions.getJarFilePath()).isEqualTo(arguments[4]);
assertThat(programOptions.getClasspaths().toArray()).isEqualTo(classpath);
assertThat(programOptions.getProgramArgs()).isEqualTo(reducedArguments);
assertThatThrownBy(() -> frontend.buildProgram(programOptions))
.isInstanceOf(FileNotFoundException.class);
}
@Test
void testNonExistingFileWithoutArguments() throws Exception {
String[] arguments = {"/some/none/existing/path"};
CommandLine commandLine =
CliFrontendParser.parse(CliFrontendParser.RUN_OPTIONS, arguments, true);
ProgramOptions programOptions = ProgramOptions.create(commandLine);
assertThat(programOptions.getJarFilePath()).isEqualTo(arguments[0]);
assertThat(programOptions.getProgramArgs()).isEqualTo(new String[0]);
try {
frontend.buildProgram(programOptions);
} catch (FileNotFoundException e) {
// that's what we want
}
}
/**
* Ensure that we will never have the following error.
*
* <pre>
* org.apache.flink.client.program.ProgramInvocationException: The main method caused an error.
* at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:398)
* at org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:301)
* at org.apache.flink.client.program.Client.getOptimizedPlan(Client.java:140)
* at org.apache.flink.client.program.Client.getOptimizedPlanAsJson(Client.java:125)
* at org.apache.flink.client.cli.CliFrontend.info(CliFrontend.java:439)
* at org.apache.flink.client.cli.CliFrontend.parseParameters(CliFrontend.java:931)
* at org.apache.flink.client.cli.CliFrontend.main(CliFrontend.java:951)
* Caused by: java.io.IOException: java.lang.RuntimeException: java.lang.ClassNotFoundException: org.apache.hadoop.hive.ql.io.RCFileInputFormat
* at org.apache.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:102)
* at org.apache.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:54)
* at tlabs.CDR_In_Report.createHCatInputFormat(CDR_In_Report.java:322)
* at tlabs.CDR_Out_Report.main(CDR_Out_Report.java:380)
* at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
* at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
* at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
* at java.lang.reflect.Method.invoke(Method.java:622)
* at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:383)
* </pre>
*
* <p>The test works as follows:
*
* <ul>
* <li>Use the CliFrontend to invoke a jar file that loads a | CliFrontendPackageProgramTest |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/async/MyAsyncProducer.java | {
"start": 1197,
"end": 3025
} | class ____ extends DefaultAsyncProducer {
private static final Logger LOG = LoggerFactory.getLogger(MyAsyncProducer.class);
private final ExecutorService executor;
private final AtomicInteger counter = new AtomicInteger();
public MyAsyncProducer(MyAsyncEndpoint endpoint) {
super(endpoint);
this.executor = endpoint.getCamelContext().getExecutorServiceManager().newDefaultThreadPool(this, "MyProducer");
}
@Override
public MyAsyncEndpoint getEndpoint() {
return (MyAsyncEndpoint) super.getEndpoint();
}
@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
executor.submit(() -> {
LOG.info("Simulating a task which takes {} millis to reply", getEndpoint().getDelay());
Thread.sleep(getEndpoint().getDelay());
int count = counter.incrementAndGet();
if (getEndpoint().getFailFirstAttempts() >= count) {
LOG.info("Simulating a failure at attempt {}", count);
exchange.setException(new CamelExchangeException("Simulated error at attempt " + count, exchange));
} else {
String reply = getEndpoint().getReply();
exchange.getMessage().setBody(reply);
// propagate headers
exchange.getMessage().setHeaders(exchange.getIn().getHeaders());
LOG.info("Setting reply {}", reply);
}
LOG.info("Callback done(false)");
callback.done(false);
return null;
});
// indicate from this point forward its being routed asynchronously
LOG.info("Task submitted, now tell Camel routing engine to that this Exchange is being continued asynchronously");
return false;
}
}
| MyAsyncProducer |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/CteGenerateSeriesFunction.java | {
"start": 15441,
"end": 16758
} | class ____ extends NumberSeriesGenerateSeriesSetReturningFunctionTypeResolver {
public CteGenerateSeriesSetReturningFunctionTypeResolver() {
super( "v", "i" );
}
public CteGenerateSeriesSetReturningFunctionTypeResolver(@Nullable String defaultValueColumnName, String defaultIndexSelectionExpression) {
super( defaultValueColumnName, defaultIndexSelectionExpression );
}
@Override
public SelectableMapping[] resolveFunctionReturnType(
List<? extends SqlAstNode> arguments,
String tableIdentifierVariable,
boolean lateral,
boolean withOrdinality,
SqmToSqlAstConverter converter) {
if ( !lateral ) {
return super.resolveFunctionReturnType( arguments, tableIdentifierVariable, lateral, withOrdinality, converter );
}
else {
return resolveIterationVariableBasedFunctionReturnType( arguments, tableIdentifierVariable, lateral, withOrdinality, converter );
}
}
}
@Override
protected void renderGenerateSeries(
SqlAppender sqlAppender,
Expression start,
Expression stop,
@Nullable Expression step,
AnonymousTupleTableGroupProducer tupleType,
String tableIdentifierVariable,
SqlAstTranslator<?> walker) {
throw new UnsupportedOperationException( "Function expands to custom SQL AST" );
}
}
| CteGenerateSeriesSetReturningFunctionTypeResolver |
java | apache__rocketmq | test/src/test/java/org/apache/rocketmq/test/client/producer/order/OrderMsgWithTagIT.java | {
"start": 1586,
"end": 6746
} | class ____ extends BaseConf {
private static Logger logger = LoggerFactory.getLogger(OrderMsgIT.class);
private RMQNormalProducer producer = null;
private String topic = null;
@Before
public void setUp() {
topic = initTopic();
logger.info(String.format("use topic: %s;", topic));
producer = getProducer(NAMESRV_ADDR, topic);
}
@After
public void tearDown() {
shutdown();
}
@Test
public void testOrderMsgWithTagSubAll() {
int msgSize = 10;
String tag = "jueyin_tag";
RMQNormalConsumer consumer = getConsumer(NAMESRV_ADDR, topic, "*", new RMQOrderListener());
List<MessageQueue> mqs = producer.getMessageQueue();
MessageQueueMsg mqMsgs = new MessageQueueMsg(mqs, msgSize, tag);
producer.send(mqMsgs.getMsgsWithMQ());
consumer.getListener().waitForMessageConsume(producer.getAllMsgBody(), CONSUME_TIME);
assertThat(VerifyUtils.getFilterdMessage(producer.getAllMsgBody(),
consumer.getListener().getAllMsgBody()))
.containsExactlyElementsIn(mqMsgs.getMsgBodys());
assertThat(VerifyUtils.verifyOrder(((RMQOrderListener) consumer.getListener()).getMsgs()))
.isEqualTo(true);
}
@Test
public void testOrderMsgWithTagSubTag() {
int msgSize = 5;
String tag = "jueyin_tag";
RMQNormalConsumer consumer = getConsumer(NAMESRV_ADDR, topic, tag, new RMQOrderListener());
List<MessageQueue> mqs = producer.getMessageQueue();
MessageQueueMsg mqMsgs = new MessageQueueMsg(mqs, msgSize, tag);
producer.send(mqMsgs.getMsgsWithMQ());
consumer.getListener().waitForMessageConsume(producer.getAllMsgBody(), CONSUME_TIME);
assertThat(VerifyUtils.getFilterdMessage(producer.getAllMsgBody(),
consumer.getListener().getAllMsgBody()))
.containsExactlyElementsIn(mqMsgs.getMsgBodys());
assertThat(VerifyUtils.verifyOrder(((RMQOrderListener) consumer.getListener()).getMsgs()))
.isEqualTo(true);
}
@Test
public void testOrderMsgWithTag1AndTag2SubTag1() {
int msgSize = 5;
String tag1 = "jueyin_tag_1";
String tag2 = "jueyin_tag_2";
RMQNormalConsumer consumer = getConsumer(NAMESRV_ADDR, topic, tag1, new RMQOrderListener());
List<MessageQueue> mqs = producer.getMessageQueue();
MessageQueueMsg mqMsgs = new MessageQueueMsg(mqs, msgSize, tag2);
producer.send(mqMsgs.getMsgsWithMQ());
producer.clearMsg();
mqMsgs = new MessageQueueMsg(mqs, msgSize, tag1);
producer.send(mqMsgs.getMsgsWithMQ());
consumer.getListener().waitForMessageConsume(producer.getAllMsgBody(), CONSUME_TIME);
assertThat(VerifyUtils.getFilterdMessage(producer.getAllMsgBody(),
consumer.getListener().getAllMsgBody()))
.containsExactlyElementsIn(mqMsgs.getMsgBodys());
assertThat(VerifyUtils.verifyOrder(((RMQOrderListener) consumer.getListener()).getMsgs()))
.isEqualTo(true);
}
@Test
public void testTwoConsumerSubTag() {
int msgSize = 10;
String tag1 = "jueyin_tag_1";
String tag2 = "jueyin_tag_2";
RMQNormalConsumer consumer1 = getConsumer(NAMESRV_ADDR, topic, tag1,
new RMQOrderListener("consumer1"));
RMQNormalConsumer consumer2 = getConsumer(NAMESRV_ADDR, topic, tag2,
new RMQOrderListener("consumer2"));
List<MessageQueue> mqs = producer.getMessageQueue();
MessageQueueMsg mqMsgs = new MessageQueueMsg(mqs, msgSize, tag1);
producer.send(mqMsgs.getMsgsWithMQ());
mqMsgs = new MessageQueueMsg(mqs, msgSize, tag2);
producer.send(mqMsgs.getMsgsWithMQ());
boolean recvAll = MQWait.waitConsumeAll(CONSUME_TIME, producer.getAllMsgBody(),
consumer1.getListener(), consumer2.getListener());
assertThat(recvAll).isEqualTo(true);
assertThat(VerifyUtils.verifyOrder(((RMQOrderListener) consumer1.getListener()).getMsgs()))
.isEqualTo(true);
assertThat(VerifyUtils.verifyOrder(((RMQOrderListener) consumer2.getListener()).getMsgs()))
.isEqualTo(true);
}
@Test
public void testConsumeTwoTag() {
int msgSize = 10;
String tag1 = "jueyin_tag_1";
String tag2 = "jueyin_tag_2";
RMQNormalConsumer consumer = getConsumer(NAMESRV_ADDR, topic,
String.format("%s||%s", tag1, tag2), new RMQOrderListener());
List<MessageQueue> mqs = producer.getMessageQueue();
MessageQueueMsg mqMsgs = new MessageQueueMsg(mqs, msgSize, tag1);
producer.send(mqMsgs.getMsgsWithMQ());
mqMsgs = new MessageQueueMsg(mqs, msgSize, tag2);
producer.send(mqMsgs.getMsgsWithMQ());
boolean recvAll = MQWait.waitConsumeAll(CONSUME_TIME, producer.getAllMsgBody(),
consumer.getListener());
assertThat(recvAll).isEqualTo(true);
assertThat(VerifyUtils.verifyOrder(((RMQOrderListener) consumer.getListener()).getMsgs()))
.isEqualTo(true);
}
}
| OrderMsgWithTagIT |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/objects/Objects_assertIsNotExactlyInstanceOf_Test.java | {
"start": 1506,
"end": 2747
} | class ____ extends ObjectsBaseTest {
@Test
void should_pass_if_actual_is_not_exactly_instance_of_type() {
objects.assertIsNotExactlyInstanceOf(someInfo(), "Yoda", Object.class);
}
@Test
void should_throw_error_if_type_is_null() {
assertThatNullPointerException().isThrownBy(() -> objects.assertIsNotExactlyInstanceOf(someInfo(), "Yoda", null))
.withMessage("The given type should not be null");
}
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> objects.assertIsNotExactlyInstanceOf(someInfo(), null,
String.class))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_actual_is_exactly_instance_of_type() {
AssertionInfo info = someInfo();
Throwable error = catchThrowable(() -> objects.assertIsNotExactlyInstanceOf(info, "Yoda", String.class));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldNotBeExactlyInstance("Yoda", String.class));
}
}
| Objects_assertIsNotExactlyInstanceOf_Test |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/cglib/transform/impl/AbstractInterceptFieldCallback.java | {
"start": 711,
"end": 2734
} | class ____ implements InterceptFieldCallback {
@Override
public int writeInt(Object obj, String name, int oldValue, int newValue) { return newValue; }
@Override
public char writeChar(Object obj, String name, char oldValue, char newValue) { return newValue; }
@Override
public byte writeByte(Object obj, String name, byte oldValue, byte newValue) { return newValue; }
@Override
public boolean writeBoolean(Object obj, String name, boolean oldValue, boolean newValue) { return newValue; }
@Override
public short writeShort(Object obj, String name, short oldValue, short newValue) { return newValue; }
@Override
public float writeFloat(Object obj, String name, float oldValue, float newValue) { return newValue; }
@Override
public double writeDouble(Object obj, String name, double oldValue, double newValue) { return newValue; }
@Override
public long writeLong(Object obj, String name, long oldValue, long newValue) { return newValue; }
@Override
public Object writeObject(Object obj, String name, Object oldValue, Object newValue) { return newValue; }
@Override
public int readInt(Object obj, String name, int oldValue) { return oldValue; }
@Override
public char readChar(Object obj, String name, char oldValue) { return oldValue; }
@Override
public byte readByte(Object obj, String name, byte oldValue) { return oldValue; }
@Override
public boolean readBoolean(Object obj, String name, boolean oldValue) { return oldValue; }
@Override
public short readShort(Object obj, String name, short oldValue) { return oldValue; }
@Override
public float readFloat(Object obj, String name, float oldValue) { return oldValue; }
@Override
public double readDouble(Object obj, String name, double oldValue) { return oldValue; }
@Override
public long readLong(Object obj, String name, long oldValue) { return oldValue; }
@Override
public Object readObject(Object obj, String name, Object oldValue) { return oldValue; }
}
| AbstractInterceptFieldCallback |
java | apache__logging-log4j2 | log4j-osgi-test/src/test/java/org/apache/logging/log4j/osgi/tests/EquinoxLoadApiBundleTest.java | {
"start": 985,
"end": 1135
} | class ____ extends AbstractLoadBundleTest {
public EquinoxLoadApiBundleTest() {
super(new EquinoxFactory());
}
}
| EquinoxLoadApiBundleTest |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeFilterSingle.java | {
"start": 1577,
"end": 3064
} | class ____<T> implements SingleObserver<T>, Disposable {
final MaybeObserver<? super T> downstream;
final Predicate<? super T> predicate;
Disposable upstream;
FilterMaybeObserver(MaybeObserver<? super T> actual, Predicate<? super T> predicate) {
this.downstream = actual;
this.predicate = predicate;
}
@Override
public void dispose() {
Disposable d = this.upstream;
this.upstream = DisposableHelper.DISPOSED;
d.dispose();
}
@Override
public boolean isDisposed() {
return upstream.isDisposed();
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.upstream, d)) {
this.upstream = d;
downstream.onSubscribe(this);
}
}
@Override
public void onSuccess(T value) {
boolean b;
try {
b = predicate.test(value);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
downstream.onError(ex);
return;
}
if (b) {
downstream.onSuccess(value);
} else {
downstream.onComplete();
}
}
@Override
public void onError(Throwable e) {
downstream.onError(e);
}
}
}
| FilterMaybeObserver |
java | spring-projects__spring-boot | module/spring-boot-restclient-test/src/main/java/org/springframework/boot/restclient/test/MockServerRestTemplateCustomizer.java | {
"start": 2723,
"end": 3388
} | class ____ implements RestTemplateCustomizer {
private final Map<RestTemplate, RequestExpectationManager> expectationManagers = new ConcurrentHashMap<>();
private final Map<RestTemplate, MockRestServiceServer> servers = new ConcurrentHashMap<>();
private final Supplier<? extends RequestExpectationManager> expectationManagerSupplier;
private boolean detectRootUri = true;
private boolean bufferContent;
public MockServerRestTemplateCustomizer() {
this(SimpleRequestExpectationManager::new);
}
/**
* Create a new {@link MockServerRestTemplateCustomizer} instance.
* @param expectationManager the expectation manager | MockServerRestTemplateCustomizer |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/http/HttpCorsConfigTests.java | {
"start": 5306,
"end": 5704
} | class ____ extends UrlBasedCorsConfigurationSource {
MyCorsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList(RequestMethod.GET.name(), RequestMethod.POST.name()));
super.registerCorsConfiguration("/**", configuration);
}
}
}
| MyCorsConfigurationSource |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_2023/Issue2023Test.java | {
"start": 565,
"end": 1505
} | class ____ {
@ProcessorTest
public void shouldUseDefaultExpressionCorrectly() {
PersonDto person = new PersonDto();
person.setName( "John" );
person.setEmail( "john@doe.com" );
NewPersonRequest request = Issue2023Mapper.INSTANCE.createRequest( person, null );
assertThat( request ).isNotNull();
assertThat( request.getName() ).isEqualTo( "John" );
assertThat( request.getEmail() ).isEqualTo( "john@doe.com" );
assertThat( request.getCorrelationId() ).isNotNull();
UUID correlationId = UUID.randomUUID();
request = Issue2023Mapper.INSTANCE.createRequest( person, correlationId );
assertThat( request ).isNotNull();
assertThat( request.getName() ).isEqualTo( "John" );
assertThat( request.getEmail() ).isEqualTo( "john@doe.com" );
assertThat( request.getCorrelationId() ).isEqualTo( correlationId );
}
}
| Issue2023Test |
java | apache__camel | components/camel-micrometer/src/main/java/org/apache/camel/component/micrometer/json/MicrometerModule.java | {
"start": 7216,
"end": 7885
} | class ____ extends MeterSerializer<FunctionTimer> {
private final TimeUnit timeUnit;
private FunctionTimerSerializer(TimeUnit timeUnit) {
super(FunctionTimer.class);
this.timeUnit = timeUnit;
}
@Override
protected void serializeStatistics(FunctionTimer timer, JsonGenerator json, SerializerProvider provider)
throws IOException {
json.writeNumberField("count", timer.count());
json.writeNumberField("mean", timer.mean(timeUnit));
json.writeNumberField("total", timer.totalTime(timeUnit));
}
}
private static final | FunctionTimerSerializer |
java | quarkusio__quarkus | extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/fieldvisibility/FieldVisibilityResource.java | {
"start": 560,
"end": 685
} | class ____ {
public String name; // hidden in the schema
public String address;
}
public static | Customer |
java | alibaba__nacos | console/src/test/java/com/alibaba/nacos/console/controller/v3/ConsoleHealthControllerTest.java | {
"start": 1673,
"end": 3880
} | class ____ {
@Mock
private HealthProxy healthProxy;
@InjectMocks
private ConsoleHealthController consoleHealthController;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(consoleHealthController).build();
}
@Test
void testLiveness() throws Exception {
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/v3/console/health/liveness");
MockHttpServletResponse response = mockMvc.perform(builder).andReturn().getResponse();
String actualValue = response.getContentAsString();
Result<String> result = new ObjectMapper().readValue(actualValue, new TypeReference<Result<String>>() {
});
assertEquals("ok", result.getData());
}
@Test
void testReadiness() throws Exception {
when(healthProxy.checkReadiness()).thenReturn(Result.success("ready"));
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/v3/console/health/readiness");
MockHttpServletResponse response = mockMvc.perform(builder).andReturn().getResponse();
String actualValue = response.getContentAsString();
Result<String> result = new ObjectMapper().readValue(actualValue, new TypeReference<Result<String>>() {
});
assertEquals("ready", result.getData());
assertEquals(200, response.getStatus());
}
@Test
void testReadinessFail() throws Exception {
when(healthProxy.checkReadiness()).thenReturn(Result.failure("fail"));
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/v3/console/health/readiness");
MockHttpServletResponse response = mockMvc.perform(builder).andReturn().getResponse();
String actualValue = response.getContentAsString();
Result<String> result = new ObjectMapper().readValue(actualValue, new TypeReference<Result<String>>() {
});
assertEquals("fail", result.getMessage());
assertEquals(500, response.getStatus());
}
}
| ConsoleHealthControllerTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.