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
|
quarkusio__quarkus
|
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/InterceptorPlacement.java
|
{
"start": 35,
"end": 106
}
|
enum ____ {
INTERCEPTOR_CLASS,
TARGET_CLASS,
}
|
InterceptorPlacement
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/index/query/IntervalsSourceProvider.java
|
{
"start": 28304,
"end": 32493
}
|
class ____ extends IntervalsSourceProvider implements VersionedNamedWriteable {
public static final String NAME = "regexp";
private final String pattern;
private final String analyzer;
private final String useField;
public Regexp(String pattern, String analyzer, String useField) {
this.pattern = pattern;
this.analyzer = analyzer;
this.useField = useField;
}
public Regexp(StreamInput in) throws IOException {
this.pattern = in.readString();
this.analyzer = in.readOptionalString();
this.useField = in.readOptionalString();
}
@Override
public IntervalsSource getSource(SearchExecutionContext context, TextFamilyFieldType fieldType) {
NamedAnalyzer analyzer = null;
if (this.analyzer != null) {
analyzer = context.getIndexAnalyzers().get(this.analyzer);
}
if (useField != null) {
fieldType = useField(context.getFieldType(useField));
}
if (analyzer == null) {
analyzer = fieldType.getTextSearchInfo().searchAnalyzer();
}
BytesRef normalizedPattern = analyzer.normalize(fieldType.name(), pattern);
IntervalsSource source = fieldType.regexpIntervals(normalizedPattern, context);
if (useField != null) {
source = Intervals.fixField(useField, source);
}
return source;
}
@Override
public void extractFields(Set<String> fields) {
if (useField != null) {
fields.add(useField);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Regexp regexp = (Regexp) o;
return Objects.equals(pattern, regexp.pattern)
&& Objects.equals(analyzer, regexp.analyzer)
&& Objects.equals(useField, regexp.useField);
}
@Override
public int hashCode() {
return Objects.hash(pattern, analyzer, useField);
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersions.V_8_16_0;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(pattern);
out.writeOptionalString(analyzer);
out.writeOptionalString(useField);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME);
builder.field("pattern", pattern);
if (analyzer != null) {
builder.field("analyzer", analyzer);
}
if (useField != null) {
builder.field("use_field", useField);
}
builder.endObject();
return builder;
}
private static final ConstructingObjectParser<Regexp, Void> PARSER = new ConstructingObjectParser<>(NAME, args -> {
String term = (String) args[0];
String analyzer = (String) args[1];
String useField = (String) args[2];
return new Regexp(term, analyzer, useField);
});
static {
PARSER.declareString(constructorArg(), new ParseField("pattern"));
PARSER.declareString(optionalConstructorArg(), new ParseField("analyzer"));
PARSER.declareString(optionalConstructorArg(), new ParseField("use_field"));
}
public static Regexp fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
String getPattern() {
return pattern;
}
String getAnalyzer() {
return analyzer;
}
String getUseField() {
return useField;
}
}
public static
|
Regexp
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/AutoInputFormat.java
|
{
"start": 1566,
"end": 2699
}
|
class ____ extends FileInputFormat {
private TextInputFormat textInputFormat = new TextInputFormat();
private SequenceFileInputFormat seqFileInputFormat =
new SequenceFileInputFormat();
public void configure(JobConf job) {
textInputFormat.configure(job);
// SequenceFileInputFormat has no configure() method
}
public RecordReader getRecordReader(InputSplit split, JobConf job,
Reporter reporter) throws IOException {
FileSplit fileSplit = (FileSplit) split;
FileSystem fs = FileSystem.get(fileSplit.getPath().toUri(), job);
FSDataInputStream is = fs.open(fileSplit.getPath());
byte[] header = new byte[3];
RecordReader reader = null;
try {
is.readFully(header);
} catch (EOFException eof) {
reader = textInputFormat.getRecordReader(split, job, reporter);
} finally {
is.close();
}
if (header[0] == 'S' && header[1] == 'E' && header[2] == 'Q') {
reader = seqFileInputFormat.getRecordReader(split, job, reporter);
} else {
reader = textInputFormat.getRecordReader(split, job, reporter);
}
return reader;
}
}
|
AutoInputFormat
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/scheduling/concurrent/DefaultManagedTaskExecutor.java
|
{
"start": 1142,
"end": 1547
}
|
class ____ not strictly JSR-236 based; it can work with any regular
* {@link java.util.concurrent.Executor} that can be found in JNDI.
* The actual adapting to {@link jakarta.enterprise.concurrent.ManagedExecutorService}
* happens in the base class {@link ConcurrentTaskExecutor} itself.
*
* @author Juergen Hoeller
* @since 4.0
* @see jakarta.enterprise.concurrent.ManagedExecutorService
*/
public
|
is
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/FlinkProjectCalcMergeRule.java
|
{
"start": 1530,
"end": 2012
}
|
class ____ extends ProjectCalcMergeRule {
public static final RelOptRule INSTANCE = new FlinkProjectCalcMergeRule(Config.DEFAULT);
protected FlinkProjectCalcMergeRule(Config config) {
super(config);
}
@Override
public boolean matches(RelOptRuleCall call) {
final Project topProject = call.rel(0);
final LogicalCalc bottomCalc = call.rel(1);
return FlinkRelUtil.isMergeable(topProject, bottomCalc);
}
}
|
FlinkProjectCalcMergeRule
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/builtin/mapper/IterableSourceTargetMapper.java
|
{
"start": 510,
"end": 830
}
|
interface ____ {
IterableSourceTargetMapper INSTANCE = Mappers.getMapper( IterableSourceTargetMapper.class );
IterableTarget sourceToTarget(IterableSource source);
@IterableMapping(dateFormat = "dd.MM.yyyy")
List<String> stringListToDateList(List<XMLGregorianCalendar> dates);
}
|
IterableSourceTargetMapper
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/legacy/api/Types.java
|
{
"start": 2012,
"end": 10516
}
|
class ____ {
// we use SQL-like naming for types and avoid Java keyword clashes
// CHECKSTYLE.OFF: MethodName
/** Returns type information for a Table API string or SQL VARCHAR type. */
public static TypeInformation<String> STRING() {
return org.apache.flink.api.common.typeinfo.Types.STRING;
}
/** Returns type information for a Table API boolean or SQL BOOLEAN type. */
public static TypeInformation<Boolean> BOOLEAN() {
return org.apache.flink.api.common.typeinfo.Types.BOOLEAN;
}
/** Returns type information for a Table API byte or SQL TINYINT type. */
public static TypeInformation<Byte> BYTE() {
return org.apache.flink.api.common.typeinfo.Types.BYTE;
}
/** Returns type information for a Table API short or SQL SMALLINT type. */
public static TypeInformation<Short> SHORT() {
return org.apache.flink.api.common.typeinfo.Types.SHORT;
}
/** Returns type information for a Table API integer or SQL INT/INTEGER type. */
public static TypeInformation<Integer> INT() {
return org.apache.flink.api.common.typeinfo.Types.INT;
}
/** Returns type information for a Table API long or SQL BIGINT type. */
public static TypeInformation<Long> LONG() {
return org.apache.flink.api.common.typeinfo.Types.LONG;
}
/** Returns type information for a Table API float or SQL FLOAT/REAL type. */
public static TypeInformation<Float> FLOAT() {
return org.apache.flink.api.common.typeinfo.Types.FLOAT;
}
/** Returns type information for a Table API integer or SQL DOUBLE type. */
public static TypeInformation<Double> DOUBLE() {
return org.apache.flink.api.common.typeinfo.Types.DOUBLE;
}
/** Returns type information for a Table API big decimal or SQL DECIMAL type. */
public static TypeInformation<BigDecimal> DECIMAL() {
return org.apache.flink.api.common.typeinfo.Types.BIG_DEC;
}
/** Returns type information for a Table API SQL date or SQL DATE type. */
public static TypeInformation<java.sql.Date> SQL_DATE() {
return org.apache.flink.api.common.typeinfo.Types.SQL_DATE;
}
/** Returns type information for a Table API SQL time or SQL TIME type. */
public static TypeInformation<java.sql.Time> SQL_TIME() {
return org.apache.flink.api.common.typeinfo.Types.SQL_TIME;
}
/** Returns type information for a Table API SQL timestamp or SQL TIMESTAMP type. */
public static TypeInformation<java.sql.Timestamp> SQL_TIMESTAMP() {
return org.apache.flink.api.common.typeinfo.Types.SQL_TIMESTAMP;
}
/** Returns type information for a Table API LocalDate type. */
public static TypeInformation<java.time.LocalDate> LOCAL_DATE() {
return org.apache.flink.api.common.typeinfo.Types.LOCAL_DATE;
}
/** Returns type information for a Table API LocalTime type. */
public static TypeInformation<java.time.LocalTime> LOCAL_TIME() {
return org.apache.flink.api.common.typeinfo.Types.LOCAL_TIME;
}
/** Returns type information for a Table API LocalDateTime type. */
public static TypeInformation<java.time.LocalDateTime> LOCAL_DATE_TIME() {
return org.apache.flink.api.common.typeinfo.Types.LOCAL_DATE_TIME;
}
/** Returns type information for a Table API interval of months. */
public static TypeInformation<Integer> INTERVAL_MONTHS() {
return TimeIntervalTypeInfo.INTERVAL_MONTHS;
}
/** Returns type information for a Table API interval of milliseconds. */
public static TypeInformation<Long> INTERVAL_MILLIS() {
return TimeIntervalTypeInfo.INTERVAL_MILLIS;
}
/**
* Returns type information for {@link Row} with fields of the given types.
*
* <p>A row is a variable-length, null-aware composite type for storing multiple values in a
* deterministic field order. Every field can be null regardless of the field's type. The type
* of row fields cannot be automatically inferred; therefore, it is required to provide type
* information whenever a row is used.
*
* <p>The schema of rows can have up to <code>Integer.MAX_VALUE</code> fields, however, all row
* instances must strictly adhere to the schema defined by the type info.
*
* <p>This method generates type information with fields of the given types; the fields have the
* default names (f0, f1, f2 ..).
*
* @param types The types of the row fields, e.g., Types.STRING(), Types.INT()
*/
public static TypeInformation<Row> ROW(TypeInformation<?>... types) {
return org.apache.flink.api.common.typeinfo.Types.ROW(types);
}
/**
* Returns type information for {@link Row} with fields of the given types and with given names.
*
* <p>A row is a variable-length, null-aware composite type for storing multiple values in a
* deterministic field order. Every field can be null independent of the field's type. The type
* of row fields cannot be automatically inferred; therefore, it is required to provide type
* information whenever a row is used.
*
* <p>The schema of rows can have up to <code>Integer.MAX_VALUE</code> fields, however, all row
* instances must strictly adhere to the schema defined by the type info.
*
* @param fieldNames The array of field names
* @param types The types of the row fields, e.g., Types.STRING(), Types.INT()
*/
public static TypeInformation<Row> ROW(String[] fieldNames, TypeInformation<?>[] types) {
return org.apache.flink.api.common.typeinfo.Types.ROW_NAMED(fieldNames, types);
}
/**
* Generates type information for an array consisting of Java primitive elements. The elements
* do not support null values.
*
* @param elementType type of the array elements; e.g. Types.INT()
*/
public static TypeInformation<?> PRIMITIVE_ARRAY(TypeInformation<?> elementType) {
if (elementType.equals(BOOLEAN())) {
return PrimitiveArrayTypeInfo.BOOLEAN_PRIMITIVE_ARRAY_TYPE_INFO;
} else if (elementType.equals(BYTE())) {
return PrimitiveArrayTypeInfo.BYTE_PRIMITIVE_ARRAY_TYPE_INFO;
} else if (elementType.equals(SHORT())) {
return PrimitiveArrayTypeInfo.SHORT_PRIMITIVE_ARRAY_TYPE_INFO;
} else if (elementType.equals(INT())) {
return PrimitiveArrayTypeInfo.INT_PRIMITIVE_ARRAY_TYPE_INFO;
} else if (elementType.equals(LONG())) {
return PrimitiveArrayTypeInfo.LONG_PRIMITIVE_ARRAY_TYPE_INFO;
} else if (elementType.equals(FLOAT())) {
return PrimitiveArrayTypeInfo.FLOAT_PRIMITIVE_ARRAY_TYPE_INFO;
} else if (elementType.equals(DOUBLE())) {
return PrimitiveArrayTypeInfo.DOUBLE_PRIMITIVE_ARRAY_TYPE_INFO;
}
throw new TableException(
String.format(
"%s cannot be an element of a primitive array. Only Java primitive types are supported.",
elementType));
}
/**
* Generates type information for an array consisting of Java object elements. Null values for
* elements are supported.
*
* @param elementType type of the array elements; e.g. Types.INT()
*/
public static <E> TypeInformation<E[]> OBJECT_ARRAY(TypeInformation<E> elementType) {
return ObjectArrayTypeInfo.getInfoFor(elementType);
}
/**
* Generates type information for a Java HashMap. Null values in keys are not supported. An
* entry's value can be null.
*
* @param keyType type of the keys of the map e.g. Types.STRING()
* @param valueType type of the values of the map e.g. Types.STRING()
*/
public static <K, V> TypeInformation<Map<K, V>> MAP(
TypeInformation<K> keyType, TypeInformation<V> valueType) {
return new MapTypeInfo<>(keyType, valueType);
}
/**
* Generates type information for a Multiset. A Multiset is baked by a Java HashMap and maps an
* arbitrary key to an integer value. Null values in keys are not supported.
*
* @param elementType type of the elements of the multiset e.g. Types.STRING()
*/
public static <E> TypeInformation<Map<E, Integer>> MULTISET(TypeInformation<E> elementType) {
return new MultisetTypeInfo<>(elementType);
}
// CHECKSTYLE.ON: MethodName
private Types() {
// no instantiation
}
}
|
Types
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-web-proxy/src/test/java/org/apache/hadoop/yarn/server/webproxy/TestWebAppProxyServlet.java
|
{
"start": 6108,
"end": 10642
}
|
class ____ extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
LOG.warn("doGet() interrupted", e);
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setStatus(HttpServletResponse.SC_OK);
}
}
@Test
@Timeout(5000)
void testWebAppProxyServlet() throws Exception {
configuration.set(YarnConfiguration.PROXY_ADDRESS, "localhost:9090");
// overriding num of web server threads, see HttpServer.HTTP_MAXTHREADS
configuration.setInt("hadoop.http.max.threads", 10);
WebAppProxyServerForTest proxy = new WebAppProxyServerForTest();
proxy.init(configuration);
proxy.start();
int proxyPort = proxy.proxy.proxyServer.getConnectorAddress(0).getPort();
AppReportFetcherForTest appReportFetcher = proxy.proxy.appReportFetcher;
// wrong url
try {
// wrong url without app ID
URL emptyUrl = new URL("http://localhost:" + proxyPort + "/proxy");
HttpURLConnection emptyProxyConn = (HttpURLConnection) emptyUrl
.openConnection();
emptyProxyConn.connect();
assertEquals(HttpURLConnection.HTTP_NOT_FOUND, emptyProxyConn.getResponseCode());
// wrong url. Set wrong app ID
URL wrongUrl = new URL("http://localhost:" + proxyPort + "/proxy/app");
HttpURLConnection proxyConn = (HttpURLConnection) wrongUrl
.openConnection();
proxyConn.connect();
assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR,
proxyConn.getResponseCode());
// set true Application ID in url
URL url = new URL("http://localhost:" + proxyPort + "/proxy/application_00_0");
proxyConn = (HttpURLConnection) url.openConnection();
// set cookie
proxyConn.setRequestProperty("Cookie", "checked_application_0_0000=true");
proxyConn.connect();
assertEquals(HttpURLConnection.HTTP_OK, proxyConn.getResponseCode());
assertTrue(isResponseCookiePresent(
proxyConn, "checked_application_0_0000", "true"));
// test that redirection is squashed correctly
URL redirectUrl = new URL("http://localhost:" + proxyPort
+ "/proxy/redirect/application_00_0");
proxyConn = (HttpURLConnection) redirectUrl.openConnection();
proxyConn.setInstanceFollowRedirects(false);
proxyConn.connect();
assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, proxyConn.getResponseCode(),
"The proxy returned an unexpected status code rather than"
+ "redirecting the connection (302)");
String expected =
WebAppUtils.getResolvedRMWebAppURLWithScheme(configuration)
+ "/cluster/failure/application_00_0";
String redirect = proxyConn.getHeaderField(ProxyUtils.LOCATION);
assertEquals(expected, redirect, "The proxy did not redirect the connection to the failure "
+ "page of the RM");
// cannot found application 1: null
appReportFetcher.answer = 1;
proxyConn = (HttpURLConnection) url.openConnection();
proxyConn.setRequestProperty("Cookie", "checked_application_0_0000=true");
proxyConn.connect();
assertEquals(HttpURLConnection.HTTP_NOT_FOUND,
proxyConn.getResponseCode());
assertFalse(isResponseCookiePresent(
proxyConn, "checked_application_0_0000", "true"));
// cannot found application 2: ApplicationNotFoundException
appReportFetcher.answer = 4;
proxyConn = (HttpURLConnection) url.openConnection();
proxyConn.setRequestProperty("Cookie", "checked_application_0_0000=true");
proxyConn.connect();
assertEquals(HttpURLConnection.HTTP_NOT_FOUND,
proxyConn.getResponseCode());
assertFalse(isResponseCookiePresent(
proxyConn, "checked_application_0_0000", "true"));
// wrong user
appReportFetcher.answer = 2;
proxyConn = (HttpURLConnection) url.openConnection();
proxyConn.connect();
assertEquals(HttpURLConnection.HTTP_OK, proxyConn.getResponseCode());
String s = readInputStream(proxyConn.getInputStream());
assertTrue(s
.contains("to continue to an Application Master web
|
TimeOutTestServlet
|
java
|
spring-projects__spring-framework
|
spring-test/src/main/java/org/springframework/test/context/ContextLoader.java
|
{
"start": 931,
"end": 1040
}
|
interface ____ should
* not be implemented directly. Implement {@link SmartContextLoader} instead of this
*
|
and
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolver.java
|
{
"start": 1265,
"end": 2964
}
|
class ____ implements PlaceholdersResolver {
private final @Nullable Iterable<PropertySource<?>> sources;
private final PropertyPlaceholderHelper helper;
public PropertySourcesPlaceholdersResolver(Environment environment) {
this(getSources(environment), null);
}
public PropertySourcesPlaceholdersResolver(@Nullable Iterable<PropertySource<?>> sources) {
this(sources, null);
}
public PropertySourcesPlaceholdersResolver(@Nullable Iterable<PropertySource<?>> sources,
@Nullable PropertyPlaceholderHelper helper) {
this.sources = sources;
this.helper = (helper != null) ? helper
: new PropertyPlaceholderHelper(SystemPropertyUtils.PLACEHOLDER_PREFIX,
SystemPropertyUtils.PLACEHOLDER_SUFFIX, SystemPropertyUtils.VALUE_SEPARATOR,
SystemPropertyUtils.ESCAPE_CHARACTER, true);
}
@Override
public @Nullable Object resolvePlaceholders(@Nullable Object value) {
if (value instanceof String string) {
return this.helper.replacePlaceholders(string, this::resolvePlaceholder);
}
return value;
}
protected @Nullable String resolvePlaceholder(String placeholder) {
if (this.sources != null) {
for (PropertySource<?> source : this.sources) {
Object value = source.getProperty(placeholder);
if (value != null) {
return String.valueOf(value);
}
}
}
return null;
}
private static PropertySources getSources(Environment environment) {
Assert.notNull(environment, "'environment' must not be null");
Assert.isInstanceOf(ConfigurableEnvironment.class, environment,
"'environment' must be a ConfigurableEnvironment");
return ((ConfigurableEnvironment) environment).getPropertySources();
}
}
|
PropertySourcesPlaceholdersResolver
|
java
|
FasterXML__jackson-core
|
src/main/java/tools/jackson/core/TreeNode.java
|
{
"start": 505,
"end": 10830
}
|
interface ____
{
/*
/**********************************************************************
/* Minimal introspection methods
/**********************************************************************
*/
/**
* Method that can be used for efficient type detection
* when using stream abstraction for traversing nodes.
* Will return the first {@link JsonToken} that equivalent
* stream event would produce (for most nodes there is just
* one token but for structured/container types multiple)
*
* @return {@link JsonToken} that is most closely associated with the node type
*/
JsonToken asToken();
/**
* If this node is a numeric type (as per {@link JsonToken#isNumeric}),
* returns native type that node uses to store the numeric value;
* otherwise returns null.
*
* @return Type of number contained, if any; or null if node does not
* contain numeric value.
*/
JsonParser.NumberType numberType();
/**
* Method that returns number of child nodes this node contains:
* for Array nodes, number of child elements, for Object nodes,
* number of properties, and for all other nodes 0.
*
* @return For non-container nodes returns 0; for arrays number of
* contained elements, and for objects number of properties.
*/
int size();
/**
* Method that returns true for all value nodes: ones that
* are not containers, and that do not represent "missing" nodes
* in the path. Such value nodes represent String, Number, Boolean
* and null values from JSON.
*<p>
* Note: one and only one of methods {@link #isValueNode},
* {@link #isContainer()} and {@link #isMissingNode} ever
* returns true for any given node.
*
* @return True if this node is considered a value node; something that
* represents either a scalar value or explicit {@code null}
*/
boolean isValueNode();
/**
* Method that returns true for container nodes: Arrays and Objects.
*<p>
* Note: one and only one of methods {@link #isValueNode},
* {@link #isContainer()} and {@link #isMissingNode} ever
* returns true for any given node.
*
* @return {@code True} for Array and Object nodes, {@code false} otherwise
*/
boolean isContainer();
/**
* Method that returns true for "virtual" nodes which represent
* missing entries constructed by path accessor methods when
* there is no actual node matching given criteria.
*<p>
* Note: one and only one of methods {@link #isValueNode},
* {@link #isContainer()} and {@link #isMissingNode} ever
* returns true for any given node.
*
* @return {@code True} if this node represents a "missing" node
*/
boolean isMissingNode();
/**
* Method that returns true if this node is an Array node, false
* otherwise.
* Note that if true is returned, {@link #isContainer()}
* must also return true.
*
* @return {@code True} for Array nodes, {@code false} for everything else
*/
boolean isArray();
/**
* Method that returns true if this node is an Object node, false
* otherwise.
* Note that if true is returned, {@link #isContainer()}
* must also return true.
*
* @return {@code True} for Object nodes, {@code false} for everything else
*/
boolean isObject();
/**
* Method that returns true if this node is a node that represents
* logical {@code null} value.
*
* @return {@code True} for nodes representing explicit input {@code null},
* {@code false} for everything else
*
* @since 3.0
*/
boolean isNull();
/**
* Method that returns true if this node represents an embedded
* "foreign" (or perhaps native?) object (like POJO), not represented
* as regular content. Such nodes are used to pass information that
* either native format cannot express as-is, metadata not included within
* at all, or something else that requires special handling.
*
* @return {@code True} for nodes representing "embedded" (or format-specific, native)
* value -- ones that streaming api exposes as {@link JsonToken#VALUE_EMBEDDED_OBJECT}
* -- {@code false} for other nodes
*
* @since 3.0
*/
boolean isEmbeddedValue();
/*
/**********************************************************************
/* Basic traversal through structured entries (Arrays, Objects)
/**********************************************************************
*/
/**
* Method for accessing value of the specified property of
* an Object node. If this node is not an Object (or it
* does not have a value for specified property) {@code null} is returned.
*<p>
* NOTE: handling of explicit null values may vary between
* implementations; some trees may retain explicit nulls, others not.
*
* @param propertyName Name of the property to access
*
* @return Node that represent value of the specified property,
* if this node is an Object and has value for the specified
* property; {@code null} otherwise.
*/
TreeNode get(String propertyName);
/**
* Method for accessing value of the specified element of
* an array node. For other nodes, null is returned.
*<p>
* For array nodes, index specifies
* exact location within array and allows for efficient iteration
* over child elements (underlying storage is guaranteed to
* be efficiently indexable, i.e. has random-access to elements).
* If index is less than 0, or equal-or-greater than
* <code>node.size()</code>, null is returned; no exception is
* thrown for any index.
*
* @param index Index of the Array node element to access
*
* @return Node that represent value of the specified element,
* if this node is an array and has specified element;
* {@code null} otherwise.
*/
TreeNode get(int index);
/**
* Method for accessing value of the specified property of
* an Object node.
* For other nodes, a "missing node" (virtual node
* for which {@link #isMissingNode} returns true) is returned.
*
* @param propertyName Name of the property to access
*
* @return Node that represent value of the specified Object property,
* if this node is an object and has value for the specified property;
* otherwise "missing node" is returned.
*/
TreeNode path(String propertyName);
/**
* Method for accessing value of the specified element of
* an array node.
* For other nodes, a "missing node" (virtual node
* for which {@link #isMissingNode} returns true) is returned.
*<p>
* For array nodes, index specifies
* exact location within array and allows for efficient iteration
* over child elements (underlying storage is guaranteed to
* be efficiently indexable, i.e. has random-access to elements).
* If index is less than 0, or equal-or-greater than
* <code>node.size()</code>, "missing node" is returned; no exception is
* thrown for any index.
*
* @param index Index of the Array node element to access
*
* @return Node that represent value of the specified element,
* if this node is an array and has specified element;
* otherwise "missing node" is returned.
*/
TreeNode path(int index);
/**
* Method for accessing names of all properties for this node, if (and only if)
* this node is an Object node. Number of property names accessible
* will be {@link #size}.
*
* @return {@link Collection} of names of all properties this Object node
* has (if Object node); empty {@link Collection} otherwise (never {@code null}).
*/
Collection<String> propertyNames();
/**
* Method for locating node specified by given JSON pointer instances.
* Method will never return null; if no matching node exists,
* will return a node for which {@link TreeNode#isMissingNode()} returns true.
*
* @param ptr {@link JsonPointer} expression for descendant node to return
*
* @return Node that matches given JSON Pointer, if any: if no match exists,
* will return a "missing" node (for which {@link TreeNode#isMissingNode()}
* returns {@code true}).
*/
TreeNode at(JsonPointer ptr);
/**
* Convenience method that is functionally equivalent to:
*<pre>
* return at(JsonPointer.valueOf(jsonPointerExpression));
*</pre>
*<p>
* Note that if the same expression is used often, it is preferable to construct
* {@link JsonPointer} instance once and reuse it: this method will not perform
* any caching of compiled expressions.
*
* @param ptrExpr Expression to compile as a {@link JsonPointer}
* instance
*
* @return Node that matches given JSON Pointer, if any: if no match exists,
* will return a "missing" node (for which {@link TreeNode#isMissingNode()}
* returns {@code true}).
*/
TreeNode at(String ptrExpr) throws IllegalArgumentException;
/*
/**********************************************************************
/* Converting to/from Streaming API
/**********************************************************************
*/
/**
* Method for constructing a {@link JsonParser} instance for
* iterating over contents of the tree that this node is root of.
* Functionally equivalent to first serializing tree and then re-parsing but
* more efficient.
*<p>
* NOTE: constructed parser instance will NOT initially point to a token,
* so before passing it to deserializers, it is typically necessary to
* advance it to the first available token by calling {@link JsonParser#nextToken()}.
*
* @param readCtxt {@link ObjectReadContext} to associate with parser constructed
* (to allow seamless databinding functionality)
*
* @return {@link JsonParser} that will stream over contents of this node
*/
JsonParser traverse(ObjectReadContext readCtxt);
}
|
TreeNode
|
java
|
apache__rocketmq
|
proxy/src/main/java/org/apache/rocketmq/proxy/grpc/ProxyAndTlsProtocolNegotiator.java
|
{
"start": 8491,
"end": 11404
}
|
class ____ extends ChannelInboundHandlerAdapter {
private ProtocolNegotiationEvent pne = InternalProtocolNegotiationEvent.getDefault();
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HAProxyMessage) {
handleWithMessage((HAProxyMessage) msg);
ctx.fireUserEventTriggered(pne);
} else {
super.channelRead(ctx, msg);
}
ctx.pipeline().remove(this);
}
/**
* The definition of key refers to the implementation of nginx
* <a href="https://nginx.org/en/docs/http/ngx_http_core_module.html#var_proxy_protocol_addr">ngx_http_core_module</a>
*
* @param msg
*/
private void handleWithMessage(HAProxyMessage msg) {
try {
Attributes.Builder builder = InternalProtocolNegotiationEvent.getAttributes(pne).toBuilder();
if (StringUtils.isNotBlank(msg.sourceAddress())) {
builder.set(AttributeKeys.PROXY_PROTOCOL_ADDR, msg.sourceAddress());
}
if (msg.sourcePort() > 0) {
builder.set(AttributeKeys.PROXY_PROTOCOL_PORT, String.valueOf(msg.sourcePort()));
}
if (StringUtils.isNotBlank(msg.destinationAddress())) {
builder.set(AttributeKeys.PROXY_PROTOCOL_SERVER_ADDR, msg.destinationAddress());
}
if (msg.destinationPort() > 0) {
builder.set(AttributeKeys.PROXY_PROTOCOL_SERVER_PORT, String.valueOf(msg.destinationPort()));
}
if (CollectionUtils.isNotEmpty(msg.tlvs())) {
msg.tlvs().forEach(tlv -> handleHAProxyTLV(tlv, builder));
}
pne = InternalProtocolNegotiationEvent
.withAttributes(InternalProtocolNegotiationEvent.getDefault(), builder.build());
} finally {
msg.release();
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof ProtocolNegotiationEvent) {
pne = (ProtocolNegotiationEvent) evt;
} else {
super.userEventTriggered(ctx, evt);
}
}
}
protected void handleHAProxyTLV(HAProxyTLV tlv, Attributes.Builder builder) {
byte[] valueBytes = ByteBufUtil.getBytes(tlv.content());
if (!BinaryUtil.isAscii(valueBytes)) {
return;
}
Attributes.Key<String> key = AttributeKeys.valueOf(
HAProxyConstants.PROXY_PROTOCOL_TLV_PREFIX + String.format("%02x", tlv.typeByteValue()));
builder.set(key, new String(valueBytes, CharsetUtil.UTF_8));
}
private
|
HAProxyMessageHandler
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/HAUtilClient.java
|
{
"start": 1692,
"end": 5678
}
|
class ____ {
private static final Logger LOG = LoggerFactory.getLogger(HAUtilClient.class);
private static final DelegationTokenSelector tokenSelector =
new DelegationTokenSelector();
/**
* @return true if the given nameNodeUri appears to be a logical URI.
*/
public static boolean isLogicalUri(
Configuration conf, URI nameNodeUri) {
String host = nameNodeUri.getHost();
// A logical name must be one of the service IDs.
return DFSUtilClient.getNameServiceIds(conf).contains(host);
}
/**
* Check whether the client has a failover proxy provider configured
* for the namenode/nameservice.
*
* @param conf Configuration
* @param nameNodeUri The URI of namenode
* @return true if failover is configured.
*/
public static boolean isClientFailoverConfigured(
Configuration conf, URI nameNodeUri) {
String host = nameNodeUri.getHost();
String configKey = HdfsClientConfigKeys.Failover.PROXY_PROVIDER_KEY_PREFIX
+ "." + host;
return conf.get(configKey) != null;
}
/**
* Get the service name used in the delegation token for the given logical
* HA service.
* @param uri the logical URI of the cluster
* @param scheme the scheme of the corresponding FileSystem
* @return the service name
*/
public static Text buildTokenServiceForLogicalUri(final URI uri,
final String scheme) {
return new Text(buildTokenServicePrefixForLogicalUri(scheme)
+ uri.getHost());
}
public static String buildTokenServicePrefixForLogicalUri(String scheme) {
return HA_DT_SERVICE_PREFIX + scheme + ":";
}
/**
* Parse the file system URI out of the provided token.
*/
public static URI getServiceUriFromToken(final String scheme, Token<?> token) {
String tokStr = token.getService().toString();
final String prefix = buildTokenServicePrefixForLogicalUri(
scheme);
if (tokStr.startsWith(prefix)) {
tokStr = tokStr.replaceFirst(prefix, "");
}
return URI.create(scheme + "://" + tokStr);
}
/**
* @return true if this token corresponds to a logical nameservice
* rather than a specific namenode.
*/
public static boolean isTokenForLogicalUri(Token<?> token) {
return token.getService().toString().startsWith(HA_DT_SERVICE_PREFIX);
}
/**
* Locate a delegation token associated with the given HA cluster URI, and if
* one is found, clone it to also represent the underlying namenode address.
* @param ugi the UGI to modify
* @param haUri the logical URI for the cluster
* @param nnAddrs collection of NNs in the cluster to which the token
* applies
*/
public static void cloneDelegationTokenForLogicalUri(
UserGroupInformation ugi, URI haUri,
Collection<InetSocketAddress> nnAddrs) {
// this cloning logic is only used by hdfs
Text haService = HAUtilClient.buildTokenServiceForLogicalUri(haUri,
HdfsConstants.HDFS_URI_SCHEME);
Token<DelegationTokenIdentifier> haToken =
tokenSelector.selectToken(haService, ugi.getTokens());
if (haToken != null) {
for (InetSocketAddress singleNNAddr : nnAddrs) {
// this is a minor hack to prevent physical HA tokens from being
// exposed to the user via UGI.getCredentials(), otherwise these
// cloned tokens may be inadvertently propagated to jobs
Token<DelegationTokenIdentifier> specificToken =
haToken.privateClone(buildTokenService(singleNNAddr));
Text alias = new Text(
HAUtilClient.buildTokenServicePrefixForLogicalUri(
HdfsConstants.HDFS_URI_SCHEME)
+ "//" + specificToken.getService());
ugi.addToken(alias, specificToken);
LOG.debug("Mapped HA service delegation token for logical URI {}" +
" to namenode {}", haUri, singleNNAddr);
}
} else {
LOG.debug("No HA service delegation token found for logical URI {}",
haUri);
}
}
}
|
HAUtilClient
|
java
|
bumptech__glide
|
library/test/src/test/java/com/bumptech/glide/resize/load/ExifTest.java
|
{
"start": 773,
"end": 2476
}
|
class ____ {
private ArrayPool byteArrayPool;
private InputStream open(String imageName) {
return TestResourceUtil.openResource(getClass(), imageName);
}
private void assertOrientation(String filePrefix, int expectedOrientation) {
InputStream is = null;
try {
is = open(filePrefix + "_" + expectedOrientation + ".jpg");
assertEquals(
new DefaultImageHeaderParser().getOrientation(is, byteArrayPool), expectedOrientation);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// Do nothing.
}
}
}
}
@Before
public void setUp() {
byteArrayPool = new LruArrayPool();
}
@Test
public void testIssue387() throws IOException {
InputStream is = TestResourceUtil.openResource(getClass(), "issue387_rotated_jpeg.jpg");
assertThat(new DefaultImageHeaderParser().getOrientation(is, byteArrayPool)).isEqualTo(6);
}
@Test
public void testLandscape() throws IOException {
for (int i = 1; i <= 8; i++) {
assertOrientation("Landscape", i);
}
}
@Test
public void testPortrait() throws IOException {
for (int i = 1; i <= 8; i++) {
assertOrientation("Portrait", i);
}
}
@Test
public void testHandlesInexactSizesInByteArrayPools() {
for (int i = 1; i <= 8; i++) {
byteArrayPool.put(new byte[ArrayPool.STANDARD_BUFFER_SIZE_BYTES]);
assertOrientation("Portrait", i);
}
for (int i = 1; i <= 8; i++) {
byteArrayPool.put(new byte[ArrayPool.STANDARD_BUFFER_SIZE_BYTES]);
assertOrientation("Landscape", i);
}
}
}
|
ExifTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalSortedSetTest.java
|
{
"start": 1756,
"end": 2402
}
|
class ____ {
@Id
private Long id;
//tag::collections-bidirectional-sorted-set-example[]
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
@SortNatural
private SortedSet<Phone> phones = new TreeSet<>();
//end::collections-bidirectional-sorted-set-example[]
public Person() {
}
public Person(Long id) {
this.id = id;
}
public Set<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
phones.add(phone);
phone.setPerson(this);
}
public void removePhone(Phone phone) {
phones.remove(phone);
phone.setPerson(null);
}
}
@Entity(name = "Phone")
public static
|
Person
|
java
|
spring-projects__spring-boot
|
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java
|
{
"start": 2904,
"end": 2975
}
|
class ____ {
}
@ImportAutoConfiguration(ConfigC.class)
static
|
NoConfig
|
java
|
apache__maven
|
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4347ImportScopeWithSettingsProfilesTest.java
|
{
"start": 1033,
"end": 2088
}
|
class ____ extends AbstractMavenIntegrationTestCase {
/**
* Test that profiles from settings.xml will be used to resolve import-scoped dependency POMs.
* In this case, the settings profile enables snapshot resolution on the central repository, which
* is required to resolve the import-scoped POM with a SNAPSHOT version.
*
* @throws Exception in case of failure
*/
@Test
public void testit() throws Exception {
File testDir = extractResources("/mng-4347");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.deleteDirectory("target");
verifier.deleteArtifacts("org.apache.maven.its.mng4347");
verifier.setAutoclean(false);
verifier.addCliArgument("-s");
verifier.addCliArgument("settings.xml");
verifier.filterFile("settings-template.xml", "settings.xml");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
}
}
|
MavenITmng4347ImportScopeWithSettingsProfilesTest
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/serializer/filters/AfterFilterClassLevelTest.java
|
{
"start": 1413,
"end": 1484
}
|
class ____ {
public int id = 1001;
}
public static
|
ModelA
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest128_quote.java
|
{
"start": 329,
"end": 2116
}
|
class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "CREATE TABLE \"linxi_test\".\"linxi_subpart11\" (\n" +
" \"id\" BIGINT NOT NULL\n" +
" COMMENT '',\n" +
" \"int_test\" BIGINT NOT NULL\n" +
" COMMENT '',\n" +
" v_test VARCHAR NOT NULL\n" +
" COMMENT '',\n" +
" PRIMARY KEY (\'id\', int_test, subcol)\n" +
") PARTITION BY HASH KEY (\"id\"\n" +
") PARTITION NUM 10 SUBPARTITION BY LIST (\"subcol\" BIGINT\n" +
") SUBPARTITION OPTIONS (available_Partition_Num=100\n" +
") TABLEGROUP group2 OPTIONS (UPDATETYPE='realtime'\n" +
") COMMENT ''";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0);
assertEquals(1, statementList.size());
assertEquals("CREATE TABLE \"linxi_test\".\"linxi_subpart11\" (\n" +
"\t\"id\" BIGINT NOT NULL COMMENT '',\n" +
"\t\"int_test\" BIGINT NOT NULL COMMENT '',\n" +
"\tv_test VARCHAR NOT NULL COMMENT '',\n" +
"\tPRIMARY KEY (\'id\', int_test, subcol)\n" +
")\n" +
"OPTIONS (UPDATETYPE = 'realtime') COMMENT ''\n" +
"PARTITION BY HASH KEY('id') PARTITION NUM 10\n" +
"SUBPARTITION BY LIST (\"subcol\" BIGINT)\n" +
"SUBPARTITION OPTIONS (available_Partition_Num = 100)\n" +
"TABLEGROUP group2", stmt.toString());
}
}
|
MySqlCreateTableTest128_quote
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/booleanarrays/BooleanArrays_assertNullOrEmpty_Test.java
|
{
"start": 1368,
"end": 2016
}
|
class ____ extends BooleanArraysBaseTest {
@Test
void should_fail_if_array_is_not_null_and_is_not_empty() {
AssertionInfo info = someInfo();
boolean[] actual = { true, false };
Throwable error = catchThrowable(() -> arrays.assertNullOrEmpty(info, actual));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldBeNullOrEmpty(actual));
}
@Test
void should_pass_if_array_is_null() {
arrays.assertNullOrEmpty(someInfo(), null);
}
@Test
void should_pass_if_array_is_empty() {
arrays.assertNullOrEmpty(someInfo(), emptyArray());
}
}
|
BooleanArrays_assertNullOrEmpty_Test
|
java
|
elastic__elasticsearch
|
x-pack/plugin/text-structure/src/test/java/org/elasticsearch/xpack/textstructure/structurefinder/TextStructureTestCase.java
|
{
"start": 645,
"end": 5147
}
|
class ____ extends ESTestCase {
protected static final List<String> POSSIBLE_CHARSETS = Collections.unmodifiableList(
Charset.availableCharsets()
.keySet()
.stream()
.filter(name -> TextStructureFinderManager.FILEBEAT_SUPPORTED_ENCODINGS.contains(name.toLowerCase(Locale.ROOT)))
.collect(Collectors.toList())
);
protected static final String CSV_SAMPLE = """
time,id,value
2018-05-17T16:23:40,key1,42.0
2018-05-17T16:24:11,"key with spaces",42.0
""";
protected static final String NDJSON_SAMPLE = """
{"logger":"controller","timestamp":1478261151445,"level":"INFO","pid":42,"thread":"0x7fff7d2a8000","message":"message 1",\
"class":"ml","method":"core::SomeNoiseMaker","file":"Noisemaker.cc","line":333}
{"logger":"controller","timestamp":1478261151445,"level":"INFO","pid":42,"thread":"0x7fff7d2a8000","message":"message 2",\
"class":"ml","method":"core::SomeNoiseMaker","file":"Noisemaker.cc","line":333}
""";
protected static final String PIPE_DELIMITED_SAMPLE = """
2018-01-06 16:56:14.295748|INFO |VirtualServer |1 |listening on 0.0.0.0:9987, :::9987
2018-01-06 17:19:44.465252|INFO |VirtualServer |1 |client 'User1'(id:2) changed default admin channelgroup to 'Guest'(id:8)
2018-01-06 17:21:25.764368|INFO |VirtualServer |1 |client 'User1'(id:2) was added to channelgroup 'Channel Admin'(id:5) by \
client 'User1'(id:2) in channel 'Default Channel'(id:1)""";
protected static final String SEMI_COLON_DELIMITED_SAMPLE = """
"pos_id";"trip_id";"latitude";"longitude";"altitude";"timestamp"
"1";"3";"4703.7815";"1527.4713";"359.9";"2017-01-19 16:19:04.742113"
"2";"3";"4703.7815";"1527.4714";"359.9";"2017-01-19 16:19:05.741890"
"3";"3";"4703.7816";"1527.4716";"360.3";"2017-01-19 16:19:06.738842
""";
protected static final String TEXT_SAMPLE = """
[2018-05-11T17:07:29,461][INFO ][o.e.n.Node ] [node-0] initializing ...
[2018-05-11T17:07:29,553][INFO ][o.e.e.NodeEnvironment ] [node-0] using [1] data paths, mounts [[/ (/dev/disk1)]], net \
usable_space [223.4gb], net total_space [464.7gb], types [hfs]
[2018-05-11T17:07:29,553][INFO ][o.e.e.NodeEnvironment ] [node-0] heap size [3.9gb], compressed ordinary object pointers \
[true]
[2018-05-11T17:07:29,556][INFO ][o.e.n.Node ] [node-0] node name [node-0], node ID [tJ9u8HcaTbWxRtnlfz1RQA]
""";
protected static final String TEXT_WITH_NO_TIMESTAMPS_SAMPLE = """
[INFO ][o.e.n.Node ] [node-0] initializing ...
[INFO ][o.e.e.NodeEnvironment ] [node-0] using [1] data paths, mounts [[/ (/dev/disk1)]], net \
usable_space [223.4gb], net total_space [464.7gb], types [hfs]
[INFO ][o.e.e.NodeEnvironment ] [node-0] heap size [3.9gb], compressed ordinary object pointers [true]
[INFO ][o.e.n.Node ] [node-0] node name [node-0], node ID [tJ9u8HcaTbWxRtnlfz1RQA]
""";
protected static final String TSV_SAMPLE = """
time\tid\tvalue
2018-05-17T16:23:40\tkey1\t42.0
2018-05-17T16:24:11\t"key with spaces"\t42.0
""";
protected static final String XML_SAMPLE = """
<log4j:event logger="autodetect" timestamp="1526574809521" level="ERROR" thread="0x7fffc5a7c3c0">
<log4j:message><![CDATA[Neither a fieldname clause nor a field config file was specified]]></log4j:message>
</log4j:event>
<log4j:event logger="autodetect" timestamp="1526574809522" level="FATAL" thread="0x7fffc5a7c3c0">
<log4j:message><![CDATA[Field config could not be interpreted]]></log4j:message>
</log4j:event>
""";
// This doesn't need closing because it has an infinite timeout
protected static final TimeoutChecker NOOP_TIMEOUT_CHECKER = new TimeoutChecker("unit test", null, null);
protected List<String> explanation;
@Before
public void initExplanation() {
explanation = new ArrayList<>();
}
@After
public void printExplanation() {
LogManager.getLogger(getClass()).info("Explanation:\n" + String.join("\n", explanation));
}
protected Boolean randomHasByteOrderMarker(String charset) {
return charset.toUpperCase(Locale.ROOT).startsWith("UTF") ? randomBoolean() : null;
}
}
|
TextStructureTestCase
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/support/logging/Jdk14LoggingImplTest.java
|
{
"start": 195,
"end": 873
}
|
class ____ extends TestCase {
public void test_0() throws Exception {
Jdk14LoggingImpl impl = new Jdk14LoggingImpl(DruidDataSource.class.getName());
impl.isDebugEnabled();
impl.isInfoEnabled();
impl.isWarnEnabled();
impl.debug("");
impl.debug("", new Exception());
impl.info("");
impl.warn("");
impl.warn("", new Exception());
impl.error("");
impl.error("", new Exception());
assertEquals(1, impl.getInfoCount());
assertEquals(2, impl.getErrorCount());
assertEquals(2, impl.getWarnCount());
assertEquals(1, impl.getInfoCount());
}
}
|
Jdk14LoggingImplTest
|
java
|
apache__kafka
|
clients/src/test/java/org/apache/kafka/common/config/AbstractConfigTest.java
|
{
"start": 22901,
"end": 28885
}
|
class
____.put("config.providers", "file");
props.put("config.providers.file.class", MockFileConfigProvider.class.getName());
String id = UUID.randomUUID().toString();
props.put("config.providers.file.param.testId", id);
props.put("prefix.ssl.truststore.location.number", 5);
props.put("sasl.kerberos.service.name", "service name");
props.put("sasl.kerberos.key", "${file:/usr/kerberos:key}");
props.put("sasl.kerberos.password", "${file:/usr/kerberos:password}");
TestIndirectConfigResolution config = new TestIndirectConfigResolution(props, Collections.emptyMap());
assertEquals("testKey", config.originals().get("sasl.kerberos.key"));
assertEquals("randomPassword", config.originals().get("sasl.kerberos.password"));
MockFileConfigProvider.assertClosed(id);
}
@Test
public void testConfigProvidersPropsAsParam() {
// Test Case: Valid Test Case for ConfigProviders as a separate variable
Properties providers = new Properties();
providers.put("config.providers", "file");
providers.put("config.providers.file.class", MockFileConfigProvider.class.getName());
String id = UUID.randomUUID().toString();
providers.put("config.providers.file.param.testId", id);
Properties props = new Properties();
props.put("sasl.kerberos.key", "${file:/usr/kerberos:key}");
props.put("sasl.kerberos.password", "${file:/usr/kerberos:password}");
TestIndirectConfigResolution config = new TestIndirectConfigResolution(props, Utils.castToStringObjectMap(providers));
assertEquals("testKey", config.originals().get("sasl.kerberos.key"));
assertEquals("randomPassword", config.originals().get("sasl.kerberos.password"));
MockFileConfigProvider.assertClosed(id);
}
@Test
public void testAutomaticConfigProvidersWithFullClassName() {
// case0: MockFileConfigProvider is disallowed by org.apache.kafka.automatic.config.providers
System.setProperty(AbstractConfig.AUTOMATIC_CONFIG_PROVIDERS_PROPERTY, "file");
assertThrows(ConfigException.class, () -> new TestIndirectConfigResolution(Map.of("config.providers", "file",
"config.providers.file.class", MockFileConfigProvider.class.getName()),
Map.of()));
// case1: MockFileConfigProvider is allowed by org.apache.kafka.automatic.config.providers
System.setProperty(AbstractConfig.AUTOMATIC_CONFIG_PROVIDERS_PROPERTY, MockFileConfigProvider.class.getName());
Map<String, String> props = Map.of("config.providers", "file",
"config.providers.file.class", MockFileConfigProvider.class.getName(),
"config.providers.file.param.testId", UUID.randomUUID().toString(),
"test.key", "${file:/path:key}");
assertEquals("testKey", new TestIndirectConfigResolution(props, Map.of()).originals().get("test.key"));
// case2: MockFileConfigProvider and EnvVarConfigProvider are allowed by org.apache.kafka.automatic.config.providers
System.setProperty(AbstractConfig.AUTOMATIC_CONFIG_PROVIDERS_PROPERTY,
MockFileConfigProvider.class.getName() + "," + EnvVarConfigProvider.class.getName());
assertEquals("testKey", new TestIndirectConfigResolution(props, Map.of()).originals().get("test.key"));
}
@Test
public void testImmutableOriginalsWithConfigProvidersProps() {
// Test Case: Valid Test Case for ConfigProviders as a separate variable
Properties providers = new Properties();
providers.put("config.providers", "file");
providers.put("config.providers.file.class", MockFileConfigProvider.class.getName());
String id = UUID.randomUUID().toString();
providers.put("config.providers.file.param.testId", id);
Properties props = new Properties();
props.put("sasl.kerberos.key", "${file:/usr/kerberos:key}");
Map<?, ?> immutableMap = Collections.unmodifiableMap(props);
Map<String, ?> provMap = Utils.castToStringObjectMap(providers);
TestIndirectConfigResolution config = new TestIndirectConfigResolution(immutableMap, provMap);
assertEquals("testKey", config.originals().get("sasl.kerberos.key"));
MockFileConfigProvider.assertClosed(id);
}
@Test
public void testAutoConfigResolutionWithMultipleConfigProviders() {
// Test Case: Valid Test Case With Multiple ConfigProviders as a separate variable
Properties providers = new Properties();
providers.put("config.providers", "file,vault");
providers.put("config.providers.file.class", MockFileConfigProvider.class.getName());
String id = UUID.randomUUID().toString();
providers.put("config.providers.file.param.testId", id);
providers.put("config.providers.vault.class", MockVaultConfigProvider.class.getName());
Properties props = new Properties();
props.put("sasl.kerberos.key", "${file:/usr/kerberos:key}");
props.put("sasl.kerberos.password", "${file:/usr/kerberos:password}");
props.put("sasl.truststore.key", "${vault:/usr/truststore:truststoreKey}");
props.put("sasl.truststore.password", "${vault:/usr/truststore:truststorePassword}");
TestIndirectConfigResolution config = new TestIndirectConfigResolution(props, Utils.castToStringObjectMap(providers));
assertEquals("testKey", config.originals().get("sasl.kerberos.key"));
assertEquals("randomPassword", config.originals().get("sasl.kerberos.password"));
assertEquals("testTruststoreKey", config.originals().get("sasl.truststore.key"));
assertEquals("randomtruststorePassword", config.originals().get("sasl.truststore.password"));
MockFileConfigProvider.assertClosed(id);
}
@Test
public void testAutoConfigResolutionWithInvalidConfigProviderClass() {
// Test Case: Invalid
|
props
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/core/asyncprocessing/AsyncFutureImpl.java
|
{
"start": 1892,
"end": 26345
}
|
class ____<T> implements InternalAsyncFuture<T> {
/** The future holds the result. This may complete in async threads. */
private final CompletableFuture<T> completableFuture;
/** The callback runner. */
protected final CallbackRunner callbackRunner;
/** The exception handler that handles callback framework's error. */
protected final AsyncFrameworkExceptionHandler exceptionHandler;
public AsyncFutureImpl(
CallbackRunner callbackRunner, AsyncFrameworkExceptionHandler exceptionHandler) {
this.completableFuture = new CompletableFuture<>();
this.callbackRunner = callbackRunner;
this.exceptionHandler = exceptionHandler;
}
@Override
public <U> InternalAsyncFuture<U> thenApply(
FunctionWithException<? super T, ? extends U, ? extends Exception> fn) {
callbackRegistered();
if (completableFuture.isDone()) {
// this branch must be invoked in task thread when expected
T t;
try {
t = completableFuture.get();
} catch (Exception e) {
exceptionHandler.handleException(
"Caught exception when processing completed AsyncFuture's callback.", e);
return null;
}
U r = FunctionWithException.unchecked(fn).apply(t);
callbackFinished();
return InternalAsyncFutureUtils.completedFuture(r);
} else {
AsyncFutureImpl<U> ret = makeNewFuture();
completableFuture
.thenAccept(
(t) -> {
callbackRunner.submit(
() -> {
ret.completeInCallbackRunner(fn.apply(t));
callbackFinished();
});
})
.exceptionally(
(e) -> {
exceptionHandler.handleException(
"Caught exception when submitting AsyncFuture's callback.",
e);
return null;
});
return ret;
}
}
@Override
public InternalAsyncFuture<Void> thenAccept(
ThrowingConsumer<? super T, ? extends Exception> action) {
callbackRegistered();
if (completableFuture.isDone()) {
// this branch must be invoked in task thread when expected
T t;
try {
t = completableFuture.get();
} catch (Exception e) {
exceptionHandler.handleException(
"Caught exception when processing completed AsyncFuture's callback.", e);
return null;
}
ThrowingConsumer.unchecked(action).accept(t);
callbackFinished();
return InternalAsyncFutureUtils.completedVoidFuture();
} else {
AsyncFutureImpl<Void> ret = makeNewFuture();
completableFuture
.thenAccept(
(t) -> {
callbackRunner.submit(
() -> {
action.accept(t);
ret.completeInCallbackRunner(null);
callbackFinished();
});
})
.exceptionally(
(e) -> {
exceptionHandler.handleException(
"Caught exception when submitting AsyncFuture's callback.",
e);
return null;
});
return ret;
}
}
@Override
public <U> InternalAsyncFuture<U> thenCompose(
FunctionWithException<? super T, ? extends StateFuture<U>, ? extends Exception>
action) {
callbackRegistered();
if (completableFuture.isDone()) {
// this branch must be invoked in task thread when expected
T t;
try {
t = completableFuture.get();
} catch (Throwable e) {
exceptionHandler.handleException(
"Caught exception when processing completed AsyncFuture's callback.", e);
return null;
}
callbackFinished();
return (InternalAsyncFuture<U>) FunctionWithException.unchecked(action).apply(t);
} else {
AsyncFutureImpl<U> ret = makeNewFuture();
completableFuture
.thenAccept(
(t) -> {
callbackRunner.submit(
() -> {
StateFuture<U> su = action.apply(t);
su.thenAccept(ret::completeInCallbackRunner);
callbackFinished();
});
})
.exceptionally(
(e) -> {
exceptionHandler.handleException(
"Caught exception when submitting AsyncFuture's callback.",
e);
return null;
});
return ret;
}
}
@Override
public <U, V> InternalAsyncFuture<V> thenCombine(
StateFuture<? extends U> other,
BiFunctionWithException<? super T, ? super U, ? extends V, ? extends Exception> fn) {
callbackRegistered();
if (completableFuture.isDone()) {
// this branch must be invoked in task thread when expected
T t;
try {
t = completableFuture.get();
} catch (Throwable e) {
exceptionHandler.handleException(
"Caught exception when submitting AsyncFuture's callback.", e);
return null;
}
return (InternalAsyncFuture<V>)
other.thenCompose(
(u) -> {
V v = fn.apply(t, u);
callbackFinished();
return InternalAsyncFutureUtils.completedFuture(v);
});
} else {
AsyncFutureImpl<V> ret = makeNewFuture();
((InternalAsyncFuture<? extends U>) other)
.thenSyncAccept(
(u) -> {
completableFuture
.thenAccept(
(t) -> {
callbackRunner.submit(
() -> {
ret.completeInCallbackRunner(
fn.apply(t, u));
callbackFinished();
});
})
.exceptionally(
(e) -> {
exceptionHandler.handleException(
"Caught exception when submitting AsyncFuture's callback.",
e);
return null;
});
});
return ret;
}
}
@Override
public <U, V> InternalAsyncFuture<Tuple2<Boolean, Object>> thenConditionallyApply(
FunctionWithException<? super T, Boolean, ? extends Exception> condition,
FunctionWithException<? super T, ? extends U, ? extends Exception> actionIfTrue,
FunctionWithException<? super T, ? extends V, ? extends Exception> actionIfFalse) {
callbackRegistered();
if (completableFuture.isDone()) {
// this branch must be invoked in task thread when expected
T t;
try {
t = completableFuture.get();
} catch (Exception e) {
exceptionHandler.handleException(
"Caught exception when processing completed AsyncFuture's callback.", e);
return null;
}
boolean test = FunctionWithException.unchecked(condition).apply(t);
Object r =
test
? FunctionWithException.unchecked(actionIfTrue).apply(t)
: FunctionWithException.unchecked(actionIfFalse).apply(t);
callbackFinished();
return InternalAsyncFutureUtils.completedFuture(Tuple2.of(test, r));
} else {
AsyncFutureImpl<Tuple2<Boolean, Object>> ret = makeNewFuture();
completableFuture
.thenAccept(
(t) -> {
callbackRunner.submit(
() -> {
boolean test = condition.apply(t);
Object r =
test
? actionIfTrue.apply(t)
: actionIfFalse.apply(t);
ret.completeInCallbackRunner(Tuple2.of(test, r));
callbackFinished();
});
})
.exceptionally(
(e) -> {
exceptionHandler.handleException(
"Caught exception when submitting AsyncFuture's callback.",
e);
return null;
});
return ret;
}
}
@Override
public <U> InternalAsyncFuture<Tuple2<Boolean, U>> thenConditionallyApply(
FunctionWithException<? super T, Boolean, ? extends Exception> condition,
FunctionWithException<? super T, ? extends U, ? extends Exception> actionIfTrue) {
callbackRegistered();
if (completableFuture.isDone()) {
// this branch must be invoked in task thread when expected
T t;
try {
t = completableFuture.get();
} catch (Exception e) {
exceptionHandler.handleException(
"Caught exception when processing completed InternalAsyncFuture's callback.",
e);
return null;
}
boolean test = FunctionWithException.unchecked(condition).apply(t);
U r = test ? FunctionWithException.unchecked(actionIfTrue).apply(t) : null;
callbackFinished();
return InternalAsyncFutureUtils.completedFuture(Tuple2.of(test, r));
} else {
AsyncFutureImpl<Tuple2<Boolean, U>> ret = makeNewFuture();
completableFuture
.thenAccept(
(t) -> {
callbackRunner.submit(
() -> {
boolean test = condition.apply(t);
U r = test ? actionIfTrue.apply(t) : null;
ret.completeInCallbackRunner(Tuple2.of(test, r));
callbackFinished();
});
})
.exceptionally(
(e) -> {
exceptionHandler.handleException(
"Caught exception when submitting AsyncFuture's callback.",
e);
return null;
});
return ret;
}
}
@Override
public InternalAsyncFuture<Boolean> thenConditionallyAccept(
FunctionWithException<? super T, Boolean, ? extends Exception> condition,
ThrowingConsumer<? super T, ? extends Exception> actionIfTrue,
ThrowingConsumer<? super T, ? extends Exception> actionIfFalse) {
callbackRegistered();
if (completableFuture.isDone()) {
// this branch must be invoked in task thread when expected
T t;
try {
t = completableFuture.get();
} catch (Exception e) {
exceptionHandler.handleException(
"Caught exception when processing completed AsyncFuture's callback.", e);
return null;
}
boolean test = FunctionWithException.unchecked(condition).apply(t);
if (test) {
ThrowingConsumer.unchecked(actionIfTrue).accept(t);
} else {
ThrowingConsumer.unchecked(actionIfFalse).accept(t);
}
callbackFinished();
return InternalAsyncFutureUtils.completedFuture(test);
} else {
AsyncFutureImpl<Boolean> ret = makeNewFuture();
completableFuture
.thenAccept(
(t) -> {
callbackRunner.submit(
() -> {
boolean test = condition.apply(t);
if (test) {
actionIfTrue.accept(t);
} else {
actionIfFalse.accept(t);
}
ret.completeInCallbackRunner(test);
callbackFinished();
});
})
.exceptionally(
(e) -> {
exceptionHandler.handleException(
"Caught exception when submitting AsyncFuture's callback.",
e);
return null;
});
return ret;
}
}
@Override
public InternalAsyncFuture<Boolean> thenConditionallyAccept(
FunctionWithException<? super T, Boolean, ? extends Exception> condition,
ThrowingConsumer<? super T, ? extends Exception> actionIfTrue) {
return thenConditionallyAccept(condition, actionIfTrue, (b) -> {});
}
@Override
public <U, V> InternalAsyncFuture<Tuple2<Boolean, Object>> thenConditionallyCompose(
FunctionWithException<? super T, Boolean, ? extends Exception> condition,
FunctionWithException<? super T, ? extends StateFuture<U>, ? extends Exception>
actionIfTrue,
FunctionWithException<? super T, ? extends StateFuture<V>, ? extends Exception>
actionIfFalse) {
callbackRegistered();
if (completableFuture.isDone()) {
// this branch must be invoked in task thread when expected
T t;
try {
t = completableFuture.get();
} catch (Throwable e) {
exceptionHandler.handleException(
"Caught exception when processing completed AsyncFuture's callback.", e);
return null;
}
boolean test = FunctionWithException.unchecked(condition).apply(t);
StateFuture<?> actionResult;
if (test) {
actionResult = FunctionWithException.unchecked(actionIfTrue).apply(t);
} else {
actionResult = FunctionWithException.unchecked(actionIfFalse).apply(t);
}
AsyncFutureImpl<Tuple2<Boolean, Object>> ret = makeNewFuture();
actionResult.thenAccept(
(e) -> {
ret.completeInCallbackRunner(Tuple2.of(test, e));
});
callbackFinished();
return ret;
} else {
AsyncFutureImpl<Tuple2<Boolean, Object>> ret = makeNewFuture();
completableFuture
.thenAccept(
(t) -> {
callbackRunner.submit(
() -> {
boolean test = condition.apply(t);
StateFuture<?> actionResult;
if (test) {
actionResult = actionIfTrue.apply(t);
} else {
actionResult = actionIfFalse.apply(t);
}
actionResult.thenAccept(
(e) -> {
ret.completeInCallbackRunner(
Tuple2.of(test, e));
});
callbackFinished();
});
})
.exceptionally(
(e) -> {
exceptionHandler.handleException(
"Caught exception when submitting AsyncFuture's callback.",
e);
return null;
});
return ret;
}
}
@Override
public <U> InternalAsyncFuture<Tuple2<Boolean, U>> thenConditionallyCompose(
FunctionWithException<? super T, Boolean, ? extends Exception> condition,
FunctionWithException<? super T, ? extends StateFuture<U>, ? extends Exception>
actionIfTrue) {
callbackRegistered();
if (completableFuture.isDone()) {
// this branch must be invoked in task thread when expected
T t;
try {
t = completableFuture.get();
} catch (Throwable e) {
exceptionHandler.handleException(
"Caught exception when processing completed AsyncFuture's callback.", e);
return null;
}
boolean test = FunctionWithException.unchecked(condition).apply(t);
if (test) {
StateFuture<U> actionResult =
FunctionWithException.unchecked(actionIfTrue).apply(t);
AsyncFutureImpl<Tuple2<Boolean, U>> ret = makeNewFuture();
actionResult.thenAccept(
(e) -> {
ret.completeInCallbackRunner(Tuple2.of(true, e));
});
callbackFinished();
return ret;
} else {
callbackFinished();
return InternalAsyncFutureUtils.completedFuture(Tuple2.of(false, null));
}
} else {
AsyncFutureImpl<Tuple2<Boolean, U>> ret = makeNewFuture();
completableFuture
.thenAccept(
(t) -> {
callbackRunner.submit(
() -> {
boolean test = condition.apply(t);
if (test) {
StateFuture<U> actionResult = actionIfTrue.apply(t);
actionResult.thenAccept(
(e) -> {
ret.completeInCallbackRunner(
Tuple2.of(true, e));
});
} else {
ret.completeInCallbackRunner(
Tuple2.of(false, null));
}
callbackFinished();
});
})
.exceptionally(
(e) -> {
exceptionHandler.handleException(
"Caught exception when submitting AsyncFuture's callback.",
e);
return null;
});
return ret;
}
}
/**
* Make a new future based on context of this future. Subclasses need to overload this method to
* generate their own instances (if needed).
*
* @return the new created future.
*/
public <A> AsyncFutureImpl<A> makeNewFuture() {
return new AsyncFutureImpl<>(callbackRunner, exceptionHandler);
}
@Override
public boolean isDone() {
return completableFuture.isDone();
}
@Override
public T get() {
T t;
try {
t = completableFuture.get();
} catch (Exception e) {
exceptionHandler.handleException(
"Caught exception when getting AsyncFuture's result.", e);
return null;
}
return t;
}
@Override
public void complete(T result) {
if (completableFuture.isCompletedExceptionally()) {
throw new IllegalStateException("AsyncFuture already failed !");
}
completableFuture.complete(result);
postComplete(false);
}
@Override
public void completeExceptionally(String message, Throwable ex) {
exceptionHandler.handleException(message, ex);
}
private void completeInCallbackRunner(T result) {
completableFuture.complete(result);
postComplete(true);
}
/** Will be triggered when a callback is registered. */
public void callbackRegistered() {
// does nothing by default.
}
/** Will be triggered when this future completes. */
public void postComplete(boolean inCallbackRunner) {
// does nothing by default.
}
/** Will be triggered when a callback finishes processing. */
public void callbackFinished() {
// does nothing by default.
}
@Override
public void thenSyncAccept(ThrowingConsumer<? super T, ? extends Exception> action) {
completableFuture
.thenAccept(ThrowingConsumer.unchecked(action))
.exceptionally(
(e) -> {
exceptionHandler.handleException(
"Caught exception when processing completed AsyncFuture's callback.",
e);
return null;
});
}
/** The entry for a state future to submit task to mailbox. */
public
|
AsyncFutureImpl
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/PublicFieldFloatTest.java
|
{
"start": 197,
"end": 512
}
|
class ____ {
public float id;
}
public void test_codec() throws Exception {
VO vo = new VO();
vo.id = 123.4F;
String str = JSON.toJSONString(vo);
VO vo1 = JSON.parseObject(str, VO.class);
Assert.assertTrue(vo1.id == vo.id);
}
}
|
VO
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/buildextension/annotations/AddObservesTest.java
|
{
"start": 1985,
"end": 2173
}
|
class ____ {
static final AtomicBoolean OBSERVED = new AtomicBoolean();
public void observe(String event) {
OBSERVED.set(true);
}
}
}
|
IWantToObserve
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/dialect/sql/ast/SybaseSqmToSqlAstConverter.java
|
{
"start": 1056,
"end": 2708
}
|
class ____<T extends Statement> extends BaseSqmToSqlAstConverter<T> {
private boolean needsDummyTableGroup;
public SybaseSqmToSqlAstConverter(
SqmStatement<?> statement,
QueryOptions queryOptions,
DomainParameterXref domainParameterXref,
QueryParameterBindings domainParameterBindings,
LoadQueryInfluencers fetchInfluencers,
SqlAstCreationContext creationContext,
boolean deduplicateSelectionItems) {
super(
creationContext,
statement,
queryOptions,
fetchInfluencers,
domainParameterXref,
domainParameterBindings,
deduplicateSelectionItems
);
}
@Override
public QuerySpec visitQuerySpec(SqmQuerySpec<?> sqmQuerySpec) {
final boolean needsDummy = this.needsDummyTableGroup;
this.needsDummyTableGroup = false;
try {
final QuerySpec querySpec = super.visitQuerySpec( sqmQuerySpec );
if ( this.needsDummyTableGroup ) {
querySpec.getFromClause().addRoot(
new StandardTableGroup(
true,
null,
null,
null,
new NamedTableReference( "(select 1)", "dummy_(x)" ),
null,
getCreationContext().getSessionFactory()
)
);
}
return querySpec;
}
finally {
this.needsDummyTableGroup = needsDummy;
}
}
@Override
protected Expression resolveGroupOrOrderByExpression(SqmExpression<?> groupByClauseExpression) {
final Expression expression = super.resolveGroupOrOrderByExpression( groupByClauseExpression );
if ( expression instanceof Literal ) {
// Note that SqlAstTranslator.renderPartitionItem depends on this
this.needsDummyTableGroup = true;
}
return expression;
}
}
|
SybaseSqmToSqlAstConverter
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/script/field/vectors/ByteBinaryDenseVector.java
|
{
"start": 756,
"end": 5103
}
|
class ____ implements DenseVector {
public static final int MAGNITUDE_BYTES = 4;
private final BytesRef docVector;
protected final byte[] vectorValue;
protected final int dims;
private float[] floatDocVector;
private boolean magnitudeDecoded;
private float magnitude;
public ByteBinaryDenseVector(byte[] vectorValue, BytesRef docVector, int dims) {
this.docVector = docVector;
this.dims = dims;
this.vectorValue = vectorValue;
}
@Override
public float[] getVector() {
if (floatDocVector == null) {
floatDocVector = new float[dims];
for (int i = 0; i < dims; i++) {
floatDocVector[i] = vectorValue[i];
}
}
return floatDocVector;
}
@Override
public float getMagnitude() {
if (magnitudeDecoded == false) {
magnitude = ByteBuffer.wrap(docVector.bytes, docVector.offset + dims, MAGNITUDE_BYTES).getFloat();
magnitudeDecoded = true;
}
return magnitude;
}
@Override
public int dotProduct(byte[] queryVector) {
return VectorUtil.dotProduct(queryVector, vectorValue);
}
@Override
public double dotProduct(float[] queryVector) {
return ESVectorUtil.ipFloatByte(queryVector, vectorValue);
}
@Override
public double dotProduct(List<Number> queryVector) {
int result = 0;
for (int i = 0; i < queryVector.size(); i++) {
result += vectorValue[i] * queryVector.get(i).intValue();
}
return result;
}
@SuppressForbidden(reason = "used only for bytes so it cannot overflow")
private static int abs(int value) {
return Math.abs(value);
}
@Override
public int l1Norm(byte[] queryVector) {
int result = 0;
for (int i = 0; i < queryVector.length; i++) {
result += abs(vectorValue[i] - queryVector[i]);
}
return result;
}
@Override
public double l1Norm(float[] queryVector) {
throw new UnsupportedOperationException("use [int l1Norm(byte[] queryVector)] instead");
}
@Override
public double l1Norm(List<Number> queryVector) {
int result = 0;
for (int i = 0; i < queryVector.size(); i++) {
result += abs(vectorValue[i] - queryVector.get(i).intValue());
}
return result;
}
@Override
public int hamming(byte[] queryVector) {
return VectorUtil.xorBitCount(queryVector, vectorValue);
}
@Override
public int hamming(List<Number> queryVector) {
int distance = 0;
for (int i = 0; i < queryVector.size(); i++) {
distance += Integer.bitCount((queryVector.get(i).intValue() ^ vectorValue[i]) & 0xFF);
}
return distance;
}
@Override
public double l2Norm(byte[] queryVector) {
return Math.sqrt(VectorUtil.squareDistance(queryVector, vectorValue));
}
@Override
public double l2Norm(float[] queryVector) {
throw new UnsupportedOperationException("use [double l2Norm(byte[] queryVector)] instead");
}
@Override
public double l2Norm(List<Number> queryVector) {
int result = 0;
for (int i = 0; i < queryVector.size(); i++) {
int diff = vectorValue[i] - queryVector.get(i).intValue();
result += diff * diff;
}
return Math.sqrt(result);
}
@Override
public double cosineSimilarity(byte[] queryVector, float qvMagnitude) {
return dotProduct(queryVector) / (qvMagnitude * getMagnitude());
}
@Override
public double cosineSimilarity(float[] queryVector, boolean normalizeQueryVector) {
if (normalizeQueryVector) {
return dotProduct(queryVector) / (DenseVector.getMagnitude(queryVector) * getMagnitude());
}
return dotProduct(queryVector) / getMagnitude();
}
@Override
public double cosineSimilarity(List<Number> queryVector) {
return dotProduct(queryVector) / (DenseVector.getMagnitude(queryVector) * getMagnitude());
}
@Override
public int size() {
return 1;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public int getDims() {
return dims;
}
}
|
ByteBinaryDenseVector
|
java
|
alibaba__nacos
|
config/src/main/java/com/alibaba/nacos/config/server/model/ConfigAllInfo.java
|
{
"start": 718,
"end": 2396
}
|
class ____ extends ConfigInfo {
private static final long serialVersionUID = 296578467953931353L;
private long createTime;
private long modifyTime;
private String createUser;
private String createIp;
private String use;
private String effect;
private String schema;
public ConfigAllInfo() {
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public long getModifyTime() {
return modifyTime;
}
public void setModifyTime(long modifyTime) {
this.modifyTime = modifyTime;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public String getCreateIp() {
return createIp;
}
public void setCreateIp(String createIp) {
this.createIp = createIp;
}
public String getUse() {
return use;
}
public void setUse(String use) {
this.use = use;
}
public String getEffect() {
return effect;
}
public void setEffect(String effect) {
this.effect = effect;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
|
ConfigAllInfo
|
java
|
greenrobot__EventBus
|
EventBusTest/src/org/greenrobot/eventbus/indexed/EventBusGenericsTestWithIndex.java
|
{
"start": 776,
"end": 954
}
|
class ____ extends EventBusGenericsTest {
@Before
public void overwriteEventBus() throws Exception {
eventBus = Indexed.build();
}
}
|
EventBusGenericsTestWithIndex
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/StoredProcedureApiTests.java
|
{
"start": 922,
"end": 3101
}
|
class ____ {
@Test
public void parameterValueAccess(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
final ProcedureCall call = session.createStoredProcedureCall( "test" );
call.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN);
call.registerStoredProcedureParameter( 2, String.class, ParameterMode.OUT);
call.setParameter( 1, 1 );
call.getParameterValue( 1 );
}
);
}
@Test
public void parameterValueAccessByName(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
final ProcedureCall call = session.createStoredProcedureCall( "test" );
call.registerStoredProcedureParameter("a", Integer.class, ParameterMode.IN);
call.registerStoredProcedureParameter( "b", String.class, ParameterMode.OUT);
call.setParameter( "a", 1 );
call.getParameterValue( "a" );
}
);
}
@Test
public void testInvalidParameterReference(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
final ProcedureCall call1 = session.createStoredProcedureCall( "test" );
call1.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN);
final Parameter<Integer> p1_1 = (Parameter<Integer>) call1.getParameter( 1 );
call1.setParameter( 1, 1 );
final ProcedureCall call2 = session.createStoredProcedureCall( "test" );
call2.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN);
call2.setParameter( 1, 1 );
try {
call2.getParameterValue( p1_1 );
fail( "Expecting failure" );
}
catch (IllegalArgumentException expected) {
}
}
);
}
@Test
public void testParameterBindTypeMismatch(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
try {
final ProcedureCall call1 = session.createStoredProcedureCall( "test" );
call1.registerStoredProcedureParameter( 1, Integer.class, ParameterMode.IN );
call1.setParameter( 1, new Date() );
fail( "expecting failure" );
}
catch (IllegalArgumentException expected) {
}
}
);
}
@Entity( name = "Person" )
@Table( name = "person" )
public static
|
StoredProcedureApiTests
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/observers/SerializedObserverTest.java
|
{
"start": 27141,
"end": 31446
}
|
class ____ implements ObservableSource<String> {
final String[] values;
Thread t;
AtomicInteger threadsRunning = new AtomicInteger();
AtomicInteger maxConcurrentThreads = new AtomicInteger();
ExecutorService threadPool;
TestMultiThreadedObservable(String... values) {
this.values = values;
this.threadPool = Executors.newCachedThreadPool();
}
@Override
public void subscribe(final Observer<? super String> observer) {
observer.onSubscribe(Disposable.empty());
final NullPointerException npe = new NullPointerException();
System.out.println("TestMultiThreadedObservable subscribed to ...");
t = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("running TestMultiThreadedObservable thread");
int j = 0;
for (final String s : values) {
final int fj = ++j;
threadPool.execute(new Runnable() {
@Override
public void run() {
threadsRunning.incrementAndGet();
try {
// perform onNext call
System.out.println("TestMultiThreadedObservable onNext: " + s + " on thread " + Thread.currentThread().getName());
if (s == null) {
// force an error
throw npe;
} else {
// allow the exception to queue up
int sleep = (fj % 3) * 10;
if (sleep != 0) {
Thread.sleep(sleep);
}
}
observer.onNext(s);
// capture 'maxThreads'
int concurrentThreads = threadsRunning.get();
int maxThreads = maxConcurrentThreads.get();
if (concurrentThreads > maxThreads) {
maxConcurrentThreads.compareAndSet(maxThreads, concurrentThreads);
}
} catch (Throwable e) {
observer.onError(e);
} finally {
threadsRunning.decrementAndGet();
}
}
});
}
// we are done spawning threads
threadPool.shutdown();
} catch (Throwable e) {
throw new RuntimeException(e);
}
// wait until all threads are done, then mark it as COMPLETED
try {
// wait for all the threads to finish
if (!threadPool.awaitTermination(5, TimeUnit.SECONDS)) {
System.out.println("Threadpool did not terminate in time.");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
observer.onComplete();
}
});
System.out.println("starting TestMultiThreadedObservable thread");
t.start();
System.out.println("done starting TestMultiThreadedObservable thread");
}
public void waitToFinish() {
try {
t.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
static
|
TestMultiThreadedObservable
|
java
|
square__javapoet
|
src/main/java/com/squareup/javapoet/TypeName.java
|
{
"start": 1520,
"end": 2030
}
|
class ____ an identifier for primitive
* types like {@code int} and raw reference types like {@code String} and {@code List}. It also
* identifies composite types like {@code char[]} and {@code Set<Long>}.
*
* <p>Type names are dumb identifiers only and do not model the values they name. For example, the
* type name for {@code java.util.List} doesn't know about the {@code size()} method, the fact that
* lists are collections, or even that it accepts a single type parameter.
*
* <p>Instances of this
|
is
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/injection/guice/internal/MoreTypes.java
|
{
"start": 12996,
"end": 15053
}
|
interface
____ (toResolve.isInterface()) {
Class<?>[] interfaces = rawType.getInterfaces();
for (int i = 0, length = interfaces.length; i < length; i++) {
if (interfaces[i] == toResolve) {
return rawType.getGenericInterfaces()[i];
} else if (toResolve.isAssignableFrom(interfaces[i])) {
return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], toResolve);
}
}
}
// check our supertypes
if (rawType.isInterface() == false) {
while (rawType != Object.class) {
Class<?> rawSupertype = rawType.getSuperclass();
if (rawSupertype == toResolve) {
return rawType.getGenericSuperclass();
} else if (toResolve.isAssignableFrom(rawSupertype)) {
return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, toResolve);
}
rawType = rawSupertype;
}
}
// we can't resolve this further
return toResolve;
}
public static Type resolveTypeVariable(Type type, Class<?> rawType, TypeVariable<?> unknown) {
Class<?> declaredByRaw = declaringClassOf(unknown);
// we can't reduce this further
if (declaredByRaw == null) {
return unknown;
}
Type declaredBy = getGenericSupertype(type, rawType, declaredByRaw);
if (declaredBy instanceof ParameterizedType) {
int index = indexOf(declaredByRaw.getTypeParameters(), unknown);
return ((ParameterizedType) declaredBy).getActualTypeArguments()[index];
}
return unknown;
}
private static int indexOf(Object[] array, Object toFind) {
for (int i = 0; i < array.length; i++) {
if (toFind.equals(array[i])) {
return i;
}
}
throw new NoSuchElementException();
}
/**
* Returns the declaring
|
if
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java
|
{
"start": 22005,
"end": 22571
}
|
class ____ {
private final String name;
private final int counter;
MultiConstructorProperties(String name, int counter) {
this.name = name;
this.counter = counter;
}
@ConstructorBinding
MultiConstructorProperties(@DefaultValue("test") String name) {
this.name = name;
this.counter = 42;
}
public String getName() {
return this.name;
}
public int getCounter() {
return this.counter;
}
}
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(AutowiredProperties.class)
static
|
MultiConstructorProperties
|
java
|
quarkusio__quarkus
|
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/requestcontext/RequestContextTest.java
|
{
"start": 3563,
"end": 3839
}
|
class ____ {
@Inject
RequestScopedBean bean;
@OnTextMessage
String process(String message) throws InterruptedException {
return bean.appendId(message);
}
}
@WebSocket(path = "/append")
public static
|
AppendBlocking
|
java
|
hibernate__hibernate-orm
|
hibernate-testing/src/main/java/org/hibernate/testing/orm/domain/gambit/EntityWithOneToManyNotOwned.java
|
{
"start": 349,
"end": 949
}
|
class ____ {
private Integer id;
private List<EntityWithManyToOneWithoutJoinTable> children = new ArrayList<>();
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@OneToMany(mappedBy = "owner")
public List<EntityWithManyToOneWithoutJoinTable> getChildren() {
return children;
}
public void setChildren(List<EntityWithManyToOneWithoutJoinTable> children) {
this.children = children;
}
public void addChild(EntityWithManyToOneWithoutJoinTable child) {
child.setOwner( this );
getChildren().add( child );
}
}
|
EntityWithOneToManyNotOwned
|
java
|
quarkusio__quarkus
|
extensions/tls-registry/cli/src/test/java/io/quarkus/tls/cli/SelfSignedGenerationTest.java
|
{
"start": 264,
"end": 1299
}
|
class ____ {
@AfterAll
static void cleanup() {
// File generated during the generation.
File file = new File(".env");
if (file.isFile()) {
file.delete();
}
}
@Test
public void testSelfSignedGeneration() throws Exception {
GenerateCertificateCommand command = new GenerateCertificateCommand();
command.name = "test";
command.renew = true;
command.selfSigned = true;
command.directory = Path.of("target");
command.password = "password";
command.call();
File file = new File("target/test-keystore.p12");
Assertions.assertTrue(file.exists());
KeyStore ks = KeyStore.getInstance("PKCS12");
try (FileInputStream fis = new FileInputStream(file)) {
ks.load(fis, "password".toCharArray());
Assertions.assertNotNull(ks.getCertificate("test"));
Assertions.assertNotNull(ks.getKey("test", "password".toCharArray()));
}
}
}
|
SelfSignedGenerationTest
|
java
|
apache__camel
|
components/camel-sql/src/generated/java/org/apache/camel/component/sql/stored/SqlStoredComponentConfigurer.java
|
{
"start": 737,
"end": 3137
}
|
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
SqlStoredComponent target = (SqlStoredComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "datasource":
case "dataSource": target.setDataSource(property(camelContext, javax.sql.DataSource.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "servicelocationenabled":
case "serviceLocationEnabled": target.setServiceLocationEnabled(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public String[] getAutowiredNames() {
return new String[]{"dataSource"};
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "datasource":
case "dataSource": return javax.sql.DataSource.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "servicelocationenabled":
case "serviceLocationEnabled": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
SqlStoredComponent target = (SqlStoredComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "datasource":
case "dataSource": return target.getDataSource();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "servicelocationenabled":
case "serviceLocationEnabled": return target.isServiceLocationEnabled();
default: return null;
}
}
}
|
SqlStoredComponentConfigurer
|
java
|
junit-team__junit5
|
platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java
|
{
"start": 9659,
"end": 10036
}
|
class ____ {
}
LauncherDiscoveryRequest request = builder.applySelectorsAndFiltersFromSuite(Suite.class).build();
List<PostDiscoveryFilter> filters = request.getPostDiscoveryFilters();
TestDescriptor testDescriptor = new StubAbstractTestDescriptor();
assertTrue(exactlyOne(filters).apply(testDescriptor).included());
}
@Test
void selectClassesByReference() {
|
Suite
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/external/response/streaming/StreamingInferenceTestUtils.java
|
{
"start": 625,
"end": 1591
}
|
class ____ {
public static Deque<ServerSentEvent> events(String... data) {
var item = new ArrayDeque<ServerSentEvent>();
Arrays.stream(data).map(ServerSentEvent::new).forEach(item::offer);
return item;
}
public static Deque<ServerSentEvent> events(List<Pair<String, String>> data) {
var item = new ArrayDeque<ServerSentEvent>();
data.forEach(pair -> item.offer(new ServerSentEvent(pair.getKey(), pair.getValue())));
return item;
}
@SuppressWarnings("unchecked")
public static Matcher<Iterable<? extends StreamingChatCompletionResults.Result>> containsResults(String... results) {
Matcher<StreamingChatCompletionResults.Result>[] resultMatcher = Arrays.stream(results)
.map(StreamingChatCompletionResults.Result::new)
.map(Matchers::equalTo)
.toArray(Matcher[]::new);
return Matchers.contains(resultMatcher);
}
}
|
StreamingInferenceTestUtils
|
java
|
apache__dubbo
|
dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ProviderBuilder.java
|
{
"start": 990,
"end": 7384
}
|
class ____ extends AbstractServiceBuilder<ProviderConfig, ProviderBuilder> {
/**
* Service ip addresses (used when there are multiple network cards available)
*/
private String host;
/**
* Service port
*/
private Integer port;
/**
* Context path
*/
private String contextpath;
/**
* Thread pool
*/
private String threadpool;
/**
* Thread pool name
*/
private String threadname;
/**
* Thread pool size (fixed size)
*/
private Integer threads;
/**
* IO thread pool size (fixed size)
*/
private Integer iothreads;
/**
* Thread pool keepAliveTime, default unit TimeUnit.MILLISECONDS
*/
private Integer alive;
/**
* Thread pool queue length
*/
private Integer queues;
/**
* Max acceptable connections
*/
private Integer accepts;
/**
* Protocol codec
*/
private String codec;
/**
* The serialization charset
*/
private String charset;
/**
* Payload max length
*/
private Integer payload;
/**
* The network io buffer size
*/
private Integer buffer;
/**
* Transporter
*/
private String transporter;
/**
* How information gets exchanged
*/
private String exchanger;
/**
* Thread dispatching mode
*/
private String dispatcher;
/**
* Networker
*/
private String networker;
/**
* The server-side implementation model of the protocol
*/
private String server;
/**
* The client-side implementation model of the protocol
*/
private String client;
/**
* Supported telnet commands, separated with comma.
*/
private String telnet;
/**
* Command line prompt
*/
private String prompt;
/**
* Status check
*/
private String status;
/**
* Wait time when stop
*/
private Integer wait;
/**
* Whether to use the default protocol
*/
private Boolean isDefault;
public static ProviderBuilder newBuilder() {
return new ProviderBuilder();
}
public ProviderBuilder host(String host) {
this.host = host;
return getThis();
}
public ProviderBuilder port(Integer port) {
this.port = port;
return getThis();
}
public ProviderBuilder contextPath(String contextPath) {
this.contextpath = contextPath;
return getThis();
}
public ProviderBuilder threadPool(String threadPool) {
this.threadpool = threadPool;
return getThis();
}
public ProviderBuilder threadName(String threadName) {
this.threadname = threadName;
return getThis();
}
public ProviderBuilder threads(Integer threads) {
this.threads = threads;
return getThis();
}
public ProviderBuilder ioThreads(Integer ioThreads) {
this.iothreads = ioThreads;
return getThis();
}
public ProviderBuilder alive(Integer alive) {
this.alive = alive;
return getThis();
}
public ProviderBuilder queues(Integer queues) {
this.queues = queues;
return getThis();
}
public ProviderBuilder accepts(Integer accepts) {
this.accepts = accepts;
return getThis();
}
public ProviderBuilder codec(String codec) {
this.codec = codec;
return getThis();
}
public ProviderBuilder charset(String charset) {
this.charset = charset;
return getThis();
}
public ProviderBuilder payload(Integer payload) {
this.payload = payload;
return getThis();
}
public ProviderBuilder buffer(Integer buffer) {
this.buffer = buffer;
return getThis();
}
public ProviderBuilder transporter(String transporter) {
this.transporter = transporter;
return getThis();
}
public ProviderBuilder exchanger(String exchanger) {
this.exchanger = exchanger;
return getThis();
}
public ProviderBuilder dispatcher(String dispatcher) {
this.dispatcher = dispatcher;
return getThis();
}
public ProviderBuilder networker(String networker) {
this.networker = networker;
return getThis();
}
public ProviderBuilder server(String server) {
this.server = server;
return getThis();
}
public ProviderBuilder client(String client) {
this.client = client;
return getThis();
}
public ProviderBuilder telnet(String telnet) {
this.telnet = telnet;
return getThis();
}
public ProviderBuilder prompt(String prompt) {
this.prompt = prompt;
return getThis();
}
public ProviderBuilder status(String status) {
this.status = status;
return getThis();
}
public ProviderBuilder wait(Integer wait) {
this.wait = wait;
return getThis();
}
public ProviderBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public ProviderConfig build() {
ProviderConfig provider = new ProviderConfig();
super.build(provider);
provider.setHost(host);
provider.setPort(port);
provider.setContextpath(contextpath);
provider.setThreadpool(threadpool);
provider.setThreadname(threadname);
provider.setThreads(threads);
provider.setIothreads(iothreads);
provider.setAlive(alive);
provider.setQueues(queues);
provider.setAccepts(accepts);
provider.setCodec(codec);
provider.setPayload(payload);
provider.setCharset(charset);
provider.setBuffer(buffer);
provider.setTransporter(transporter);
provider.setExchanger(exchanger);
provider.setDispatcher(dispatcher);
provider.setNetworker(networker);
provider.setServer(server);
provider.setClient(client);
provider.setTelnet(telnet);
provider.setPrompt(prompt);
provider.setStatus(status);
provider.setWait(wait);
provider.setDefault(isDefault);
return provider;
}
@Override
protected ProviderBuilder getThis() {
return this;
}
}
|
ProviderBuilder
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GitHubEndpointBuilderFactory.java
|
{
"start": 35303,
"end": 37871
}
|
interface ____ extends EndpointProducerBuilder {
default GitHubEndpointProducerBuilder basic() {
return (GitHubEndpointProducerBuilder) this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedGitHubEndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedGitHubEndpointProducerBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
}
/**
* Builder for endpoint for the GitHub component.
*/
public
|
AdvancedGitHubEndpointProducerBuilder
|
java
|
google__guava
|
android/guava/src/com/google/common/collect/ImmutableMultiset.java
|
{
"start": 2203,
"end": 4878
}
|
class ____<E> extends ImmutableCollection<E> implements Multiset<E> {
/**
* Returns a {@code Collector} that accumulates the input elements into a new {@code
* ImmutableMultiset}. Elements iterate in order by the <i>first</i> appearance of that element in
* encounter order.
*
* @since 33.2.0 (available since 21.0 in guava-jre)
*/
@IgnoreJRERequirement // Users will use this only if they're already using streams.
public static <E> Collector<E, ?, ImmutableMultiset<E>> toImmutableMultiset() {
return CollectCollectors.toImmutableMultiset(Function.identity(), e -> 1);
}
/**
* Returns a {@code Collector} that accumulates elements into an {@code ImmutableMultiset} whose
* elements are the result of applying {@code elementFunction} to the inputs, with counts equal to
* the result of applying {@code countFunction} to the inputs.
*
* <p>If the mapped elements contain duplicates (according to {@link Object#equals}), the first
* occurrence in encounter order appears in the resulting multiset, with count equal to the sum of
* the outputs of {@code countFunction.applyAsInt(t)} for each {@code t} mapped to that element.
*
* @since 33.2.0 (available since 22.0 in guava-jre)
*/
@IgnoreJRERequirement // Users will use this only if they're already using streams.
public static <T extends @Nullable Object, E>
Collector<T, ?, ImmutableMultiset<E>> toImmutableMultiset(
Function<? super T, ? extends E> elementFunction,
ToIntFunction<? super T> countFunction) {
return CollectCollectors.toImmutableMultiset(elementFunction, countFunction);
}
/**
* Returns the empty immutable multiset.
*
* <p><b>Performance note:</b> the instance returned is a singleton.
*/
@SuppressWarnings("unchecked") // all supported methods are covariant
public static <E> ImmutableMultiset<E> of() {
return (ImmutableMultiset<E>) RegularImmutableMultiset.EMPTY;
}
/**
* Returns an immutable multiset containing a single element.
*
* @throws NullPointerException if the element is null
* @since 6.0 (source-compatible since 2.0)
*/
public static <E> ImmutableMultiset<E> of(E e1) {
return copyFromElements(e1);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
public static <E> ImmutableMultiset<E> of(E e1, E e2) {
return copyFromElements(e1, e2);
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the
|
ImmutableMultiset
|
java
|
apache__flink
|
flink-end-to-end-tests/flink-batch-sql-test/src/test/java/org/apache/flink/sql/tests/Generator.java
|
{
"start": 1282,
"end": 2963
}
|
class ____ implements FromElementsSource.ElementsSupplier<RowData> {
private static final long serialVersionUID = -8455653458083514261L;
private final List<Row> elements;
static Generator create(
int numKeys, float rowsPerKeyAndSecond, int durationSeconds, int offsetSeconds) {
final int stepMs = (int) (1000 / rowsPerKeyAndSecond);
final long durationMs = durationSeconds * 1000L;
final long offsetMs = offsetSeconds * 2000L;
final List<Row> elements = new ArrayList<>();
int keyIndex = 0;
long ms = 0;
while (ms < durationMs) {
elements.add(createRow(keyIndex++, ms, offsetMs));
if (keyIndex >= numKeys) {
keyIndex = 0;
ms += stepMs;
}
}
return new Generator(elements);
}
private static Row createRow(int keyIndex, long milliseconds, long offsetMillis) {
return Row.of(
keyIndex,
LocalDateTime.ofInstant(
Instant.ofEpochMilli(milliseconds + offsetMillis), ZoneOffset.UTC),
"Some payload...");
}
private Generator(List<Row> elements) {
this.elements = elements;
}
@Override
public int numElements() {
return elements.size();
}
@Override
public RowData get(int offset) {
Row row = elements.get(offset);
int idx = row.getFieldAs(0);
LocalDateTime ts = row.getFieldAs(1);
String payload = row.getFieldAs(2);
return GenericRowData.of(
idx, TimestampData.fromLocalDateTime(ts), StringData.fromString(payload));
}
}
|
Generator
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/DummyCommonNodeLabelsManager.java
|
{
"start": 1187,
"end": 2677
}
|
class ____ extends CommonNodeLabelsManager {
Map<NodeId, Set<String>> lastNodeToLabels = null;
Collection<NodeLabel> lastAddedlabels = null;
Collection<String> lastRemovedlabels = null;
@Override
public void initNodeLabelStore(Configuration conf) {
this.store = new NodeLabelsStore() {
@Override
public void recover()
throws IOException {
}
@Override
public void init(Configuration conf, CommonNodeLabelsManager mgr)
throws Exception {
}
@Override
public void removeClusterNodeLabels(Collection<String> labels)
throws IOException {
lastRemovedlabels = labels;
}
@Override
public void updateNodeToLabelsMappings(
Map<NodeId, Set<String>> nodeToLabels) throws IOException {
lastNodeToLabels = nodeToLabels;
}
@Override
public void storeNewClusterNodeLabels(List<NodeLabel> label) throws IOException {
lastAddedlabels = label;
}
@Override
public void close() throws IOException {
// do nothing
}
};
}
@Override
protected void initDispatcher(Configuration conf) {
super.dispatcher = new InlineDispatcher();
}
@Override
protected void startDispatcher() {
// do nothing
}
@Override
protected void stopDispatcher() {
// do nothing
}
@Override
protected void serviceStop() throws Exception {
super.serviceStop();
}
}
|
DummyCommonNodeLabelsManager
|
java
|
apache__kafka
|
jmh-benchmarks/src/main/java/org/apache/kafka/jmh/server/CheckpointBench.java
|
{
"start": 2958,
"end": 7102
}
|
class ____ {
@Param({"100", "1000", "2000"})
public int numTopics;
@Param({"3"})
public int numPartitions;
private final String topicName = "foo";
private Scheduler scheduler;
private Metrics metrics;
private MockTime time;
private KafkaConfig brokerProperties;
private ReplicaManager replicaManager;
private QuotaFactory.QuotaManagers quotaManagers;
private LogDirFailureChannel failureChannel;
private LogManager logManager;
private AlterPartitionManager alterPartitionManager;
@Setup(Level.Trial)
public void setup() {
this.scheduler = new KafkaScheduler(1, true, "scheduler-thread");
this.brokerProperties = KafkaConfig.fromProps(TestUtils.createBrokerConfig(
0, true, true, 9092, Option.empty(), Option.empty(),
Option.empty(), true, false, 0, false, 0, false, 0, Option.empty(), 1, true, 1,
(short) 1, false));
this.metrics = new Metrics();
this.time = new MockTime();
this.failureChannel = new LogDirFailureChannel(brokerProperties.logDirs().size());
final List<File> files = brokerProperties.logDirs().stream().map(File::new).toList();
this.logManager = TestUtils.createLogManager(CollectionConverters.asScala(files),
new LogConfig(new Properties()), new MockConfigRepository(), new CleanerConfig(1, 4 * 1024 * 1024L, 0.9d,
1024 * 1024, 32 * 1024 * 1024, Double.MAX_VALUE, 15 * 1000, true), time, 4, false, Option.empty(), false, ServerLogConfigs.LOG_INITIAL_TASK_DELAY_MS_DEFAULT);
scheduler.startup();
final BrokerTopicStats brokerTopicStats = new BrokerTopicStats(false);
final MetadataCache metadataCache =
new KRaftMetadataCache(this.brokerProperties.brokerId(), () -> KRAFT_VERSION_1);
this.quotaManagers =
QuotaFactory.instantiate(this.brokerProperties,
this.metrics,
this.time, "", "");
this.alterPartitionManager = TestUtils.createAlterIsrManager();
this.replicaManager = new ReplicaManagerBuilder().
setConfig(brokerProperties).
setMetrics(metrics).
setTime(time).
setScheduler(scheduler).
setLogManager(logManager).
setQuotaManagers(quotaManagers).
setBrokerTopicStats(brokerTopicStats).
setMetadataCache(metadataCache).
setLogDirFailureChannel(failureChannel).
setAlterPartitionManager(alterPartitionManager).
build();
replicaManager.startup();
List<TopicPartition> topicPartitions = new ArrayList<>();
for (int topicNum = 0; topicNum < numTopics; topicNum++) {
final String topicName = this.topicName + "-" + topicNum;
for (int partitionNum = 0; partitionNum < numPartitions; partitionNum++) {
topicPartitions.add(new TopicPartition(topicName, partitionNum));
}
}
OffsetCheckpoints checkpoints = (logDir, topicPartition) -> Optional.of(0L);
for (TopicPartition topicPartition : topicPartitions) {
final Partition partition = this.replicaManager.createPartition(topicPartition);
partition.createLogIfNotExists(true, false, checkpoints, Option.apply(Uuid.randomUuid()), Option.empty());
}
replicaManager.checkpointHighWatermarks();
}
@TearDown(Level.Trial)
public void tearDown() throws Exception {
this.replicaManager.shutdown(false);
this.metrics.close();
this.scheduler.shutdown();
this.quotaManagers.shutdown();
for (File dir : CollectionConverters.asJavaCollection(logManager.liveLogDirs())) {
Utils.delete(dir);
}
}
@Benchmark
@Threads(1)
public void measureCheckpointHighWatermarks() {
this.replicaManager.checkpointHighWatermarks();
}
@Benchmark
@Threads(1)
public void measureCheckpointLogStartOffsets() {
this.logManager.checkpointLogStartOffsets();
}
}
|
CheckpointBench
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/alternatives/priority/AlternativePriorityAnnotationTest.java
|
{
"start": 3712,
"end": 3885
}
|
class ____ implements MyInterface {
@Override
public String ping() {
return TheUltimateImpl.class.getSimpleName();
}
}
}
|
TheUltimateImpl
|
java
|
apache__camel
|
components/camel-metrics/src/test/java/org/apache/camel/component/metrics/MetricsComponentTest.java
|
{
"start": 2101,
"end": 11532
}
|
class ____ {
@Mock
private CamelContext camelContext;
@Mock
private ExtendedCamelContext ecc;
@Mock
private Registry camelRegistry;
@Mock
private MetricRegistry metricRegistry;
private InOrder inOrder;
private MetricsComponent component;
@BeforeEach
public void setUp() {
component = new MetricsComponent();
inOrder = Mockito.inOrder(camelContext, camelRegistry, metricRegistry);
}
@Test
public void testCreateEndpoint() throws Exception {
component.setCamelContext(camelContext);
when(camelContext.getRegistry()).thenReturn(camelRegistry);
when(camelContext.resolvePropertyPlaceholders(anyString())).then(returnsFirstArg());
when(camelRegistry.lookupByNameAndType(MetricsComponent.METRIC_REGISTRY_NAME, MetricRegistry.class))
.thenReturn(metricRegistry);
when(camelContext.getCamelContextExtension()).thenReturn(ecc);
when(PluginHelper.getBeanIntrospection(ecc)).thenReturn(new DefaultBeanIntrospection());
when(PluginHelper.getConfigurerResolver(ecc)).thenReturn((name, context) -> null);
Map<String, Object> params = new HashMap<>();
Long value = System.currentTimeMillis();
params.put("mark", value);
component.init();
Endpoint result = component.createEndpoint("metrics:meter:long.meter", "meter:long.meter", params);
assertThat(result, is(notNullValue()));
assertThat(result, is(instanceOf(MetricsEndpoint.class)));
MetricsEndpoint me = (MetricsEndpoint) result;
assertThat(me.getMark(), is(value));
assertThat(me.getMetricsName(), is("long.meter"));
assertThat(me.getRegistry(), is(metricRegistry));
inOrder.verify(camelContext, times(1)).getRegistry();
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType(MetricsComponent.METRIC_REGISTRY_NAME,
MetricRegistry.class);
inOrder.verify(camelContext, times(1)).getTypeConverter();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testCreateEndpoints() throws Exception {
component.setCamelContext(camelContext);
when(camelContext.getRegistry()).thenReturn(camelRegistry);
when(camelContext.resolvePropertyPlaceholders(anyString())).then(returnsFirstArg());
when(camelRegistry.lookupByNameAndType(MetricsComponent.METRIC_REGISTRY_NAME, MetricRegistry.class))
.thenReturn(metricRegistry);
when(camelContext.getCamelContextExtension()).thenReturn(ecc);
when(PluginHelper.getBeanIntrospection(ecc)).thenReturn(new DefaultBeanIntrospection());
when(PluginHelper.getConfigurerResolver(ecc)).thenReturn((name, context) -> null);
Map<String, Object> params = new HashMap<>();
long value = System.currentTimeMillis();
params.put("mark", value);
component.init();
Endpoint result = component.createEndpoint("metrics:meter:long.meter", "meter:long.meter", params);
assertThat(result, is(notNullValue()));
assertThat(result, is(instanceOf(MetricsEndpoint.class)));
MetricsEndpoint me = (MetricsEndpoint) result;
assertThat(me.getMark(), is(value));
assertThat(me.getMetricsName(), is("long.meter"));
assertThat(me.getRegistry(), is(metricRegistry));
params = new HashMap<>();
params.put("increment", value + 1);
params.put("decrement", value - 1);
result = component.createEndpoint("metrics:counter:long.counter", "counter:long.counter", params);
assertThat(result, is(notNullValue()));
assertThat(result, is(instanceOf(MetricsEndpoint.class)));
MetricsEndpoint ce = (MetricsEndpoint) result;
assertThat(ce.getIncrement(), is(value + 1));
assertThat(ce.getDecrement(), is(value - 1));
assertThat(ce.getMetricsName(), is("long.counter"));
assertThat(ce.getRegistry(), is(metricRegistry));
inOrder.verify(camelContext, times(1)).getRegistry();
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType(MetricsComponent.METRIC_REGISTRY_NAME,
MetricRegistry.class);
inOrder.verify(camelContext, times(3)).getTypeConverter();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testGetMetricsName() {
assertThat(component.getMetricsName("meter:metric-a"), is("metric-a"));
assertThat(component.getMetricsName("meter:metric-a:sub-b"), is("metric-a:sub-b"));
assertThat(component.getMetricsName("metric-a"), is("metric-a"));
assertThat(component.getMetricsName("//metric-a"), is("//metric-a"));
assertThat(component.getMetricsName("meter://metric-a"), is("//metric-a"));
}
@Test
public void testCreateNewEndpointForCounter() {
Endpoint endpoint = new MetricsEndpoint(null, null, metricRegistry, MetricsType.COUNTER, "a name");
assertThat(endpoint, is(notNullValue()));
assertThat(endpoint, is(instanceOf(MetricsEndpoint.class)));
}
@Test
public void testCreateNewEndpointForMeter() {
Endpoint endpoint = new MetricsEndpoint(null, null, metricRegistry, MetricsType.METER, "a name");
assertThat(endpoint, is(notNullValue()));
assertThat(endpoint, is(instanceOf(MetricsEndpoint.class)));
}
@Test
public void testCreateNewEndpointForGauge() {
MetricsEndpoint endpoint = new MetricsEndpoint(null, null, metricRegistry, MetricsType.GAUGE, "a name");
assertThat(endpoint, is(notNullValue()));
assertThat(endpoint, is(instanceOf(MetricsEndpoint.class)));
}
@Test
public void testCreateNewEndpointForHistogram() {
Endpoint endpoint = new MetricsEndpoint(null, null, metricRegistry, MetricsType.HISTOGRAM, "a name");
assertThat(endpoint, is(notNullValue()));
assertThat(endpoint, is(instanceOf(MetricsEndpoint.class)));
}
@Test
public void testCreateNewEndpointForTimer() {
Endpoint endpoint = new MetricsEndpoint(null, null, metricRegistry, MetricsType.TIMER, "a name");
assertThat(endpoint, is(notNullValue()));
assertThat(endpoint, is(instanceOf(MetricsEndpoint.class)));
}
@Test
public void testGetMetricsType() {
for (MetricsType type : EnumSet.allOf(MetricsType.class)) {
assertThat(component.getMetricsType(type.toString() + ":metrics-name"), is(type));
}
}
@Test
public void testGetMetricsTypeNotSet() {
assertThat(component.getMetricsType("no-metrics-type"), is(MetricsComponent.DEFAULT_METRICS_TYPE));
}
@Test
public void testGetMetricsTypeNotFound() {
assertThrows(RuntimeCamelException.class,
() -> component.getMetricsType("unknown-metrics:metrics-name"));
}
@Test
public void testGetOrCreateMetricRegistryFoundInCamelRegistry() {
when(camelRegistry.lookupByNameAndType("name", MetricRegistry.class)).thenReturn(metricRegistry);
MetricRegistry result = MetricsComponent.getOrCreateMetricRegistry(camelRegistry, "name");
assertThat(result, is(metricRegistry));
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", MetricRegistry.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testGetOrCreateMetricRegistryFoundInCamelRegistryByType() {
when(camelRegistry.lookupByNameAndType("name", MetricRegistry.class)).thenReturn(null);
when(camelRegistry.findByType(MetricRegistry.class)).thenReturn(Collections.singleton(metricRegistry));
MetricRegistry result = MetricsComponent.getOrCreateMetricRegistry(camelRegistry, "name");
assertThat(result, is(metricRegistry));
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", MetricRegistry.class);
inOrder.verify(camelRegistry, times(1)).findByType(MetricRegistry.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testGetOrCreateMetricRegistryNotFoundInCamelRegistry() {
when(camelRegistry.lookupByNameAndType("name", MetricRegistry.class)).thenReturn(null);
when(camelRegistry.findByType(MetricRegistry.class)).thenReturn(Collections.<MetricRegistry> emptySet());
MetricRegistry result = MetricsComponent.getOrCreateMetricRegistry(camelRegistry, "name");
assertThat(result, is(notNullValue()));
assertThat(result, is(not(metricRegistry)));
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", MetricRegistry.class);
inOrder.verify(camelRegistry, times(1)).findByType(MetricRegistry.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testGetMetricRegistryFromCamelRegistry() {
when(camelRegistry.lookupByNameAndType("name", MetricRegistry.class)).thenReturn(metricRegistry);
MetricRegistry result = MetricsComponent.getMetricRegistryFromCamelRegistry(camelRegistry, "name");
assertThat(result, is(metricRegistry));
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", MetricRegistry.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testCreateMetricRegistry() {
MetricRegistry registry = MetricsComponent.createMetricRegistry();
assertThat(registry, is(notNullValue()));
}
}
|
MetricsComponentTest
|
java
|
spring-projects__spring-framework
|
spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/DataBufferTestUtils.java
|
{
"start": 1044,
"end": 1585
}
|
class ____ {
/**
* Dump all the bytes in the given data buffer, and returns them as a byte array.
* <p>Note that this method reads the entire buffer into the heap, which might
* consume a lot of memory.
* @param buffer the data buffer to dump the bytes of
* @return the bytes in the given data buffer
*/
public static byte[] dumpBytes(DataBuffer buffer) {
Assert.notNull(buffer, "'buffer' must not be null");
byte[] bytes = new byte[buffer.readableByteCount()];
buffer.read(bytes);
return bytes;
}
}
|
DataBufferTestUtils
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configuration/EnableWebSecurityTests.java
|
{
"start": 6984,
"end": 7070
}
|
class ____ {
Child() {
}
}
@Configuration(proxyBeanMethods = false)
static
|
Child
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/score/DecayIntEvaluator.java
|
{
"start": 1184,
"end": 4640
}
|
class ____ implements EvalOperator.ExpressionEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(DecayIntEvaluator.class);
private final Source source;
private final EvalOperator.ExpressionEvaluator value;
private final int origin;
private final int scale;
private final int offset;
private final double decay;
private final Decay.DecayFunction decayFunction;
private final DriverContext driverContext;
private Warnings warnings;
public DecayIntEvaluator(Source source, EvalOperator.ExpressionEvaluator value, int origin,
int scale, int offset, double decay, Decay.DecayFunction decayFunction,
DriverContext driverContext) {
this.source = source;
this.value = value;
this.origin = origin;
this.scale = scale;
this.offset = offset;
this.decay = decay;
this.decayFunction = decayFunction;
this.driverContext = driverContext;
}
@Override
public Block eval(Page page) {
try (IntBlock valueBlock = (IntBlock) value.eval(page)) {
IntVector valueVector = valueBlock.asVector();
if (valueVector == null) {
return eval(page.getPositionCount(), valueBlock);
}
return eval(page.getPositionCount(), valueVector).asBlock();
}
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += value.baseRamBytesUsed();
return baseRamBytesUsed;
}
public DoubleBlock eval(int positionCount, IntBlock valueBlock) {
try(DoubleBlock.Builder result = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
switch (valueBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
int value = valueBlock.getInt(valueBlock.getFirstValueIndex(p));
result.appendDouble(Decay.process(value, this.origin, this.scale, this.offset, this.decay, this.decayFunction));
}
return result.build();
}
}
public DoubleVector eval(int positionCount, IntVector valueVector) {
try(DoubleVector.FixedBuilder result = driverContext.blockFactory().newDoubleVectorFixedBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
int value = valueVector.getInt(p);
result.appendDouble(p, Decay.process(value, this.origin, this.scale, this.offset, this.decay, this.decayFunction));
}
return result.build();
}
}
@Override
public String toString() {
return "DecayIntEvaluator[" + "value=" + value + ", origin=" + origin + ", scale=" + scale + ", offset=" + offset + ", decay=" + decay + ", decayFunction=" + decayFunction + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(value);
}
private Warnings warnings() {
if (warnings == null) {
this.warnings = Warnings.createWarnings(
driverContext.warningsMode(),
source.source().getLineNumber(),
source.source().getColumnNumber(),
source.text()
);
}
return warnings;
}
static
|
DecayIntEvaluator
|
java
|
spring-projects__spring-security
|
web/src/main/java/org/springframework/security/web/access/DelegatingMissingAuthorityAccessDeniedHandler.java
|
{
"start": 3708,
"end": 8313
}
|
class ____ implements AccessDeniedHandler {
private final ThrowableAnalyzer throwableAnalyzer = new ThrowableAnalyzer();
private final Map<String, AuthenticationEntryPoint> entryPoints;
private RequestCache requestCache = new NullRequestCache();
private AccessDeniedHandler defaultAccessDeniedHandler = new AccessDeniedHandlerImpl();
private DelegatingMissingAuthorityAccessDeniedHandler(Map<String, AuthenticationEntryPoint> entryPoints) {
Assert.notEmpty(entryPoints, "entryPoints cannot be empty");
this.entryPoints = entryPoints;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException denied)
throws IOException, ServletException {
List<AuthorityRequiredFactorErrorEntry> errorEntries = authorityErrors(denied);
List<RequiredFactorError> errors = errorEntries.stream()
.map(AuthorityRequiredFactorErrorEntry::getError)
.filter(Objects::nonNull)
.toList();
for (AuthorityRequiredFactorErrorEntry authorityError : errorEntries) {
String requiredAuthority = authorityError.getAuthority();
AuthenticationEntryPoint entryPoint = this.entryPoints.get(requiredAuthority);
if (entryPoint == null) {
continue;
}
this.requestCache.saveRequest(request, response);
if (!errors.isEmpty()) {
request.setAttribute(WebAttributes.REQUIRED_FACTOR_ERRORS, errors);
}
String message = String.format("Missing Authorities %s", requiredAuthority);
AuthenticationException ex = new InsufficientAuthenticationException(message, denied);
entryPoint.commence(request, response, ex);
return;
}
this.defaultAccessDeniedHandler.handle(request, response, denied);
}
/**
* Use this {@link AccessDeniedHandler} for {@link AccessDeniedException}s that this
* handler doesn't support. By default, this uses {@link AccessDeniedHandlerImpl}.
* @param defaultAccessDeniedHandler the default {@link AccessDeniedHandler} to use
*/
public void setDefaultAccessDeniedHandler(AccessDeniedHandler defaultAccessDeniedHandler) {
Assert.notNull(defaultAccessDeniedHandler, "defaultAccessDeniedHandler cannot be null");
this.defaultAccessDeniedHandler = defaultAccessDeniedHandler;
}
/**
* Use this {@link RequestCache} to remember the current request.
* <p>
* Uses {@link NullRequestCache} by default
* </p>
* @param requestCache the {@link RequestCache} to use
*/
public void setRequestCache(RequestCache requestCache) {
Assert.notNull(requestCache, "requestCachgrantedaue cannot be null");
this.requestCache = requestCache;
}
private List<AuthorityRequiredFactorErrorEntry> authorityErrors(AccessDeniedException ex) {
AuthorizationDeniedException denied = findAuthorizationDeniedException(ex);
if (denied == null) {
return List.of();
}
AuthorizationResult authorizationResult = denied.getAuthorizationResult();
if (authorizationResult instanceof FactorAuthorizationDecision factorDecision) {
// @formatter:off
return factorDecision.getFactorErrors().stream()
.map((error) -> {
String authority = error.getRequiredFactor().getAuthority();
return new AuthorityRequiredFactorErrorEntry(authority, error);
})
.collect(Collectors.toList());
// @formatter:on
}
if (authorizationResult instanceof AuthorityAuthorizationDecision authorityDecision) {
// @formatter:off
return authorityDecision.getAuthorities().stream()
.filter((ga) -> ga.getAuthority() != null)
.map((grantedAuthority) -> {
String authority = grantedAuthority.getAuthority();
if (authority.startsWith("FACTOR_")) {
RequiredFactor required = RequiredFactor.withAuthority(authority).build();
return new AuthorityRequiredFactorErrorEntry(authority, RequiredFactorError.createMissing(required));
}
else {
return new AuthorityRequiredFactorErrorEntry(authority, null);
}
})
.collect(Collectors.toList());
// @formatter:on
}
return List.of();
}
private @Nullable AuthorizationDeniedException findAuthorizationDeniedException(AccessDeniedException ex) {
if (ex instanceof AuthorizationDeniedException denied) {
return denied;
}
Throwable[] chain = this.throwableAnalyzer.determineCauseChain(ex);
return (AuthorizationDeniedException) this.throwableAnalyzer
.getFirstThrowableOfType(AuthorizationDeniedException.class, chain);
}
public static Builder builder() {
return new Builder();
}
/**
* A builder for configuring the set of authority/entry-point pairs
*
* @author Josh Cummings
* @since 7.0
*/
public static final
|
DelegatingMissingAuthorityAccessDeniedHandler
|
java
|
google__auto
|
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
|
{
"start": 45725,
"end": 46011
}
|
class ____ {
public abstract float aFloat();
public abstract double aDouble();
public static RedeclareFloatAndDouble of(float aFloat, double aDouble) {
return new AutoValue_AutoValueTest_RedeclareFloatAndDouble(aFloat, aDouble);
}
static
|
RedeclareFloatAndDouble
|
java
|
apache__maven
|
its/core-it-suite/src/test/java/org/apache/maven/it/MavenIT0113ServerAuthzAvailableToWagonMgrInPluginTest.java
|
{
"start": 994,
"end": 2007
}
|
class ____ extends AbstractMavenIntegrationTestCase {
/**
* Test that the auth infos given in the settings.xml are pushed into the wagon manager and are available
* to other components/plugins.
*
* @throws Exception in case of failure
*/
@Test
public void testit0113() throws Exception {
File testDir = extractResources("/it0113");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.addCliArgument("--settings");
verifier.addCliArgument("settings.xml");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
Properties props = verifier.loadProperties("target/auth.properties");
assertEquals("testuser", props.getProperty("test.username"));
assertEquals("testtest", props.getProperty("test.password"));
}
}
|
MavenIT0113ServerAuthzAvailableToWagonMgrInPluginTest
|
java
|
apache__logging-log4j2
|
log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java
|
{
"start": 1136,
"end": 3840
}
|
class ____ implements Marker {
public static final long serialVersionUID = 1590472L;
private final IMarkerFactory factory;
private final org.apache.logging.log4j.Marker marker;
/**
* Constructs a Log4jMarker using an existing Log4j {@link org.apache.logging.log4j.Marker}.
* @param marker The Log4j Marker upon which to base this Marker.
*/
public Log4jMarker(final IMarkerFactory markerFactory, final org.apache.logging.log4j.Marker marker) {
this.factory = markerFactory;
this.marker = marker;
}
@Override
public void add(final Marker marker) {
if (marker == null) {
throw new IllegalArgumentException();
}
final Marker m = factory.getMarker(marker.getName());
this.marker.addParents(((Log4jMarker) m).getLog4jMarker());
}
@Override
public boolean contains(final Marker marker) {
if (marker == null) {
throw new IllegalArgumentException();
}
return this.marker.isInstanceOf(marker.getName());
}
@Override
public boolean contains(final String s) {
return s != null ? this.marker.isInstanceOf(s) : false;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Log4jMarker)) {
return false;
}
final Log4jMarker other = (Log4jMarker) obj;
return Objects.equals(marker, other.marker);
}
public org.apache.logging.log4j.Marker getLog4jMarker() {
return marker;
}
@Override
public String getName() {
return marker.getName();
}
@Override
public boolean hasChildren() {
return marker.hasParents();
}
@Override
public int hashCode() {
return 31 + Objects.hashCode(marker);
}
@Override
public boolean hasReferences() {
return marker.hasParents();
}
@Override
public Iterator<Marker> iterator() {
final org.apache.logging.log4j.Marker[] log4jParents = this.marker.getParents();
if (log4jParents == null) {
return Collections.emptyIterator();
}
final List<Marker> parents = new ArrayList<>(log4jParents.length);
for (final org.apache.logging.log4j.Marker m : log4jParents) {
parents.add(factory.getMarker(m.getName()));
}
return parents.iterator();
}
@Override
public boolean remove(final Marker marker) {
return marker != null ? this.marker.remove(MarkerManager.getMarker(marker.getName())) : false;
}
}
|
Log4jMarker
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SpringWebserviceEndpointBuilderFactory.java
|
{
"start": 53246,
"end": 53613
}
|
class ____ extends AbstractEndpointBuilder implements SpringWebserviceEndpointBuilder, AdvancedSpringWebserviceEndpointBuilder {
public SpringWebserviceEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new SpringWebserviceEndpointBuilderImpl(path);
}
}
|
SpringWebserviceEndpointBuilderImpl
|
java
|
apache__maven
|
its/core-it-suite/src/test/resources/mng-6118-submodule-invocation-full-reactor/lib/src/test/java/org/apache/its/mng6118/HelperTest.java
|
{
"start": 1756,
"end": 1975
}
|
class ____ {
private final Helper helper = new Helper();
@Test
public void shouldAnswerWithTrue() {
assertNotNull(helper.generateObject(), "Helper should generate a non-null object");
}
}
|
HelperTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/GroupedSchemaValidatorImplTest.java
|
{
"start": 633,
"end": 945
}
|
class ____ extends IndividuallySchemaValidatorImplTest {
@Override
protected void getSchemaValidator(MetadataImplementor metadata) {
new GroupedSchemaValidatorImpl( tool, DefaultSchemaFilter.INSTANCE )
.doValidation( metadata, executionOptions, ContributableMatcher.ALL );
}
}
|
GroupedSchemaValidatorImplTest
|
java
|
apache__camel
|
components/camel-oauth/src/main/java/org/apache/camel/oauth/TokenCredentials.java
|
{
"start": 843,
"end": 1165
}
|
class ____ extends Credentials {
private String token;
public TokenCredentials(String token) {
this.token = token;
}
public String getToken() {
return token;
}
public TokenCredentials setToken(String token) {
this.token = token;
return this;
}
}
|
TokenCredentials
|
java
|
google__dagger
|
javatests/dagger/functional/jakarta/SimpleJakartaTest.java
|
{
"start": 1255,
"end": 1305
}
|
class ____ {
@Inject Foo() {}
}
@Module
|
Foo
|
java
|
google__guava
|
android/guava/src/com/google/common/io/FileWriteMode.java
|
{
"start": 943,
"end": 1063
}
|
enum ____ {
/** Specifies that writes to the opened file should append to the end of the file. */
APPEND
}
|
FileWriteMode
|
java
|
elastic__elasticsearch
|
x-pack/plugin/searchable-snapshots/src/main/java/org/elasticsearch/xpack/searchablesnapshots/allocation/SearchableSnapshotAllocator.java
|
{
"start": 25323,
"end": 27452
}
|
class ____ {
private final Set<DiscoveryNode> fetchingDataNodes = new HashSet<>();
private final Map<DiscoveryNode, NodeCacheFilesMetadata> data = new HashMap<>();
AsyncCacheStatusFetch() {}
synchronized DiscoveryNode[] addFetches(DiscoveryNode[] nodes) {
final Collection<DiscoveryNode> nodesToFetch = new ArrayList<>();
for (DiscoveryNode node : nodes) {
if (data.containsKey(node) == false && fetchingDataNodes.add(node)) {
nodesToFetch.add(node);
}
}
return nodesToFetch.toArray(new DiscoveryNode[0]);
}
synchronized void addData(Map<DiscoveryNode, NodeCacheFilesMetadata> newData) {
data.putAll(newData);
fetchingDataNodes.removeAll(newData.keySet());
}
@Nullable
synchronized Map<DiscoveryNode, NodeCacheFilesMetadata> data() {
return fetchingDataNodes.size() > 0 ? null : Map.copyOf(data);
}
synchronized int numberOfInFlightFetches() {
return fetchingDataNodes.size();
}
}
private record MatchingNodes(@Nullable Map<String, NodeAllocationResult> nodeDecisions, @Nullable DiscoveryNode nodeWithHighestMatch) {
private static MatchingNodes create(
Map<DiscoveryNode, Long> matchingNodes,
@Nullable Map<String, NodeAllocationResult> nodeDecisions
) {
return new MatchingNodes(nodeDecisions, getNodeWithHighestMatch(matchingNodes));
}
/**
* Returns the node with the highest number of bytes cached for the shard or {@code null} if no node with any bytes matched exists.
*/
@Nullable
private static DiscoveryNode getNodeWithHighestMatch(Map<DiscoveryNode, Long> matchingNodes) {
return matchingNodes.entrySet()
.stream()
.filter(entry -> entry.getValue() > 0L)
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(null);
}
}
}
|
AsyncCacheStatusFetch
|
java
|
quarkusio__quarkus
|
integration-tests/awt/src/main/java/io/quarkus/awt/it/enums/ColorSpaceEnum.java
|
{
"start": 109,
"end": 348
}
|
enum ____ {
CS_sRGB(1000),
CS_LINEAR_RGB(1004),
CS_CIEXYZ(1001),
CS_PYCC(1002),
CS_GRAY(1003),
CS_DEFAULT(-1);
public final int code;
ColorSpaceEnum(int code) {
this.code = code;
}
}
|
ColorSpaceEnum
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/classification/Accuracy.java
|
{
"start": 2735,
"end": 5919
}
|
class ____ implements EvaluationMetric {
public static final ParseField NAME = new ParseField("accuracy");
static final String OVERALL_ACCURACY_AGG_NAME = "classification_overall_accuracy";
private static final ObjectParser<Accuracy, Void> PARSER = new ObjectParser<>(NAME.getPreferredName(), true, Accuracy::new);
public static Accuracy fromXContent(XContentParser parser) {
return PARSER.apply(parser, null);
}
private static final int MAX_CLASSES_CARDINALITY = 1000;
private final MulticlassConfusionMatrix matrix;
private final SetOnce<String> actualField = new SetOnce<>();
private final SetOnce<Double> overallAccuracy = new SetOnce<>();
private final SetOnce<Result> result = new SetOnce<>();
public Accuracy() {
this.matrix = new MulticlassConfusionMatrix(MAX_CLASSES_CARDINALITY, NAME.getPreferredName() + "_");
}
public Accuracy(StreamInput in) throws IOException {
this.matrix = new MulticlassConfusionMatrix(in);
}
@Override
public String getWriteableName() {
return registeredMetricName(Classification.NAME, NAME);
}
@Override
public String getName() {
return NAME.getPreferredName();
}
@Override
public Set<String> getRequiredFields() {
return Sets.newHashSet(EvaluationFields.ACTUAL_FIELD.getPreferredName(), EvaluationFields.PREDICTED_FIELD.getPreferredName());
}
@Override
public final Tuple<List<AggregationBuilder>, List<PipelineAggregationBuilder>> aggs(
EvaluationParameters parameters,
EvaluationFields fields
) {
// Store given {@code actualField} for the purpose of generating error message in {@code process}.
this.actualField.trySet(fields.getActualField());
List<AggregationBuilder> aggs = new ArrayList<>();
List<PipelineAggregationBuilder> pipelineAggs = new ArrayList<>();
if (overallAccuracy.get() == null) {
Script script = PainlessScripts.buildIsEqualScript(fields.getActualField(), fields.getPredictedField());
aggs.add(AggregationBuilders.avg(OVERALL_ACCURACY_AGG_NAME).script(script));
}
if (result.get() == null) {
Tuple<List<AggregationBuilder>, List<PipelineAggregationBuilder>> matrixAggs = matrix.aggs(parameters, fields);
aggs.addAll(matrixAggs.v1());
pipelineAggs.addAll(matrixAggs.v2());
}
return Tuple.tuple(aggs, pipelineAggs);
}
@Override
public void process(InternalAggregations aggs) {
if (overallAccuracy.get() == null && aggs.get(OVERALL_ACCURACY_AGG_NAME) instanceof NumericMetricsAggregation.SingleValue) {
NumericMetricsAggregation.SingleValue overallAccuracyAgg = aggs.get(OVERALL_ACCURACY_AGG_NAME);
overallAccuracy.set(overallAccuracyAgg.value());
}
matrix.process(aggs);
if (result.get() == null && matrix.getResult().isPresent()) {
if (matrix.getResult().get().getOtherActualClassCount() > 0) {
// This means there were more than {@code maxClassesCardinality} buckets.
// We cannot calculate per-
|
Accuracy
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/SpatialRelatesFunction.java
|
{
"start": 4661,
"end": 14702
}
|
class ____ extends BinarySpatialComparator<Boolean> {
protected final ShapeField.QueryRelation queryRelation;
protected final ShapeIndexer shapeIndexer;
protected SpatialRelations(
ShapeField.QueryRelation queryRelation,
SpatialCoordinateTypes spatialCoordinateType,
CoordinateEncoder encoder,
ShapeIndexer shapeIndexer
) {
super(spatialCoordinateType, encoder);
this.queryRelation = queryRelation;
this.shapeIndexer = shapeIndexer;
}
@Override
protected Boolean compare(BytesRef left, BytesRef right) throws IOException {
return geometryRelatesGeometry(left, right);
}
protected boolean geometryRelatesGeometry(BytesRef left, BytesRef right) throws IOException {
Component2D rightComponent2D = asLuceneComponent2D(crsType, fromBytesRef(right));
// We already have a Component2D for the right geometry, so we need to convert the left geometry to a doc-values byte array
return geometryRelatesGeometry(asGeometryDocValueReader(coordinateEncoder, shapeIndexer, fromBytesRef(left)), rightComponent2D);
}
protected boolean geometryRelatesGeometry(GeometryDocValueReader reader, Component2D rightComponent2D) throws IOException {
var visitor = Component2DVisitor.getVisitor(rightComponent2D, queryRelation, coordinateEncoder);
reader.visit(visitor);
return visitor.matches();
}
protected void processSourceAndConstantGrid(
BooleanBlock.Builder builder,
int position,
BytesRefBlock wkb,
long gridId,
DataType gridType
) {
if (wkb.getValueCount(position) < 1) {
builder.appendNull();
} else {
builder.appendBoolean(compareGeometryAndGrid(asGeometry(wkb, position), gridId, gridType));
}
}
protected void processSourceAndSourceGrid(
BooleanBlock.Builder builder,
int position,
BytesRefBlock wkb,
LongBlock gridIds,
DataType gridType
) {
if (wkb.getValueCount(position) < 1 || gridIds.getValueCount(position) < 1) {
builder.appendNull();
} else {
builder.appendBoolean(compareGeometryAndGrid(asGeometry(wkb, position), gridIds.getLong(position), gridType));
}
}
protected boolean compareGeometryAndGrid(Geometry geometry, long gridId, DataType gridType) {
if (geometry instanceof Point point) {
long geoGridId = getGridId(point, gridId, gridType);
return switch (queryRelation) {
case INTERSECTS -> gridId == geoGridId;
case DISJOINT -> gridId != geoGridId;
default -> throw new IllegalArgumentException("Unsupported grid relation: " + queryRelation);
};
} else {
throw new IllegalArgumentException(
"Unsupported grid intersection geometry type: " + geometry.getClass().getSimpleName() + "; expected Point"
);
}
}
protected void processGeoPointDocValuesAndConstantGrid(
BooleanBlock.Builder builder,
int position,
LongBlock encodedPoint,
long gridId,
DataType gridType
) {
if (encodedPoint.getValueCount(position) < 1) {
builder.appendNull();
} else {
final Point point = spatialCoordinateType.longAsPoint(encodedPoint.getLong(position));
long geoGridId = getGridId(point, gridId, gridType);
builder.appendBoolean(gridId == geoGridId);
}
}
protected void processGeoPointDocValuesAndSourceGrid(
BooleanBlock.Builder builder,
int position,
LongBlock encodedPoint,
LongBlock gridIds,
DataType gridType
) {
if (encodedPoint.getValueCount(position) < 1 || gridIds.getValueCount(position) < 1) {
builder.appendNull();
} else {
final Point point = spatialCoordinateType.longAsPoint(encodedPoint.getLong(position));
final long gridId = gridIds.getLong(position);
long geoGridId = getGridId(point, gridId, gridType);
builder.appendBoolean(gridId == geoGridId);
}
}
private long getGridId(Point point, long gridId, DataType gridType) {
return switch (gridType) {
case GEOHASH -> Geohash.longEncode(point.getX(), point.getY(), Geohash.stringEncode(gridId).length());
case GEOTILE -> GeoTileUtils.longEncode(
point.getX(),
point.getY(),
Integer.parseInt(GeoTileUtils.stringEncode(gridId).split("/")[0])
);
case GEOHEX -> H3.geoToH3(point.getY(), point.getX(), H3.getResolution(gridId));
default -> throw new IllegalArgumentException(
"Unsupported grid type: " + gridType + "; expected GEOHASH, GEOTILE, or GEOHEX"
);
};
}
protected void processSourceAndConstant(BooleanBlock.Builder builder, int position, BytesRefBlock left, Component2D right)
throws IOException {
if (left.getValueCount(position) < 1) {
builder.appendNull();
} else {
final GeometryDocValueReader reader = asGeometryDocValueReader(coordinateEncoder, shapeIndexer, left, position);
builder.appendBoolean(geometryRelatesGeometry(reader, right));
}
}
protected void processSourceAndSource(BooleanBlock.Builder builder, int position, BytesRefBlock left, BytesRefBlock right)
throws IOException {
if (left.getValueCount(position) < 1 || right.getValueCount(position) < 1) {
builder.appendNull();
} else {
final GeometryDocValueReader reader = asGeometryDocValueReader(coordinateEncoder, shapeIndexer, left, position);
final Component2D component2D = asLuceneComponent2D(crsType, right, position);
builder.appendBoolean(geometryRelatesGeometry(reader, component2D));
}
}
protected void processPointDocValuesAndConstant(
BooleanBlock.Builder builder,
int position,
LongBlock leftValue,
Component2D rightValue
) throws IOException {
if (leftValue.getValueCount(position) < 1) {
builder.appendNull();
} else {
final GeometryDocValueReader reader = asGeometryDocValueReader(
coordinateEncoder,
shapeIndexer,
leftValue,
position,
spatialCoordinateType::longAsPoint
);
builder.appendBoolean(geometryRelatesGeometry(reader, rightValue));
}
}
protected void processPointDocValuesAndSource(
BooleanBlock.Builder builder,
int position,
LongBlock leftValue,
BytesRefBlock rightValue
) throws IOException {
if (leftValue.getValueCount(position) < 1 || rightValue.getValueCount(position) < 1) {
builder.appendNull();
} else {
final GeometryDocValueReader reader = asGeometryDocValueReader(
coordinateEncoder,
shapeIndexer,
leftValue,
position,
spatialCoordinateType::longAsPoint
);
final Component2D component2D = asLuceneComponent2D(crsType, rightValue, position);
builder.appendBoolean(geometryRelatesGeometry(reader, component2D));
}
}
}
@Override
public Translatable translatable(LucenePushdownPredicates pushdownPredicates) {
return super.translatable(pushdownPredicates); // only for the explicit Override, as only this subclass implements TranslationAware
}
@Override
public Query asQuery(LucenePushdownPredicates pushdownPredicates, TranslatorHandler handler) {
if (left().foldable()) {
checkSpatialRelatesFunction(left(), queryRelation());
return translate(handler, right(), left());
} else {
checkSpatialRelatesFunction(right(), queryRelation());
return translate(handler, left(), right());
}
}
private static void checkSpatialRelatesFunction(Expression constantExpression, ShapeRelation queryRelation) {
Check.isTrue(
constantExpression.foldable(),
"Line {}:{}: Comparisons against fields are not (currently) supported; offender [{}] in [ST_{}]",
constantExpression.sourceLocation().getLineNumber(),
constantExpression.sourceLocation().getColumnNumber(),
Expressions.name(constantExpression),
queryRelation
);
}
private Query translate(TranslatorHandler handler, Expression spatialExpression, Expression constantExpression) {
TypedAttribute attribute = LucenePushdownPredicates.checkIsPushableAttribute(spatialExpression);
String name = handler.nameOf(attribute);
try {
// TODO: Support geo-grid query pushdown
Geometry shape = SpatialRelatesUtils.makeGeometryFromLiteral(constantExpression);
return new SpatialRelatesQuery(source(), name, queryRelation(), shape, attribute.dataType());
} catch (IllegalArgumentException e) {
throw new QlIllegalArgumentException(e.getMessage(), e);
}
}
}
|
SpatialRelations
|
java
|
grpc__grpc-java
|
testing/src/main/java/io/grpc/internal/testing/StatsTestUtils.java
|
{
"start": 6236,
"end": 7277
}
|
class ____ extends TagContextBinarySerializer {
private final FakeTagger tagger = new FakeTagger();
@Override
public TagContext fromByteArray(byte[] bytes) throws TagContextDeserializationException {
String serializedString = new String(bytes, UTF_8);
if (serializedString.startsWith(EXTRA_TAG_HEADER_VALUE_PREFIX)) {
return tagger.emptyBuilder()
.putLocal(EXTRA_TAG,
TagValue.create(serializedString.substring(EXTRA_TAG_HEADER_VALUE_PREFIX.length())))
.build();
} else {
throw new TagContextDeserializationException("Malformed value");
}
}
@Override
public byte[] toByteArray(TagContext tags) {
TagValue extraTagValue = getTags(tags).get(EXTRA_TAG);
if (extraTagValue == null) {
throw new UnsupportedOperationException("TagContext must contain EXTRA_TAG");
}
return (EXTRA_TAG_HEADER_VALUE_PREFIX + extraTagValue.asString()).getBytes(UTF_8);
}
}
public static final
|
FakeTagContextBinarySerializer
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/LineReader.java
|
{
"start": 1841,
"end": 14933
}
|
class ____ implements Closeable, IOStatisticsSource {
private static final int DEFAULT_BUFFER_SIZE = 64 * 1024;
private int bufferSize = DEFAULT_BUFFER_SIZE;
private InputStream in;
private byte[] buffer;
// the number of bytes of real data in the buffer
private int bufferLength = 0;
// the current position in the buffer
private int bufferPosn = 0;
private static final byte CR = '\r';
private static final byte LF = '\n';
// The line delimiter
private final byte[] recordDelimiterBytes;
/**
* Create a line reader that reads from the given stream using the
* default buffer-size (64k).
* @param in The input stream
*/
public LineReader(InputStream in) {
this(in, DEFAULT_BUFFER_SIZE);
}
/**
* Create a line reader that reads from the given stream using the
* given buffer-size.
* @param in The input stream
* @param bufferSize Size of the read buffer
*/
public LineReader(InputStream in, int bufferSize) {
this.in = in;
this.bufferSize = bufferSize;
this.buffer = new byte[this.bufferSize];
this.recordDelimiterBytes = null;
}
/**
* Create a line reader that reads from the given stream using the
* <code>io.file.buffer.size</code> specified in the given
* <code>Configuration</code>.
* @param in input stream
* @param conf configuration
* @throws IOException raised on errors performing I/O.
*/
public LineReader(InputStream in, Configuration conf) throws IOException {
this(in, conf.getInt(IO_FILE_BUFFER_SIZE_KEY, DEFAULT_BUFFER_SIZE));
}
/**
* Create a line reader that reads from the given stream using the
* default buffer-size, and using a custom delimiter of array of
* bytes.
* @param in The input stream
* @param recordDelimiterBytes The delimiter
*/
public LineReader(InputStream in, byte[] recordDelimiterBytes) {
this.in = in;
this.bufferSize = DEFAULT_BUFFER_SIZE;
this.buffer = new byte[this.bufferSize];
this.recordDelimiterBytes = recordDelimiterBytes;
}
/**
* Create a line reader that reads from the given stream using the
* given buffer-size, and using a custom delimiter of array of
* bytes.
* @param in The input stream
* @param bufferSize Size of the read buffer
* @param recordDelimiterBytes The delimiter
*/
public LineReader(InputStream in, int bufferSize,
byte[] recordDelimiterBytes) {
this.in = in;
this.bufferSize = bufferSize;
this.buffer = new byte[this.bufferSize];
this.recordDelimiterBytes = recordDelimiterBytes;
}
/**
* Create a line reader that reads from the given stream using the
* <code>io.file.buffer.size</code> specified in the given
* <code>Configuration</code>, and using a custom delimiter of array of
* bytes.
* @param in input stream
* @param conf configuration
* @param recordDelimiterBytes The delimiter
* @throws IOException raised on errors performing I/O.
*/
public LineReader(InputStream in, Configuration conf,
byte[] recordDelimiterBytes) throws IOException {
this.in = in;
this.bufferSize = conf.getInt(IO_FILE_BUFFER_SIZE_KEY, DEFAULT_BUFFER_SIZE);
this.buffer = new byte[this.bufferSize];
this.recordDelimiterBytes = recordDelimiterBytes;
}
/**
* Close the underlying stream.
* @throws IOException raised on errors performing I/O.
*/
public void close() throws IOException {
in.close();
}
/**
* Return any IOStatistics provided by the source.
* @return IO stats from the input stream.
*/
@Override
public IOStatistics getIOStatistics() {
return IOStatisticsSupport.retrieveIOStatistics(in);
}
/**
* Read one line from the InputStream into the given Text.
*
* @param str the object to store the given line (without newline)
* @param maxLineLength the maximum number of bytes to store into str;
* the rest of the line is silently discarded.
* @param maxBytesToConsume the maximum number of bytes to consume
* in this call. This is only a hint, because if the line cross
* this threshold, we allow it to happen. It can overshoot
* potentially by as much as one buffer length.
*
* @return the number of bytes read including the (longest) newline
* found.
*
* @throws IOException if the underlying stream throws
*/
public int readLine(Text str, int maxLineLength,
int maxBytesToConsume) throws IOException {
if (this.recordDelimiterBytes != null) {
return readCustomLine(str, maxLineLength, maxBytesToConsume);
} else {
return readDefaultLine(str, maxLineLength, maxBytesToConsume);
}
}
protected int fillBuffer(InputStream in, byte[] buffer, boolean inDelimiter)
throws IOException {
return in.read(buffer);
}
/**
* Read a line terminated by one of CR, LF, or CRLF.
*/
private int readDefaultLine(Text str, int maxLineLength, int maxBytesToConsume)
throws IOException {
/* We're reading data from in, but the head of the stream may be
* already buffered in buffer, so we have several cases:
* 1. No newline characters are in the buffer, so we need to copy
* everything and read another buffer from the stream.
* 2. An unambiguously terminated line is in buffer, so we just
* copy to str.
* 3. Ambiguously terminated line is in buffer, i.e. buffer ends
* in CR. In this case we copy everything up to CR to str, but
* we also need to see what follows CR: if it's LF, then we
* need consume LF as well, so next call to readLine will read
* from after that.
* We use a flag prevCharCR to signal if previous character was CR
* and, if it happens to be at the end of the buffer, delay
* consuming it until we have a chance to look at the char that
* follows.
*/
str.clear();
int txtLength = 0; //tracks str.getLength(), as an optimization
int newlineLength = 0; //length of terminating newline
boolean prevCharCR = false; //true of prev char was CR
long bytesConsumed = 0;
do {
int startPosn = bufferPosn; //starting from where we left off the last time
if (bufferPosn >= bufferLength) {
startPosn = bufferPosn = 0;
if (prevCharCR) {
++bytesConsumed; //account for CR from previous read
}
bufferLength = fillBuffer(in, buffer, prevCharCR);
if (bufferLength <= 0) {
break; // EOF
}
}
for (; bufferPosn < bufferLength; ++bufferPosn) { //search for newline
if (buffer[bufferPosn] == LF) {
newlineLength = (prevCharCR) ? 2 : 1;
++bufferPosn; // at next invocation proceed from following byte
break;
}
if (prevCharCR) { //CR + notLF, we are at notLF
newlineLength = 1;
break;
}
prevCharCR = (buffer[bufferPosn] == CR);
}
int readLength = bufferPosn - startPosn;
if (prevCharCR && newlineLength == 0) {
--readLength; //CR at the end of the buffer
}
bytesConsumed += readLength;
int appendLength = readLength - newlineLength;
if (appendLength > maxLineLength - txtLength) {
appendLength = maxLineLength - txtLength;
}
if (appendLength > 0) {
str.append(buffer, startPosn, appendLength);
txtLength += appendLength;
}
} while (newlineLength == 0 && bytesConsumed < maxBytesToConsume);
if (bytesConsumed > Integer.MAX_VALUE) {
throw new IOException("Too many bytes before newline: " + bytesConsumed);
}
return (int)bytesConsumed;
}
/**
* Read a line terminated by a custom delimiter.
*/
private int readCustomLine(Text str, int maxLineLength, int maxBytesToConsume)
throws IOException {
/* We're reading data from inputStream, but the head of the stream may be
* already captured in the previous buffer, so we have several cases:
*
* 1. The buffer tail does not contain any character sequence which
* matches with the head of delimiter. We count it as a
* ambiguous byte count = 0
*
* 2. The buffer tail contains a X number of characters,
* that forms a sequence, which matches with the
* head of delimiter. We count ambiguous byte count = X
*
* // *** eg: A segment of input file is as follows
*
* " record 1792: I found this bug very interesting and
* I have completely read about it. record 1793: This bug
* can be solved easily record 1794: This ."
*
* delimiter = "record";
*
* supposing:- String at the end of buffer =
* "I found this bug very interesting and I have completely re"
* There for next buffer = "ad about it. record 179 ...."
*
* The matching characters in the input
* buffer tail and delimiter head = "re"
* Therefore, ambiguous byte count = 2 **** //
*
* 2.1 If the following bytes are the remaining characters of
* the delimiter, then we have to capture only up to the starting
* position of delimiter. That means, we need not include the
* ambiguous characters in str.
*
* 2.2 If the following bytes are not the remaining characters of
* the delimiter ( as mentioned in the example ),
* then we have to include the ambiguous characters in str.
*/
str.clear();
int txtLength = 0; // tracks str.getLength(), as an optimization
long bytesConsumed = 0;
int delPosn = 0;
int ambiguousByteCount=0; // To capture the ambiguous characters count
do {
int startPosn = bufferPosn; // Start from previous end position
if (bufferPosn >= bufferLength) {
startPosn = bufferPosn = 0;
bufferLength = fillBuffer(in, buffer, ambiguousByteCount > 0);
if (bufferLength <= 0) {
if (ambiguousByteCount > 0) {
str.append(recordDelimiterBytes, 0, ambiguousByteCount);
bytesConsumed += ambiguousByteCount;
}
break; // EOF
}
}
for (; bufferPosn < bufferLength; ++bufferPosn) {
if (buffer[bufferPosn] == recordDelimiterBytes[delPosn]) {
delPosn++;
if (delPosn >= recordDelimiterBytes.length) {
bufferPosn++;
break;
}
} else if (delPosn != 0) {
bufferPosn -= delPosn;
if(bufferPosn < -1) {
bufferPosn = -1;
}
delPosn = 0;
}
}
int readLength = bufferPosn - startPosn;
bytesConsumed += readLength;
int appendLength = readLength - delPosn;
if (appendLength > maxLineLength - txtLength) {
appendLength = maxLineLength - txtLength;
}
bytesConsumed += ambiguousByteCount;
if (appendLength >= 0 && ambiguousByteCount > 0) {
//appending the ambiguous characters (refer case 2.2)
str.append(recordDelimiterBytes, 0, ambiguousByteCount);
ambiguousByteCount = 0;
// since it is now certain that the split did not split a delimiter we
// should not read the next record: clear the flag otherwise duplicate
// records could be generated
unsetNeedAdditionalRecordAfterSplit();
}
if (appendLength > 0) {
str.append(buffer, startPosn, appendLength);
txtLength += appendLength;
}
if (bufferPosn >= bufferLength) {
if (delPosn > 0 && delPosn < recordDelimiterBytes.length) {
ambiguousByteCount = delPosn;
bytesConsumed -= ambiguousByteCount; //to be consumed in next
}
}
} while (delPosn < recordDelimiterBytes.length
&& bytesConsumed < maxBytesToConsume);
if (bytesConsumed > Integer.MAX_VALUE) {
throw new IOException("Too many bytes before delimiter: " + bytesConsumed);
}
return (int) bytesConsumed;
}
/**
* Read from the InputStream into the given Text.
* @param str the object to store the given line
* @param maxLineLength the maximum number of bytes to store into str.
* @return the number of bytes read including the newline
* @throws IOException if the underlying stream throws
*/
public int readLine(Text str, int maxLineLength) throws IOException {
return readLine(str, maxLineLength, Integer.MAX_VALUE);
}
/**
* Read from the InputStream into the given Text.
* @param str the object to store the given line
* @return the number of bytes read including the newline
* @throws IOException if the underlying stream throws
*/
public int readLine(Text str) throws IOException {
return readLine(str, Integer.MAX_VALUE, Integer.MAX_VALUE);
}
protected int getBufferPosn() {
return bufferPosn;
}
protected int getBufferSize() {
return bufferSize;
}
protected void unsetNeedAdditionalRecordAfterSplit() {
// needed for custom multi byte line delimiters only
// see MAPREDUCE-6549 for details
}
}
|
LineReader
|
java
|
spring-projects__spring-framework
|
spring-test/src/main/java/org/springframework/test/context/CacheAwareContextLoaderDelegate.java
|
{
"start": 8653,
"end": 8907
}
|
class ____ is no longer using the application context(s)
* @since 7.0
* @see #registerContextUsage(MergedContextConfiguration, Class)
*/
default void unregisterContextUsage(MergedContextConfiguration key, Class<?> testClass) {
/* no-op */
}
}
|
that
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/component/StructComponentArrayTest.java
|
{
"start": 2302,
"end": 2519
}
|
class ____ {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Embeddable
@Struct( name = "label_type")
public static
|
Publisher
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/InconsistentCapitalization.java
|
{
"start": 4735,
"end": 5515
}
|
class ____ scope).
*/
private static String getExplicitQualification(
TreePath path, ClassTree tree, VisitorState state) {
for (Tree node : path) {
if (node.equals(tree)) {
break;
}
if (node instanceof ClassTree) {
if (ASTHelpers.getSymbol(node).isSubClass(ASTHelpers.getSymbol(tree), state.getTypes())) {
return "super.";
}
return tree.getSimpleName() + ".this.";
}
}
return "this.";
}
/** Returns true if the given symbol has static modifier and is all upper case. */
private static boolean isUpperCaseAndStatic(Symbol symbol) {
return isStatic(symbol) && symbol.name.contentEquals(Ascii.toUpperCase(symbol.name.toString()));
}
/**
* Matcher for all fields of the given
|
node
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/JoinedInheritanceEagerTest.java
|
{
"start": 1270,
"end": 2583
}
|
class ____ {
@BeforeEach
public void setUp(SessionFactoryScope scope) {
scope.inTransaction( session -> {
EntityC entityC = new EntityC( 1L );
EntityD entityD = new EntityD( 2L );
EntityB entityB = new EntityB( 3L );
entityB.setRelation( entityD );
EntityA entityA = new EntityA( 4L );
entityA.setRelation( entityC );
session.persist( entityC );
session.persist( entityD );
session.persist( entityA );
session.persist( entityB );
} );
}
@AfterEach
public void cleanUp(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
@JiraKey("HHH-12375")
public void joinUnrelatedCollectionOnBaseType(SessionFactoryScope scope) {
scope.inSession(
session -> {
session.getTransaction().begin();
try {
session.createQuery( "from BaseEntity b join b.attributes" ).list();
fail( "Expected a resolution exception for property 'attributes'!" );
}
catch (IllegalArgumentException ex) {
Assertions.assertTrue( ex.getCause().getMessage().contains( "Could not resolve attribute 'attributes' "));
}
finally {
session.getTransaction().commit();
}
}
);
}
@Entity(name = "BaseEntity")
@Inheritance(strategy = InheritanceType.JOINED)
public static
|
JoinedInheritanceEagerTest
|
java
|
lettuce-io__lettuce-core
|
src/test/java/io/lettuce/core/dynamic/ReactiveCommandSegmentCommandFactoryUnitTests.java
|
{
"start": 1163,
"end": 3070
}
|
class ____ {
private CodecAwareOutputFactoryResolver outputFactoryResolver = new CodecAwareOutputFactoryResolver(
new OutputRegistryCommandOutputFactoryResolver(new OutputRegistry()), StringCodec.UTF8);
@Test
void commandCreationWithTimeoutShouldFail() {
try {
createCommand("get", ReactiveWithTimeout.class, String.class, Timeout.class);
fail("Missing CommandCreationException");
} catch (CommandCreationException e) {
assertThat(e).hasMessageContaining("Reactive command methods do not support Timeout parameters");
}
}
@Test
void shouldResolveNonStreamingOutput() {
RedisCommand<?, ?, ?> command = createCommand("getOne", ReactiveWithTimeout.class, String.class);
assertThat(command.getOutput()).isNotInstanceOf(StreamingOutput.class);
}
@Test
void shouldResolveStreamingOutput() {
RedisCommand<?, ?, ?> command = createCommand("getMany", ReactiveWithTimeout.class, String.class);
assertThat(command.getOutput()).isInstanceOf(StreamingOutput.class);
}
RedisCommand<?, ?, ?> createCommand(String methodName, Class<?> interfaceClass, Class<?>... parameterTypes) {
Method method = ReflectionUtils.findMethod(interfaceClass, methodName, parameterTypes);
CommandMethod commandMethod = DeclaredCommandMethod.create(method);
AnnotationCommandSegmentFactory segmentFactory = new AnnotationCommandSegmentFactory();
CommandSegments commandSegments = segmentFactory.createCommandSegments(commandMethod);
ReactiveCommandSegmentCommandFactory factory = new ReactiveCommandSegmentCommandFactory(commandSegments, commandMethod,
new StringCodec(), outputFactoryResolver);
return factory.createCommand(new Object[] { "foo" });
}
private static
|
ReactiveCommandSegmentCommandFactoryUnitTests
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/stats/StatsAccumulatorTests.java
|
{
"start": 667,
"end": 6187
}
|
class ____ extends AbstractWireSerializingTestCase<StatsAccumulator> {
public void testGivenNoValues() {
StatsAccumulator accumulator = new StatsAccumulator();
assertThat(accumulator.getMin(), equalTo(0.0));
assertThat(accumulator.getMax(), equalTo(0.0));
assertThat(accumulator.getTotal(), equalTo(0.0));
assertThat(accumulator.getAvg(), equalTo(0.0));
}
public void testGivenPositiveValues() {
StatsAccumulator accumulator = new StatsAccumulator();
for (int i = 1; i <= 10; i++) {
accumulator.add(i);
}
assertThat(accumulator.getMin(), equalTo(1.0));
assertThat(accumulator.getMax(), equalTo(10.0));
assertThat(accumulator.getTotal(), equalTo(55.0));
assertThat(accumulator.getAvg(), equalTo(5.5));
}
public void testGivenNegativeValues() {
StatsAccumulator accumulator = new StatsAccumulator();
for (int i = 1; i <= 10; i++) {
accumulator.add(-1 * i);
}
assertThat(accumulator.getMin(), equalTo(-10.0));
assertThat(accumulator.getMax(), equalTo(-1.0));
assertThat(accumulator.getTotal(), equalTo(-55.0));
assertThat(accumulator.getAvg(), equalTo(-5.5));
}
public void testAsMap() {
StatsAccumulator accumulator = new StatsAccumulator();
accumulator.add(5.0);
accumulator.add(10.0);
Map<String, Double> expectedMap = new HashMap<>();
expectedMap.put("min", 5.0);
expectedMap.put("max", 10.0);
expectedMap.put("avg", 7.5);
expectedMap.put("total", 15.0);
assertThat(accumulator.asMap(), equalTo(expectedMap));
}
public void testMerge() {
StatsAccumulator accumulator = new StatsAccumulator();
accumulator.add(5.0);
accumulator.add(10.0);
assertThat(accumulator.getMin(), equalTo(5.0));
assertThat(accumulator.getMax(), equalTo(10.0));
assertThat(accumulator.getTotal(), equalTo(15.0));
assertThat(accumulator.getAvg(), equalTo(7.5));
StatsAccumulator accumulator2 = new StatsAccumulator();
accumulator2.add(1.0);
accumulator2.add(3.0);
accumulator2.add(7.0);
assertThat(accumulator2.getMin(), equalTo(1.0));
assertThat(accumulator2.getMax(), equalTo(7.0));
assertThat(accumulator2.getTotal(), equalTo(11.0));
assertThat(accumulator2.getAvg(), equalTo(11.0 / 3.0));
accumulator.merge(accumulator2);
assertThat(accumulator.getMin(), equalTo(1.0));
assertThat(accumulator.getMax(), equalTo(10.0));
assertThat(accumulator.getTotal(), equalTo(26.0));
assertThat(accumulator.getAvg(), equalTo(5.2));
// same as accumulator
StatsAccumulator accumulator3 = new StatsAccumulator();
accumulator3.add(5.0);
accumulator3.add(10.0);
// merging the other way should yield the same results
accumulator2.merge(accumulator3);
assertThat(accumulator2.getMin(), equalTo(1.0));
assertThat(accumulator2.getMax(), equalTo(10.0));
assertThat(accumulator2.getTotal(), equalTo(26.0));
assertThat(accumulator2.getAvg(), equalTo(5.2));
}
public void testMergeMixedEmpty() {
StatsAccumulator accumulator = new StatsAccumulator();
StatsAccumulator accumulator2 = new StatsAccumulator();
accumulator2.add(1.0);
accumulator2.add(3.0);
accumulator.merge(accumulator2);
assertThat(accumulator.getMin(), equalTo(1.0));
assertThat(accumulator.getMax(), equalTo(3.0));
assertThat(accumulator.getTotal(), equalTo(4.0));
StatsAccumulator accumulator3 = new StatsAccumulator();
accumulator.merge(accumulator3);
assertThat(accumulator.getMin(), equalTo(1.0));
assertThat(accumulator.getMax(), equalTo(3.0));
assertThat(accumulator.getTotal(), equalTo(4.0));
StatsAccumulator accumulator4 = new StatsAccumulator();
accumulator3.merge(accumulator4);
assertThat(accumulator3.getMin(), equalTo(0.0));
assertThat(accumulator3.getMax(), equalTo(0.0));
assertThat(accumulator3.getTotal(), equalTo(0.0));
}
public void testFromStatsAggregation() {
Stats stats = mock(Stats.class);
when(stats.getMax()).thenReturn(25.0);
when(stats.getMin()).thenReturn(2.5);
when(stats.getCount()).thenReturn(4L);
when(stats.getSum()).thenReturn(48.0);
when(stats.getAvg()).thenReturn(12.0);
StatsAccumulator accumulator = StatsAccumulator.fromStatsAggregation(stats);
assertThat(accumulator.getMin(), equalTo(2.5));
assertThat(accumulator.getMax(), equalTo(25.0));
assertThat(accumulator.getTotal(), equalTo(48.0));
assertThat(accumulator.getAvg(), equalTo(12.0));
}
@Override
public StatsAccumulator createTestInstance() {
StatsAccumulator accumulator = new StatsAccumulator();
for (int i = 0; i < randomInt(10); ++i) {
accumulator.add(randomDoubleBetween(0.0, 1000.0, true));
}
return accumulator;
}
@Override
protected StatsAccumulator mutateInstance(StatsAccumulator instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected Reader<StatsAccumulator> instanceReader() {
return StatsAccumulator::new;
}
}
|
StatsAccumulatorTests
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/javadoc/MalformedInlineTagTest.java
|
{
"start": 2230,
"end": 2776
}
|
class ____ {
/**
* Add one to value.
*
* @param x an {@code int} value to increment
* @return {@code x} + 1
*/
int addOne(int x) {
return x + 1;
}
}
""")
.doTest(TEXT_MATCH);
}
@Test
public void positive_atLineEnd() {
helper
.addInputLines(
"Test.java",
"""
/** This malformed tag spans @{code multiple lines}. */
|
Test
|
java
|
apache__camel
|
components/camel-stax/src/test/java/org/apache/camel/component/stax/model/Order.java
|
{
"start": 1140,
"end": 2078
}
|
class ____ {
@XmlElement(required = true)
protected String id;
@XmlElement(required = true)
protected int amount;
@XmlElement(required = true)
protected int customerId;
@XmlElement(required = true)
protected String description;
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return "Order[" + id + "]";
}
}
|
Order
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/deser/creators/AnySetterForCreator562Test.java
|
{
"start": 1322,
"end": 1838
}
|
class ____
{
String a;
@JsonAnySetter
Map<String,Object> stuffFromField;
Map<String,Object> stuffFromConstructor;
@JsonCreator
public POJO562WithAnnotationOnBothCtorParamAndField(@JsonProperty("a") String a,
@JsonAnySetter Map<String, Object> leftovers
) {
this.a = a;
stuffFromConstructor = leftovers;
}
}
static
|
POJO562WithAnnotationOnBothCtorParamAndField
|
java
|
square__retrofit
|
retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/SingleThrowingTest.java
|
{
"start": 1432,
"end": 1705
}
|
class ____ {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final TestRule resetRule = new RxJavaPluginsResetRule();
@Rule
public final RecordingSingleObserver.Rule subscriberRule = new RecordingSingleObserver.Rule();
|
SingleThrowingTest
|
java
|
apache__dubbo
|
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.java
|
{
"start": 1543,
"end": 4319
}
|
interface ____ {@link ServiceDefinition}.
*
* @return Service description
*/
public static ServiceDefinition build(final Class<?> interfaceClass) {
ServiceDefinition sd = new ServiceDefinition();
build(sd, interfaceClass);
return sd;
}
public static FullServiceDefinition buildFullDefinition(final Class<?> interfaceClass) {
FullServiceDefinition sd = new FullServiceDefinition();
build(sd, interfaceClass);
return sd;
}
public static FullServiceDefinition buildFullDefinition(final Class<?> interfaceClass, Map<String, String> params) {
FullServiceDefinition sd = new FullServiceDefinition();
build(sd, interfaceClass);
sd.setParameters(params);
return sd;
}
public static <T extends ServiceDefinition> void build(T sd, final Class<?> interfaceClass) {
sd.setCanonicalName(interfaceClass.getCanonicalName());
sd.setCodeSource(ClassUtils.getCodeSource(interfaceClass));
Annotation[] classAnnotations = interfaceClass.getAnnotations();
sd.setAnnotations(annotationToStringList(classAnnotations));
TypeDefinitionBuilder builder = new TypeDefinitionBuilder();
List<Method> methods = ClassUtils.getPublicNonStaticMethods(interfaceClass);
for (Method method : methods) {
MethodDefinition md = new MethodDefinition();
md.setName(method.getName());
Annotation[] methodAnnotations = method.getAnnotations();
md.setAnnotations(annotationToStringList(methodAnnotations));
// Process parameter types.
Class<?>[] paramTypes = method.getParameterTypes();
Type[] genericParamTypes = method.getGenericParameterTypes();
String[] parameterTypes = new String[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
TypeDefinition td = builder.build(genericParamTypes[i], paramTypes[i]);
parameterTypes[i] = td.getType();
}
md.setParameterTypes(parameterTypes);
// Process return type.
TypeDefinition td = builder.build(method.getGenericReturnType(), method.getReturnType());
md.setReturnType(td.getType());
sd.getMethods().add(md);
}
sd.setTypes(builder.getTypeDefinitions());
}
private static List<String> annotationToStringList(Annotation[] annotations) {
if (annotations == null) {
return Collections.emptyList();
}
List<String> list = new ArrayList<>();
for (Annotation annotation : annotations) {
list.add(annotation.toString());
}
return list;
}
/**
* Describe a Java
|
in
|
java
|
elastic__elasticsearch
|
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlBaseParser.java
|
{
"start": 213266,
"end": 223583
}
|
class ____ extends PrimaryExpressionContext {
public BooleanExpressionContext operand;
public BooleanExpressionContext elseClause;
public TerminalNode CASE() {
return getToken(SqlBaseParser.CASE, 0);
}
public TerminalNode END() {
return getToken(SqlBaseParser.END, 0);
}
public List<WhenClauseContext> whenClause() {
return getRuleContexts(WhenClauseContext.class);
}
public WhenClauseContext whenClause(int i) {
return getRuleContext(WhenClauseContext.class, i);
}
public TerminalNode ELSE() {
return getToken(SqlBaseParser.ELSE, 0);
}
public List<BooleanExpressionContext> booleanExpression() {
return getRuleContexts(BooleanExpressionContext.class);
}
public BooleanExpressionContext booleanExpression(int i) {
return getRuleContext(BooleanExpressionContext.class, i);
}
public CaseContext(PrimaryExpressionContext ctx) {
copyFrom(ctx);
}
@Override
public void enterRule(ParseTreeListener listener) {
if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).enterCase(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).exitCase(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if (visitor instanceof SqlBaseVisitor) return ((SqlBaseVisitor<? extends T>) visitor).visitCase(this);
else return visitor.visitChildren(this);
}
}
public final PrimaryExpressionContext primaryExpression() throws RecognitionException {
return primaryExpression(0);
}
private PrimaryExpressionContext primaryExpression(int _p) throws RecognitionException {
ParserRuleContext _parentctx = _ctx;
int _parentState = getState();
PrimaryExpressionContext _localctx = new PrimaryExpressionContext(_ctx, _parentState);
PrimaryExpressionContext _prevctx = _localctx;
int _startState = 70;
enterRecursionRule(_localctx, 70, RULE_primaryExpression, _p);
int _la;
try {
int _alt;
enterOuterAlt(_localctx, 1);
{
setState(685);
_errHandler.sync(this);
switch (getInterpreter().adaptivePredict(_input, 95, _ctx)) {
case 1: {
_localctx = new CastContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(650);
castExpression();
}
break;
case 2: {
_localctx = new ExtractContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(651);
extractExpression();
}
break;
case 3: {
_localctx = new CurrentDateTimeFunctionContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(652);
builtinDateTimeFunction();
}
break;
case 4: {
_localctx = new ConstantDefaultContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(653);
constant();
}
break;
case 5: {
_localctx = new StarContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(657);
_errHandler.sync(this);
_la = _input.LA(1);
if ((((_la) & ~0x3f) == 0 && ((1L << _la) & -6012133270006398784L) != 0)
|| ((((_la - 70)) & ~0x3f) == 0 && ((1L << (_la - 70)) & -5764607520692920591L) != 0)
|| _la == BACKQUOTED_IDENTIFIER) {
{
setState(654);
qualifiedName();
setState(655);
match(DOT);
}
}
setState(659);
match(ASTERISK);
}
break;
case 6: {
_localctx = new FunctionContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(660);
functionExpression();
}
break;
case 7: {
_localctx = new SubqueryExpressionContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(661);
match(T__0);
setState(662);
query();
setState(663);
match(T__1);
}
break;
case 8: {
_localctx = new DereferenceContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(665);
qualifiedName();
}
break;
case 9: {
_localctx = new ParenthesizedExpressionContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(666);
match(T__0);
setState(667);
expression();
setState(668);
match(T__1);
}
break;
case 10: {
_localctx = new CaseContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(670);
match(CASE);
setState(672);
_errHandler.sync(this);
_la = _input.LA(1);
if ((((_la) & ~0x3f) == 0 && ((1L << _la) & -4787154059691900734L) != 0)
|| ((((_la - 66)) & ~0x3f) == 0 && ((1L << (_la - 66)) & -1089854304776749293L) != 0)
|| ((((_la - 130)) & ~0x3f) == 0 && ((1L << (_la - 130)) & 27L) != 0)) {
{
setState(671);
((CaseContext) _localctx).operand = booleanExpression(0);
}
}
setState(675);
_errHandler.sync(this);
_la = _input.LA(1);
do {
{
{
setState(674);
whenClause();
}
}
setState(677);
_errHandler.sync(this);
_la = _input.LA(1);
} while (_la == WHEN);
setState(681);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la == ELSE) {
{
setState(679);
match(ELSE);
setState(680);
((CaseContext) _localctx).elseClause = booleanExpression(0);
}
}
setState(683);
match(END);
}
break;
}
_ctx.stop = _input.LT(-1);
setState(692);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input, 96, _ctx);
while (_alt != 2 && _alt != org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER) {
if (_alt == 1) {
if (_parseListeners != null) triggerExitRuleEvent();
_prevctx = _localctx;
{
{
_localctx = new CastOperatorExpressionContext(new PrimaryExpressionContext(_parentctx, _parentState));
pushNewRecursionContext(_localctx, _startState, RULE_primaryExpression);
setState(687);
if (!(precpred(_ctx, 10))) throw new FailedPredicateException(this, "precpred(_ctx, 10)");
setState(688);
match(CAST_OP);
setState(689);
dataType();
}
}
}
setState(694);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input, 96, _ctx);
}
}
} catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
} finally {
unrollRecursionContexts(_parentctx);
}
return _localctx;
}
@SuppressWarnings("CheckReturnValue")
public static
|
CaseContext
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/sorted/state/AbstractBatchExecutionKeyState.java
|
{
"start": 1158,
"end": 4155
}
|
class ____<K, N, V> implements InternalKvState<K, N, V> {
private final V defaultValue;
private final TypeSerializer<V> stateTypeSerializer;
private final TypeSerializer<K> keySerializer;
private final TypeSerializer<N> namespaceSerializer;
private final Map<N, V> valuesForNamespaces = new HashMap<>();
private N currentNamespace;
private V currentNamespaceValue;
protected AbstractBatchExecutionKeyState(
V defaultValue,
TypeSerializer<K> keySerializer,
TypeSerializer<N> namespaceSerializer,
TypeSerializer<V> stateTypeSerializer) {
this.defaultValue = defaultValue;
this.stateTypeSerializer = stateTypeSerializer;
this.keySerializer = keySerializer;
this.namespaceSerializer = namespaceSerializer;
}
V getOrDefault() {
if (currentNamespaceValue == null && defaultValue != null) {
return stateTypeSerializer.copy(defaultValue);
}
return currentNamespaceValue;
}
public V getCurrentNamespaceValue() {
return currentNamespaceValue;
}
public void setCurrentNamespaceValue(V currentNamespaceValue) {
this.currentNamespaceValue = currentNamespaceValue;
}
@Override
public TypeSerializer<V> getValueSerializer() {
return stateTypeSerializer;
}
@Override
public TypeSerializer<K> getKeySerializer() {
return keySerializer;
}
@Override
public TypeSerializer<N> getNamespaceSerializer() {
return namespaceSerializer;
}
@Override
public void setCurrentNamespace(N namespace) {
if (Objects.equals(currentNamespace, namespace)) {
return;
}
if (currentNamespace != null) {
if (currentNamespaceValue == null) {
valuesForNamespaces.remove(currentNamespace);
} else {
valuesForNamespaces.put(currentNamespace, currentNamespaceValue);
}
}
currentNamespaceValue = valuesForNamespaces.get(namespace);
currentNamespace = namespace;
}
@Override
public byte[] getSerializedValue(
byte[] serializedKeyAndNamespace,
TypeSerializer<K> safeKeySerializer,
TypeSerializer<N> safeNamespaceSerializer,
TypeSerializer<V> safeValueSerializer) {
throw new UnsupportedOperationException(
"Queryable state is not supported in BATCH runtime.");
}
@Override
public StateIncrementalVisitor<K, N, V> getStateIncrementalVisitor(
int recommendedMaxNumberOfReturnedRecords) {
return null;
}
@Override
public void clear() {
this.currentNamespaceValue = null;
this.valuesForNamespaces.remove(currentNamespace);
}
void clearAllNamespaces() {
currentNamespaceValue = null;
currentNamespace = null;
valuesForNamespaces.clear();
}
}
|
AbstractBatchExecutionKeyState
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/MetaRecoveryContext.java
|
{
"start": 1203,
"end": 1582
}
|
class ____ {
public static final Logger LOG =
LoggerFactory.getLogger(MetaRecoveryContext.class.getName());
public final static int FORCE_NONE = 0;
public final static int FORCE_FIRST_CHOICE = 1;
public final static int FORCE_ALL = 2;
private int force;
/** Exception thrown when the user has requested processing to stop. */
static public
|
MetaRecoveryContext
|
java
|
micronaut-projects__micronaut-core
|
http-client/src/main/java/io/micronaut/http/client/netty/Pool49.java
|
{
"start": 14637,
"end": 21401
}
|
class ____ {
final EventExecutor loop;
final LocalPool<Http1PoolEntry> http1;
final LocalPool<Http2PoolEntry> http2;
/**
* Number of connections that have been requested for this loop but not yet been
* established.
*/
int localPendingConnections = 0;
final AtomicBoolean dispatchPendingRequestsQueued = new AtomicBoolean(false);
/**
* Pending requests that will definitely run on this event loop.
*/
final Queue<PendingRequest> localPendingRequests = new ArrayDeque<>();
/**
* Volatile flag to check whether we need more connections to serve the pending requests of
* this loop. Basically {@code localPendingConnections < localPendingRequests.size()},
* except this is volatile so other threads can also read it.
*/
volatile boolean needPendingConnection = false;
LocalPoolPair(EventExecutor loop) {
this.loop = loop;
http1 = new LocalPool<>();
http2 = new LocalPool<>();
}
/**
* Notify us that a request has been queued in {@link #globalPendingRequests} and we may
* want to pick it up with one of our idle connections.
*/
void notifyGlobalPendingRequestQueued() {
if (!dispatchPendingRequestsQueued.compareAndSet(false, true)) {
return;
}
loop.execute(() -> {
dispatchPendingRequestsQueued.set(false);
dispatchPendingRequests();
});
}
/**
* Try to find an already available pool entry to serve a request.
*
* @return The pool entry
*/
@Nullable
PoolEntry findAvailablePoolEntry() {
assert loop.inEventLoop();
PoolEntry http2 = this.http2.peekAvailable();
if (http2 != null) {
return http2;
}
PoolEntry http1 = this.http1.peekAvailable();
if (http1 != null) {
return http1;
}
return null;
}
/**
* Enqueue a request to be picked up by a local connection.
*
* @param request The request
*/
private void addLocalPendingRequest(PendingRequest request) {
localPendingRequests.add(request);
needPendingConnection = true;
}
/**
* Assign any pending requests (local or global) to available connections.
*/
void dispatchPendingRequests() {
// local requests first
while (!localPendingRequests.isEmpty()) {
PoolEntry poolEntry = findAvailablePoolEntry();
if (poolEntry == null) {
return;
}
PendingRequest request = localPendingRequests.poll();
assert request != null;
request.dispatchTo(poolEntry);
}
needPendingConnection = false;
// then global requests
if (globalPendingRequests.isEmpty()) {
return;
}
while (true) {
PoolEntry poolEntry = findAvailablePoolEntry();
if (poolEntry == null) {
return;
}
PendingRequest request = globalPendingRequests.poll();
if (request == null) {
return;
}
request.dispatchTo(poolEntry);
}
}
/**
* Second step of opening a connection. Like {@link #openConnectionStep1()}, this is
* housekeeping, but this time it's specific to a particular loop.
*
* @see #openConnectionStep1()
* @see #openConnectionStep2()
*/
void openConnectionStep2() {
localPendingConnections++;
needPendingConnection = localPendingRequests.size() < localPendingConnections;
}
/**
* Final step of opening a connection. This actually triggers opening a connection. We want
* to enqueue any request <i>before</i> calling this method, in case it's successful
* immediately.
*
* @see #openConnectionStep1()
* @see #openConnectionStep2()
*/
void openConnectionStep3() {
try {
listener.openNewConnection((EventLoop) loop);
} catch (Exception e) {
onNewConnectionFailure(e);
}
}
/**
* Open a local connection if limits permit and we have unassigned requests.
*/
void openLocalConnectionIfNecessary() {
assert loop.inEventLoop();
while (localPendingRequests.size() > localPendingConnections) {
if (!openConnectionStep1()) {
break;
}
openConnectionStep2();
openConnectionStep3();
}
}
/**
* Called when there's a connection failure for this pool. Will notify one pending request,
* and undo housekeeping from {@link #openConnectionStep1()} and
* {@link #openConnectionStep2()}.
*
* @param error The error to send to the pending request
*/
void onNewConnectionFailure(Throwable error) {
assert loop.inEventLoop();
globalStats.updateAndGet(s -> s.addPendingConnectionCount(-1)); // TODO: is this called for websockets?
localPendingConnections--;
PendingRequest local = localPendingRequests.poll();
if (local != null) {
local.tryCompleteExceptionally(error);
} else {
PendingRequest global = globalPendingRequests.poll();
if (global != null) {
global.tryCompleteExceptionally(error);
} else {
log.error("Failed to connect to remote", error);
}
}
openLocalConnectionIfNecessary();
openGlobalConnectionIfNecessary();
}
@Override
public String toString() {
String s;
if (loop instanceof SingleThreadIoEventLoop l) {
s = l.threadProperties().name();
} else {
s = loop.toString();
}
return "Pool[" + s + "]";
}
}
/**
* A local, event loop specific pool. This wraps a list of open connections, and a list of
* connections that are available to serve requests.
*
* @param <E> The connection type
*/
private final
|
LocalPoolPair
|
java
|
netty__netty
|
transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDomainSocketObjectEchoTest.java
|
{
"start": 935,
"end": 1339
}
|
class ____ extends SocketObjectEchoTest {
@Override
protected SocketAddress newSocketAddress() {
return EpollSocketTestPermutation.newDomainSocketAddress();
}
@Override
protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() {
return EpollSocketTestPermutation.INSTANCE.domainSocket();
}
}
|
EpollDomainSocketObjectEchoTest
|
java
|
apache__camel
|
test-infra/camel-test-infra-mongodb/src/main/java/org/apache/camel/test/infra/mongodb/services/MongoDBInfraService.java
|
{
"start": 941,
"end": 1307
}
|
interface ____ extends InfrastructureService {
/**
* The replica set URL in the format mongodb://host:port
*
* @return the replica set URL
*/
String getReplicaSetUrl();
/**
* The connection address in the format host:port
*
* @return the connection address
*/
String getConnectionAddress();
}
|
MongoDBInfraService
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/common/metrics/stats/SampledStat.java
|
{
"start": 1573,
"end": 1662
}
|
class ____ different statistics measured using this basic pattern.
*/
public abstract
|
define
|
java
|
google__gson
|
gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java
|
{
"start": 7252,
"end": 7315
}
|
enum ____ {}
@SuppressWarnings("serial")
private static
|
MyEnum
|
java
|
quarkusio__quarkus
|
core/deployment/src/main/java/io/quarkus/deployment/steps/ConfigGenerationBuildStep.java
|
{
"start": 6036,
"end": 18544
}
|
class ____ {
private static final MethodDescriptor CONFIG_BUILDER = MethodDescriptor.ofMethod(ConfigBuilder.class,
"configBuilder", SmallRyeConfigBuilder.class, SmallRyeConfigBuilder.class);
private static final MethodDescriptor WITH_SOURCES = MethodDescriptor.ofMethod(SmallRyeConfigBuilder.class,
"withSources", SmallRyeConfigBuilder.class, ConfigSource[].class);
@BuildStep
void nativeSupport(BuildProducer<RuntimeInitializedClassBuildItem> runtimeInitializedClassProducer) {
runtimeInitializedClassProducer.produce(new RuntimeInitializedClassBuildItem(
"io.quarkus.runtime.configuration.RuntimeConfigBuilder$UuidConfigSource$Holder"));
}
@BuildStep
void buildTimeRunTimeConfig(
ConfigurationBuildItem configItem,
BuildProducer<GeneratedClassBuildItem> generatedClass,
BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
BuildProducer<StaticInitConfigBuilderBuildItem> staticInitConfigBuilder,
BuildProducer<RunTimeConfigBuilderBuildItem> runTimeConfigBuilder) {
String builderClassName = "io.quarkus.runtime.generated.BuildTimeRunTimeFixedConfigSourceBuilder";
try (ClassCreator classCreator = ClassCreator.builder()
.classOutput(new GeneratedClassGizmoAdaptor(generatedClass, true))
.className(builderClassName)
.interfaces(ConfigBuilder.class)
.setFinal(true)
.build()) {
FieldDescriptor source = FieldDescriptor.of(classCreator.getClassName(), "source", ConfigSource.class);
classCreator.getFieldCreator(source).setModifiers(ACC_STATIC | Opcodes.ACC_FINAL);
MethodCreator clinit = classCreator.getMethodCreator("<clinit>", void.class);
clinit.setModifiers(ACC_STATIC);
ResultHandle map = clinit.newInstance(MethodDescriptor.ofConstructor(HashMap.class));
MethodDescriptor put = MethodDescriptor.ofMethod(Map.class, "put", Object.class, Object.class, Object.class);
for (Map.Entry<String, ConfigValue> entry : configItem.getReadResult().getBuildTimeRunTimeValues().entrySet()) {
if (entry.getValue().getValue() != null) {
clinit.invokeInterfaceMethod(put, map, clinit.load(entry.getKey()),
clinit.load(entry.getValue().getValue()));
}
}
ResultHandle defaultValuesSource = clinit.newInstance(
MethodDescriptor.ofConstructor(DefaultValuesConfigSource.class, Map.class, String.class, int.class), map,
clinit.load("BuildTime RunTime Fixed"), clinit.load(Integer.MAX_VALUE));
ResultHandle disableableConfigSource = clinit.newInstance(
MethodDescriptor.ofConstructor(DisableableConfigSource.class, ConfigSource.class),
defaultValuesSource);
clinit.writeStaticField(source, disableableConfigSource);
clinit.returnVoid();
MethodCreator method = classCreator.getMethodCreator(CONFIG_BUILDER);
ResultHandle configBuilder = method.getMethodParam(0);
ResultHandle configSources = method.newArray(ConfigSource.class, 1);
method.writeArrayValue(configSources, 0, method.readStaticField(source));
method.invokeVirtualMethod(WITH_SOURCES, configBuilder, configSources);
method.returnValue(configBuilder);
}
reflectiveClass.produce(ReflectiveClassBuildItem.builder(builderClassName).reason(getClass().getName()).build());
staticInitConfigBuilder.produce(new StaticInitConfigBuilderBuildItem(builderClassName));
runTimeConfigBuilder.produce(new RunTimeConfigBuilderBuildItem(builderClassName));
}
@BuildStep(onlyIfNot = { IsProduction.class }) // for dev or test
void runtimeOverrideConfig(
BuildProducer<StaticInitConfigBuilderBuildItem> staticInitConfigBuilder,
BuildProducer<RunTimeConfigBuilderBuildItem> runTimeConfigBuilder) {
staticInitConfigBuilder
.produce(new StaticInitConfigBuilderBuildItem(RuntimeOverrideConfigSourceBuilder.class.getName()));
runTimeConfigBuilder.produce(new RunTimeConfigBuilderBuildItem(RuntimeOverrideConfigSourceBuilder.class.getName()));
}
@BuildStep
void generateMappings(
NativeConfig nativeConfig,
ConfigurationBuildItem configItem,
CombinedIndexBuildItem combinedIndex,
BuildProducer<GeneratedClassBuildItem> generatedClasses,
BuildProducer<ReflectiveClassBuildItem> reflectiveClasses,
BuildProducer<ReflectiveMethodBuildItem> reflectiveMethods,
BuildProducer<ConfigClassBuildItem> configClasses,
BuildProducer<AdditionalConstrainedClassBuildItem> additionalConstrainedClasses) {
Map<String, GeneratedClassBuildItem> generatedConfigClasses = new HashMap<>();
processConfigMapping(nativeConfig, configItem, combinedIndex, generatedConfigClasses, reflectiveClasses,
reflectiveMethods,
configClasses, additionalConstrainedClasses);
List<ConfigClass> buildTimeRunTimeMappings = configItem.getReadResult().getBuildTimeRunTimeMappings();
for (ConfigClass buildTimeRunTimeMapping : buildTimeRunTimeMappings) {
processExtensionConfigMapping(nativeConfig, buildTimeRunTimeMapping, combinedIndex, generatedConfigClasses,
reflectiveClasses,
reflectiveMethods, configClasses, additionalConstrainedClasses);
}
List<ConfigClass> runTimeMappings = configItem.getReadResult().getRunTimeMappings();
for (ConfigClass runTimeMapping : runTimeMappings) {
processExtensionConfigMapping(nativeConfig, runTimeMapping, combinedIndex, generatedConfigClasses,
reflectiveClasses,
reflectiveMethods,
configClasses, additionalConstrainedClasses);
}
for (GeneratedClassBuildItem generatedConfigClass : generatedConfigClasses.values()) {
generatedClasses.produce(generatedConfigClass);
}
}
@BuildStep
void generateBuilders(
ConfigurationBuildItem configItem,
CombinedIndexBuildItem combinedIndex,
List<ConfigMappingBuildItem> configMappings,
List<RunTimeConfigurationDefaultBuildItem> runTimeDefaults,
List<StaticInitConfigBuilderBuildItem> staticInitConfigBuilders,
List<RunTimeConfigBuilderBuildItem> runTimeConfigBuilders,
BuildProducer<GeneratedClassBuildItem> generatedClass,
BuildProducer<ReflectiveClassBuildItem> reflectiveClass) throws Exception {
Map<String, String> defaultValues = new HashMap<>();
for (RunTimeConfigurationDefaultBuildItem e : runTimeDefaults) {
defaultValues.put(e.getKey(), e.getValue());
}
Set<String> converters = discoverService(Converter.class, reflectiveClass);
Set<String> interceptors = discoverService(ConfigSourceInterceptor.class, reflectiveClass);
Set<String> interceptorFactories = discoverService(ConfigSourceInterceptorFactory.class, reflectiveClass);
Set<String> configSources = discoverService(ConfigSource.class, reflectiveClass);
Set<String> configSourceProviders = discoverService(ConfigSourceProvider.class, reflectiveClass);
Set<String> configSourceFactories = discoverService(ConfigSourceFactory.class, reflectiveClass);
Set<String> secretKeyHandlers = discoverService(SecretKeysHandler.class, reflectiveClass);
Set<String> secretKeyHandlerFactories = discoverService(SecretKeysHandlerFactory.class, reflectiveClass);
Set<String> configCustomizers = discoverService(SmallRyeConfigBuilderCustomizer.class, reflectiveClass);
// TODO - introduce a way to ignore mappings that are only used for documentation or to prevent warnings
Set<ConfigClass> ignoreMappings = new LinkedHashSet<>();
ignoreMappings.add(ConfigClass.configClass(BuildAnalyticsConfig.class, "quarkus.analytics"));
ignoreMappings.add(ConfigClass.configClass(BuilderConfig.class, "quarkus.builder"));
ignoreMappings.add(ConfigClass.configClass(CommandLineRuntimeConfig.class, "quarkus"));
ignoreMappings.add(ConfigClass.configClass(DebugRuntimeConfig.class, "quarkus.debug"));
Set<ConfigClass> allMappings = new LinkedHashSet<>();
allMappings.addAll(staticSafeConfigMappings(configMappings));
allMappings.addAll(runtimeConfigMappings(configMappings));
allMappings.addAll(configItem.getReadResult().getBuildTimeRunTimeMappings());
allMappings.addAll(configItem.getReadResult().getRunTimeMappings());
allMappings.removeAll(ignoreMappings);
Set<ConfigClass> buildTimeRuntimeMappings = new LinkedHashSet<>(
configItem.getReadResult().getBuildTimeRunTimeMappings());
buildTimeRuntimeMappings.removeAll(ignoreMappings);
// Shared components
Map<Object, FieldDescriptor> sharedFields = generateSharedConfig(
generatedClass,
combinedIndex,
converters, allMappings, buildTimeRuntimeMappings);
// For Static Init Config
Set<ConfigClass> staticMappings = new LinkedHashSet<>(staticSafeConfigMappings(configMappings));
Set<String> staticCustomizers = new LinkedHashSet<>(staticSafeServices(configCustomizers));
staticCustomizers.add(StaticInitConfigBuilder.class.getName());
generateConfigBuilder(generatedClass, reflectiveClass, CONFIG_STATIC_NAME,
combinedIndex,
sharedFields,
defaultValues,
Map.of(),
converters,
interceptors,
staticSafeServices(interceptorFactories),
staticSafeServices(configSources),
staticSafeServices(configSourceProviders),
staticSafeServices(configSourceFactories),
secretKeyHandlers,
staticSafeServices(secretKeyHandlerFactories),
buildTimeRuntimeMappings,
Set.of(),
staticMappings,
configItem.getReadResult().getMappingsIgnorePaths(),
staticCustomizers,
staticInitConfigBuilders.stream().map(StaticInitConfigBuilderBuildItem::getBuilderClassName).collect(toSet()));
reflectiveClass.produce(ReflectiveClassBuildItem.builder(CONFIG_STATIC_NAME).build());
// For RunTime Config
Map<String, String> runtimeValues = new HashMap<>();
for (Entry<String, ConfigValue> entry : configItem.getReadResult().getRunTimeValues().entrySet()) {
runtimeValues.put(entry.getKey(), entry.getValue().getRawValue());
}
Set<ConfigClass> runTimeMappings = new LinkedHashSet<>();
runTimeMappings.addAll(runtimeConfigMappings(configMappings));
runTimeMappings.addAll(configItem.getReadResult().getBuildTimeRunTimeMappings());
runTimeMappings.addAll(configItem.getReadResult().getRunTimeMappings());
runTimeMappings.removeAll(ignoreMappings);
Set<String> runtimeCustomizers = new LinkedHashSet<>(configCustomizers);
runtimeCustomizers.add(RuntimeConfigBuilder.class.getName());
generateConfigBuilder(generatedClass, reflectiveClass, CONFIG_RUNTIME_NAME,
combinedIndex,
sharedFields,
defaultValues,
runtimeValues,
converters,
interceptors,
interceptorFactories,
configSources,
configSourceProviders,
configSourceFactories,
secretKeyHandlers,
secretKeyHandlerFactories,
buildTimeRuntimeMappings,
staticMappings,
runTimeMappings,
configItem.getReadResult().getMappingsIgnorePaths(),
runtimeCustomizers,
runTimeConfigBuilders.stream().map(RunTimeConfigBuilderBuildItem::getBuilderClassName).collect(toSet()));
reflectiveClass.produce(ReflectiveClassBuildItem.builder(CONFIG_RUNTIME_NAME).build());
}
/**
* Generate the Config
|
ConfigGenerationBuildStep
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfiguration.java
|
{
"start": 6821,
"end": 7449
}
|
class ____ {
@Bean
@ConditionalOnSingleCandidate(MBeanServer.class)
JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer,
EndpointObjectNameFactory endpointObjectNameFactory, ObjectProvider<ObjectMapper> objectMapper,
JmxEndpointsSupplier jmxEndpointsSupplier) {
JmxOperationResponseMapper responseMapper = new org.springframework.boot.actuate.endpoint.jmx.Jackson2JmxOperationResponseMapper(
objectMapper.getIfAvailable());
return new JmxEndpointExporter(mBeanServer, endpointObjectNameFactory, responseMapper,
jmxEndpointsSupplier.getEndpoints());
}
}
}
|
JmxJackson2EndpointConfiguration
|
java
|
quarkusio__quarkus
|
extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/HideCheckedExceptionMessageTest.java
|
{
"start": 2928,
"end": 3416
}
|
class ____ {
@Query
public String getSomething() throws IOException {
throw new IOException(IOEXCEPTION_MESSAGE);
}
@Query
public String getSomethingElse() throws InterruptedException {
throw new InterruptedException(INTERRUPTED_EXCEPTION_MESSAGE);
}
@Query
public String getSomethingElseElse() throws SQLException {
throw new SQLException(SQL_EXCEPTION_MESSAGE);
}
}
}
|
TestApi
|
java
|
elastic__elasticsearch
|
x-pack/plugin/profiling/src/main/java/org/elasticsearch/xpack/profiling/persistence/AbstractProfilingPersistenceManager.java
|
{
"start": 1672,
"end": 8491
}
|
class ____<T extends ProfilingIndexAbstraction> implements ClusterStateListener, Closeable {
protected final Logger logger = LogManager.getLogger(getClass());
private final AtomicBoolean inProgress = new AtomicBoolean(false);
private final ClusterService clusterService;
protected final ThreadPool threadPool;
protected final Client client;
private final IndexStateResolver indexStateResolver;
private volatile boolean templatesEnabled;
AbstractProfilingPersistenceManager(
ThreadPool threadPool,
Client client,
ClusterService clusterService,
IndexStateResolver indexStateResolver
) {
this.threadPool = threadPool;
this.client = client;
this.clusterService = clusterService;
this.indexStateResolver = indexStateResolver;
}
public void initialize() {
clusterService.addListener(this);
}
@Override
public void close() {
clusterService.removeListener(this);
}
public void setTemplatesEnabled(boolean templatesEnabled) {
this.templatesEnabled = templatesEnabled;
}
@Override
public final void clusterChanged(ClusterChangedEvent event) {
if (templatesEnabled == false) {
return;
}
// wait for the cluster state to be recovered
if (event.state().blocks().hasGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK)) {
return;
}
// If this node is not a master node, exit.
if (event.state().nodes().isLocalNodeElectedMaster() == false) {
return;
}
if (event.state().nodes().isMixedVersionCluster()) {
logger.debug("Skipping up-to-date check as cluster has mixed versions");
return;
}
if (areAllIndexTemplatesCreated(event, clusterService.getSettings()) == false) {
logger.trace("Skipping index creation; not all required resources are present yet");
return;
}
if (inProgress.compareAndSet(false, true) == false) {
logger.trace("Skipping index creation as changes are already in progress");
return;
}
// Only release the lock once all upgrade attempts have succeeded or failed.
try (var refs = new RefCountingRunnable(() -> inProgress.set(false))) {
ClusterState clusterState = event.state();
for (T index : getManagedIndices()) {
IndexState<T> state = indexStateResolver.getIndexState(clusterState, index);
if (state.getStatus().actionable) {
onIndexState(clusterState, state, ActionListener.releasing(refs.acquire()));
} else if (state.getStatus() == IndexStatus.TOO_OLD) {
logger.info("Aborting index creation as index [{}] is considered too old.", index);
return;
}
}
}
}
protected boolean areAllIndexTemplatesCreated(ClusterChangedEvent event, Settings settings) {
return ProfilingIndexTemplateRegistry.isAllResourcesCreated(event.state(), settings);
}
/**
* @return An iterable of all indices that are managed by this instance.
*/
protected abstract Iterable<T> getManagedIndices();
/**
* Handler that takes appropriate action for a certain index status.
*
* @param clusterState The current cluster state. Never <code>null</code>.
* @param indexState The state of the current index.
* @param listener Listener to be called on completion / errors.
*/
protected abstract void onIndexState(
ClusterState clusterState,
IndexState<T> indexState,
ActionListener<? super ActionResponse> listener
);
protected final void applyMigrations(IndexState<T> indexState, ActionListener<? super ActionResponse> listener) {
String writeIndex = indexState.getWriteIndex().getName();
try (var refs = new RefCountingRunnable(() -> listener.onResponse(null))) {
for (Migration migration : indexState.getPendingMigrations()) {
logger.debug("Applying migration [{}] for [{}].", migration, writeIndex);
migration.apply(
writeIndex,
(r -> updateMapping(r, ActionListener.releasing(refs.acquire()))),
(r -> updateSettings(r, ActionListener.releasing(refs.acquire())))
);
}
}
}
protected final void updateMapping(PutMappingRequest request, ActionListener<AcknowledgedResponse> listener) {
request.masterNodeTimeout(TimeValue.timeValueMinutes(1));
executeAsync("put mapping", request, listener, (req, l) -> client.admin().indices().putMapping(req, l));
}
protected final void updateSettings(UpdateSettingsRequest request, ActionListener<AcknowledgedResponse> listener) {
request.masterNodeTimeout(TimeValue.timeValueMinutes(1));
executeAsync("update settings", request, listener, (req, l) -> client.admin().indices().updateSettings(req, l));
}
protected final <Request extends ActionRequest & IndicesRequest, Response extends AcknowledgedResponse> void executeAsync(
final String actionName,
final Request request,
final ActionListener<Response> listener,
BiConsumer<Request, ActionListener<Response>> consumer
) {
final Executor executor = threadPool.generic();
executor.execute(() -> {
executeAsyncWithOrigin(client.threadPool().getThreadContext(), ClientHelper.PROFILING_ORIGIN, request, new ActionListener<>() {
@Override
public void onResponse(Response response) {
if (response.isAcknowledged() == false) {
logger.error(
"Could not execute action [{}] for indices [{}] for [{}], request was not acknowledged",
actionName,
request.indices(),
ClientHelper.PROFILING_ORIGIN
);
}
listener.onResponse(response);
}
@Override
public void onFailure(Exception ex) {
logger.error(
() -> format(
"Could not execute action [%s] for indices [%s] for [%s]",
actionName,
request.indices(),
ClientHelper.PROFILING_ORIGIN
),
ex
);
listener.onFailure(ex);
}
}, consumer);
});
}
}
|
AbstractProfilingPersistenceManager
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest.java
|
{
"start": 212,
"end": 1195
}
|
class ____ extends TestCase {
public void test_0() throws Exception {
Entity a = JSON.parseObject("{f1:null, f2:null}", Entity.class);
Assert.assertEquals(124, a.getF1());
Assert.assertEquals(null, a.getF2());
}
public void test_1() throws Exception {
Entity a = JSON.parseObject("{f1:22, f2:'33'}", Entity.class);
Assert.assertEquals(22, a.getF1());
Assert.assertEquals(33, a.getF2().intValue());
}
public void test_2() throws Exception {
Entity a = JSON.parseObject("{f1:'22', f2:33}", Entity.class);
Assert.assertEquals(22, a.getF1());
Assert.assertEquals(33, a.getF2().longValue());
}
public void test_error() throws Exception {
JSONException ex = null;
try {
JSON.parseObject("{f3:44}", UUID.class);
} catch (JSONException e) {
ex = e;
}
Assert.assertNotNull(ex);
}
public static
|
LongFieldDeserializerTest
|
java
|
mockito__mockito
|
mockito-core/src/test/java/org/mockitousage/bugs/ConcurrentModificationExceptionOnMultiThreadedVerificationTest.java
|
{
"start": 2443,
"end": 2512
}
|
interface ____ {
String targetMethod(String arg);
}
}
|
ITarget
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/nestedproperties/simple/SimpleNestedPropertiesTest.java
|
{
"start": 1060,
"end": 3988
}
|
class ____ {
@ProcessorTest
@WithClasses({ SimpleMapper.class })
public void testNull() {
TargetObject targetObject = SimpleMapper.MAPPER.toTargetObject( null );
assertThat( targetObject ).isNull();
}
@ProcessorTest
@WithClasses({ SimpleMapper.class })
public void testViaNull() {
SourceRoot sourceRoot = new SourceRoot();
// sourceRoot.getProps() is null
TargetObject targetObject = SimpleMapper.MAPPER.toTargetObject( sourceRoot );
assertEquals( 0L, targetObject.getPublicLongValue() );
assertEquals( 0L, targetObject.getLongValue() );
assertEquals( 0, targetObject.getIntValue() );
assertEquals( 0.0, targetObject.getDoubleValue(), 0.01 );
assertEquals( 0.0f, targetObject.getFloatValue(), 0.01f );
assertEquals( 0, targetObject.getShortValue() );
assertEquals( 0, targetObject.getCharValue() );
assertEquals( 0, targetObject.getByteValue() );
assertFalse( targetObject.isBooleanValue() );
assertNull( targetObject.getByteArray() );
assertNull( targetObject.getStringValue() );
}
@ProcessorTest
@WithClasses({ SimpleMapper.class })
public void testFilled() {
SourceRoot sourceRoot = new SourceRoot();
SourceProps sourceProps = new SourceProps();
sourceRoot.setProps( sourceProps );
sourceProps.publicLongValue = Long.MAX_VALUE;
sourceProps.setLongValue( Long.MAX_VALUE );
sourceProps.setIntValue( Integer.MAX_VALUE );
sourceProps.setDoubleValue( Double.MAX_VALUE );
sourceProps.setFloatValue( Float.MAX_VALUE );
sourceProps.setShortValue( Short.MAX_VALUE );
sourceProps.setCharValue( Character.MAX_VALUE );
sourceProps.setByteValue( Byte.MAX_VALUE );
sourceProps.setBooleanValue( true );
String stringValue = "lorem ipsum";
sourceProps.setByteArray( stringValue.getBytes() );
sourceProps.setStringValue( stringValue );
TargetObject targetObject = SimpleMapper.MAPPER.toTargetObject( sourceRoot );
assertEquals( Long.MAX_VALUE, targetObject.getPublicLongValue() );
assertEquals( Long.MAX_VALUE, targetObject.getLongValue() );
assertEquals( Integer.MAX_VALUE, targetObject.getIntValue() );
assertEquals( Double.MAX_VALUE, targetObject.getDoubleValue(), 0.01 );
assertEquals( Float.MAX_VALUE, targetObject.getFloatValue(), 0.01f );
assertEquals( Short.MAX_VALUE, targetObject.getShortValue() );
assertEquals( Character.MAX_VALUE, targetObject.getCharValue() );
assertEquals( Byte.MAX_VALUE, targetObject.getByteValue() );
assertTrue( targetObject.isBooleanValue() );
assertArrayEquals( stringValue.getBytes(), targetObject.getByteArray() );
assertEquals( stringValue, targetObject.getStringValue() );
}
}
|
SimpleNestedPropertiesTest
|
java
|
netty__netty
|
buffer/src/main/java/io/netty/buffer/AbstractPooledDerivedByteBuf.java
|
{
"start": 889,
"end": 953
}
|
class ____ derived {@link ByteBuf} implementations.
*/
abstract
|
for
|
java
|
apache__camel
|
core/camel-util/src/main/java/org/apache/camel/util/ReflectionHelper.java
|
{
"start": 4346,
"end": 5531
}
|
class ____ start looking at
* @param mc the callback to invoke for each method
*/
public static void doWithMethods(Class<?> clazz, MethodCallback mc) throws IllegalArgumentException {
// Keep backing up the inheritance hierarchy.
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (method.isBridge()) {
// skip the bridge methods which in Java 8 leads to problems with inheritance
// see https://bugs.openjdk.java.net/browse/JDK-6695379
continue;
}
try {
mc.doWith(method);
} catch (IllegalAccessException ex) {
throw new IllegalStateException("Shouldn't be illegal to access method '" + method.getName() + "': " + ex);
}
}
if (clazz.getSuperclass() != null) {
doWithMethods(clazz.getSuperclass(), mc);
} else if (clazz.isInterface()) {
for (Class<?> superIfc : clazz.getInterfaces()) {
doWithMethods(superIfc, mc);
}
}
}
/**
* Attempt to find a {@link Method} on the supplied
|
to
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/compositefk/ManyToOneEmbeddedIdWithToOneFKTest.java
|
{
"start": 8284,
"end": 8914
}
|
class ____ {
@EmbeddedId
private PK pk;
private byte privilegeMask;
public DataCenterUser() {
}
public DataCenterUser(DataCenter dataCenter, String username, byte privilegeMask) {
this( new PK( dataCenter, username ), privilegeMask );
}
public DataCenterUser(PK pk, byte privilegeMask) {
this.pk = pk;
this.privilegeMask = privilegeMask;
}
public PK getPk() {
return pk;
}
public void setPk(PK pk) {
this.pk = pk;
}
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
}
@Embeddable
public static
|
DataCenterUser
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/action/admin/cluster/desirednodes/UpdateDesiredNodesResponseSerializationTests.java
|
{
"start": 655,
"end": 1286
}
|
class ____ extends AbstractWireSerializingTestCase<UpdateDesiredNodesResponse> {
@Override
protected Writeable.Reader<UpdateDesiredNodesResponse> instanceReader() {
return UpdateDesiredNodesResponse::new;
}
@Override
protected UpdateDesiredNodesResponse createTestInstance() {
return new UpdateDesiredNodesResponse(randomBoolean());
}
@Override
protected UpdateDesiredNodesResponse mutateInstance(UpdateDesiredNodesResponse instance) {
return new UpdateDesiredNodesResponse(instance.hasReplacedExistingHistoryId() == false);
}
}
|
UpdateDesiredNodesResponseSerializationTests
|
java
|
apache__flink
|
flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/testutils/junit/extensions/retry/strategy/RetryOnExceptionStrategy.java
|
{
"start": 1124,
"end": 2793
}
|
class ____ extends AbstractRetryStrategy {
private static final Logger LOG = LoggerFactory.getLogger(RetryOnExceptionStrategy.class);
private final Class<? extends Throwable> repeatableException;
public RetryOnExceptionStrategy(
int retryTimes, Class<? extends Throwable> repeatableException) {
super(retryTimes, true);
this.repeatableException = repeatableException;
}
@Override
public void handleException(String testName, int attemptIndex, Throwable throwable)
throws Throwable {
// Failed when reach the total retry times
if (attemptIndex >= totalTimes) {
LOG.error("Test Failed at the last retry.", throwable);
throw throwable;
}
if (repeatableException.isAssignableFrom(throwable.getClass())) {
// continue retrying when get some repeatable exceptions
String retryMsg =
String.format(
"Retry test %s[%d/%d] failed with repeatable exception, continue retrying.",
testName, attemptIndex, totalTimes);
LOG.warn(retryMsg, throwable);
throw new TestAbortedException(retryMsg);
} else {
// stop retrying when get an unrepeatable exception
stopFollowingAttempts();
LOG.error(
String.format(
"Retry test %s[%d/%d] failed with unrepeatable exception, stop retrying.",
testName, attemptIndex, totalTimes),
throwable);
throw throwable;
}
}
}
|
RetryOnExceptionStrategy
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java
|
{
"start": 22399,
"end": 23761
}
|
class ____
extends EndpointDiscoverer<SpecializedExposableEndpoint, SpecializedOperation> {
SpecializedEndpointDiscoverer(ApplicationContext applicationContext) {
this(applicationContext, Collections.emptyList(), Collections.emptyList());
}
SpecializedEndpointDiscoverer(ApplicationContext applicationContext,
Collection<EndpointFilter<SpecializedExposableEndpoint>> filters,
Collection<OperationFilter<SpecializedOperation>> operationFilters) {
super(applicationContext, new ConversionServiceParameterValueMapper(), Collections.emptyList(), filters,
operationFilters);
}
@Override
protected SpecializedExposableEndpoint createEndpoint(Object endpointBean, EndpointId id, Access defaultAccess,
Collection<SpecializedOperation> operations) {
return new SpecializedExposableEndpoint(this, endpointBean, id, defaultAccess, operations);
}
@Override
protected SpecializedOperation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod,
OperationInvoker invoker) {
return new SpecializedOperation(operationMethod, invoker);
}
@Override
protected OperationKey createOperationKey(SpecializedOperation operation) {
return new OperationKey(operation.getOperationMethod(),
() -> "TestOperation " + operation.getOperationMethod());
}
}
static
|
SpecializedEndpointDiscoverer
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.