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 | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToIp.java | {
"start": 3216,
"end": 7826
} | class ____ extends EsqlScalarFunction implements SurrogateExpression, OptionalArgument, ConvertFunction {
private static final String LEADING_ZEROS = "leading_zeros";
public static final Map<String, DataType> ALLOWED_OPTIONS = Map.ofEntries(Map.entry(LEADING_ZEROS, KEYWORD));
private final Expression field;
private final Expression options;
@FunctionInfo(
returnType = "ip",
description = "Converts an input string to an IP value.",
examples = {
@Example(file = "ip", tag = "to_ip", explanation = """
Note that in this example, the last conversion of the string isn’t possible.
When this happens, the result is a `null` value. In this case a _Warning_ header is added to the response.
The header will provide information on the source of the failure:
`"Line 1:68: evaluation of [TO_IP(str2)] failed, treating result as null. Only first 20 failures recorded."`
A following header will contain the failure reason and the offending value:
`"java.lang.IllegalArgumentException: 'foo' is not an IP string literal."`"""),
@Example(file = "ip", tag = "to_ip_leading_zeros_octal", explanation = """
Parse v4 addresses with leading zeros as octal. Like `ping` or `ftp`.
"""),
@Example(file = "ip", tag = "to_ip_leading_zeros_decimal", explanation = """
Parse v4 addresses with leading zeros as decimal. Java's `InetAddress.getByName`.
""") }
)
public ToIp(
Source source,
@Param(
name = "field",
type = { "ip", "keyword", "text" },
description = "Input value. The input can be a single- or multi-valued column or an expression."
) Expression field,
@MapParam(
name = "options",
params = {
@MapParam.MapParamEntry(
name = "leading_zeros",
type = "keyword",
valueHint = { "reject", "octal", "decimal" },
description = "What to do with leading 0s in IPv4 addresses."
) },
description = "(Optional) Additional options.",
optional = true
) Expression options
) {
super(source, options == null ? List.of(field) : List.of(field, options));
this.field = field;
this.options = options;
}
@Override
public String getWriteableName() {
throw new UnsupportedOperationException("not serialized");
}
@Override
public void writeTo(StreamOutput out) throws IOException {
throw new UnsupportedOperationException("not serialized");
}
@Override
public DataType dataType() {
return IP;
}
@Override
public Expression replaceChildren(List<Expression> newChildren) {
return new ToIp(source(), newChildren.get(0), newChildren.size() == 1 ? null : newChildren.get(1));
}
@Override
protected NodeInfo<? extends Expression> info() {
return NodeInfo.create(this, ToIp::new, field, options);
}
@Override
public EvalOperator.ExpressionEvaluator.Factory toEvaluator(ToEvaluator toEvaluator) {
throw new UnsupportedOperationException("should be rewritten");
}
@Override
public Expression surrogate() {
return LeadingZeros.from((MapExpression) options).surrogate(source(), field);
}
@Override
public Expression field() {
return field;
}
@Override
public Set<DataType> supportedTypes() {
// All ToIpLeadingZeros* functions support the same input set. So we just pick one.
return ToIpLeadingZerosRejected.EVALUATORS.keySet();
}
@Override
protected TypeResolution resolveType() {
if (childrenResolved() == false) {
return new TypeResolution("Unresolved children");
}
TypeResolution resolution = isTypeOrUnionType(
field,
ToIpLeadingZerosRejected.EVALUATORS::containsKey,
sourceText(),
null,
supportedTypesNames(supportedTypes())
).and(Options.resolve(options, source(), SECOND, ALLOWED_OPTIONS));
if (resolution.unresolved()) {
return resolution;
}
try {
LeadingZeros.from((MapExpression) options);
} catch (IllegalArgumentException e) {
return new TypeResolution(e.getMessage());
}
return TypeResolution.TYPE_RESOLVED;
}
public | ToIp |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/TransformerResolver.java | {
"start": 1143,
"end": 2566
} | interface ____<K> {
/**
* Attempts to resolve the transformer for the given key. Usually uses the factory finder URI to resolve the
* transformer by its name derived from the given key. Transformer names may use scheme and name as a combination in
* order to resolve component specific transformers. Usually implements a fallback resolving mechanism when no
* matching transformer is found (e.g. search for generic Camel transformers just using the name).
*
* @param key the transformer key.
* @param camelContext the current Camel context.
* @return data type transformer resolved via URI factory finder or null if not found.
*/
Transformer resolve(K key, CamelContext camelContext);
/**
* Normalize transformer key to conform with factory finder resource path. Replaces all non supported characters
* such as slashes and colons to dashes. Automatically removes the default scheme prefix as it should not be part of
* the resource path.
*
* @param key the transformer key
* @return normalized String representation of the key
*/
default String normalize(K key) {
String keyString = key.toString();
keyString = StringHelper.after(keyString, DataType.DEFAULT_SCHEME + ":", keyString);
return StringHelper.sanitize(keyString).toLowerCase(Locale.US);
}
}
| TransformerResolver |
java | elastic__elasticsearch | x-pack/plugin/downsample/src/main/java/org/elasticsearch/xpack/downsample/LastValueFieldProducer.java | {
"start": 6912,
"end": 8157
} | class ____ extends LastValueFieldProducer {
private FlattenedFieldProducer(String name, boolean producesMultiValue) {
super(name, producesMultiValue);
}
@Override
public void write(XContentBuilder builder) throws IOException {
if (isEmpty() == false) {
builder.startObject(name());
var value = lastValue();
List<BytesRef> list;
if (value instanceof Object[] values) {
list = new ArrayList<>(values.length);
for (Object v : values) {
list.add(new BytesRef(v.toString()));
}
} else {
list = List.of(new BytesRef(value.toString()));
}
var iterator = list.iterator();
var helper = new FlattenedFieldSyntheticWriterHelper(() -> {
if (iterator.hasNext()) {
return iterator.next();
} else {
return null;
}
});
helper.write(builder);
builder.endObject();
}
}
}
}
| FlattenedFieldProducer |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/calcite/sql2rel/RelDecorrelator.java | {
"start": 78762,
"end": 80269
} | class ____.
newType = call.getType();
}
newCall = rexBuilder.makeCall(newType, operator, clonedOperands);
} else {
newCall = call;
}
if (projectPulledAboveLeftCorrelator && (nullIndicator != null)) {
return createCaseExpression(nullIndicator, null, newCall);
}
return newCall;
}
}
/**
* Rule to remove an Aggregate with SINGLE_VALUE. For cases like:
*
* <pre>{@code
* Aggregate(SINGLE_VALUE)
* Project(single expression)
* Aggregate
* }</pre>
*
* <p>For instance, the following subtree from TPCH query 17:
*
* <pre>{@code
* LogicalAggregate(group=[{}], agg#0=[SINGLE_VALUE($0)])
* LogicalProject(EXPR$0=[*(0.2:DECIMAL(2, 1), $0)])
* LogicalAggregate(group=[{}], agg#0=[AVG($0)])
* LogicalProject(L_QUANTITY=[$4])
* LogicalFilter(condition=[=($1, $cor0.P_PARTKEY)])
* LogicalTableScan(table=[[TPCH_01, LINEITEM]])
* }</pre>
*
* <p>will be converted into:
*
* <pre>{@code
* LogicalProject($f0=[*(0.2:DECIMAL(2, 1), $0)])
* LogicalAggregate(group=[{}], agg#0=[AVG($0)])
* LogicalProject(L_QUANTITY=[$4])
* LogicalFilter(condition=[=($1, $cor0.P_PARTKEY)])
* LogicalTableScan(table=[[TPCH_01, LINEITEM]])
* }</pre>
*/
public static final | RexShuttle |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaSchemaGeneratorWithHbm2DdlCharsetNameTest.java | {
"start": 458,
"end": 830
} | class ____
extends JpaSchemaGeneratorTest {
@Override
public String getScriptFolderPath() {
return super.getScriptFolderPath() + "iso8859/";
}
@Override
protected Map buildSettings() {
Map settings = super.buildSettings();
settings.put( AvailableSettings.HBM2DDL_CHARSET_NAME, "ISO-8859-1" );
return settings;
}
}
| JpaSchemaGeneratorWithHbm2DdlCharsetNameTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/connections/LazyLoadingConnectionCloseTest.java | {
"start": 7176,
"end": 7696
} | class ____ {
private Long id;
private String name;
private SimpleEntity parent;
@Id
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
public SimpleEntity getParent() {
return parent;
}
public void setParent(final SimpleEntity parent) {
this.parent = parent;
}
}
}
| ChildEntity |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/RemoveGlobalVariableTest.java | {
"start": 1185,
"end": 2810
} | class ____ extends ContextTestSupport {
private MockEndpoint end;
private MockEndpoint mid;
private final String variableName = "foo";
private final String expectedVariableValue = "bar";
@Test
public void testSetHeaderMidRouteThenRemove() throws Exception {
mid.expectedMessageCount(1);
end.expectedMessageCount(1);
template.sendBody("direct:start", "<blah/>");
// make sure we got the message
assertMockEndpointsSatisfied();
List<Exchange> midExchanges = mid.getExchanges();
Exchange midExchange = midExchanges.get(0);
String actualVariableValue = midExchange.getVariable(variableName, String.class);
// should be stored on global so null
assertNull(actualVariableValue);
List<Exchange> endExchanges = end.getExchanges();
Exchange endExchange = endExchanges.get(0);
// should be stored as global variable (but removed)
assertNull(context.getVariable(variableName));
}
@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
end = getMockEndpoint("mock:end");
mid = getMockEndpoint("mock:mid");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start").setVariable("global:" + variableName).constant(expectedVariableValue).to("mock:mid")
.removeVariable("global:" + variableName)
.to("mock:end");
}
};
}
}
| RemoveGlobalVariableTest |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/WordCount.java | {
"start": 3010,
"end": 5667
} | class ____ extends MapReduceBase
implements Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterator<IntWritable> values,
OutputCollector<Text, IntWritable> output,
Reporter reporter) throws IOException {
int sum = 0;
while (values.hasNext()) {
sum += values.next().get();
}
output.collect(key, new IntWritable(sum));
}
}
static int printUsage() {
System.out.println("wordcount [-m <maps>] [-r <reduces>] <input> <output>");
ToolRunner.printGenericCommandUsage(System.out);
return -1;
}
/**
* The main driver for word count map/reduce program.
* Invoke this method to submit the map/reduce job.
* @throws IOException When there is communication problems with the
* job tracker.
*/
public int run(String[] args) throws Exception {
JobConf conf = new JobConf(getConf(), WordCount.class);
conf.setJobName("wordcount");
// the keys are words (strings)
conf.setOutputKeyClass(Text.class);
// the values are counts (ints)
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(MapClass.class);
conf.setCombinerClass(Reduce.class);
conf.setReducerClass(Reduce.class);
List<String> other_args = new ArrayList<String>();
for(int i=0; i < args.length; ++i) {
try {
if ("-m".equals(args[i])) {
conf.setNumMapTasks(Integer.parseInt(args[++i]));
} else if ("-r".equals(args[i])) {
conf.setNumReduceTasks(Integer.parseInt(args[++i]));
} else {
other_args.add(args[i]);
}
} catch (NumberFormatException except) {
System.out.println("ERROR: Integer expected instead of " + args[i]);
return printUsage();
} catch (ArrayIndexOutOfBoundsException except) {
System.out.println("ERROR: Required parameter missing from " +
args[i-1]);
return printUsage();
}
}
// Make sure there are exactly 2 parameters left.
if (other_args.size() != 2) {
System.out.println("ERROR: Wrong number of parameters: " +
other_args.size() + " instead of 2.");
return printUsage();
}
FileInputFormat.setInputPaths(conf, other_args.get(0));
FileOutputFormat.setOutputPath(conf, new Path(other_args.get(1)));
JobClient.runJob(conf);
return 0;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new WordCount(), args);
System.exit(res);
}
}
| Reduce |
java | apache__maven | api/maven-api-core/src/main/java/org/apache/maven/api/services/VersionResolverRequest.java | {
"start": 3538,
"end": 5371
} | class ____ extends BaseRequest<Session>
implements VersionResolverRequest {
private final ArtifactCoordinates artifactCoordinates;
private final List<RemoteRepository> repositories;
@SuppressWarnings("checkstyle:ParameterNumber")
DefaultVersionResolverRequest(
@Nonnull Session session,
@Nullable RequestTrace trace,
@Nonnull ArtifactCoordinates artifactCoordinates,
@Nullable List<RemoteRepository> repositories) {
super(session, trace);
this.artifactCoordinates = artifactCoordinates;
this.repositories = validate(repositories);
}
@Nonnull
@Override
public ArtifactCoordinates getArtifactCoordinates() {
return artifactCoordinates;
}
@Nullable
@Override
public List<RemoteRepository> getRepositories() {
return repositories;
}
@Override
public boolean equals(Object o) {
return o instanceof DefaultVersionResolverRequest that
&& Objects.equals(artifactCoordinates, that.artifactCoordinates)
&& Objects.equals(repositories, that.repositories);
}
@Override
public int hashCode() {
return Objects.hash(artifactCoordinates, repositories);
}
@Override
public String toString() {
return "VersionResolverRequest[" + "artifactCoordinates="
+ artifactCoordinates + ", repositories="
+ repositories + ']';
}
}
}
}
| DefaultVersionResolverRequest |
java | apache__flink | flink-core/src/main/java/org/apache/flink/util/InstantiationUtil.java | {
"start": 16846,
"end": 25032
} | class ____ no (implicit) public nullary constructor, i.e. a constructor without arguments.";
} else {
return null;
}
}
@Nullable
public static <T> T readObjectFromConfig(Configuration config, String key, ClassLoader cl)
throws IOException, ClassNotFoundException {
byte[] bytes = config.getBytes(key, null);
if (bytes == null) {
return null;
}
return deserializeObject(bytes, cl);
}
public static void writeObjectToConfig(Object o, Configuration config, String key)
throws IOException {
byte[] bytes = serializeObject(o);
config.setBytes(key, bytes);
}
public static <T> byte[] serializeToByteArray(TypeSerializer<T> serializer, T record)
throws IOException {
if (record == null) {
throw new NullPointerException("Record to serialize to byte array must not be null.");
}
ByteArrayOutputStream bos = new ByteArrayOutputStream(64);
DataOutputViewStreamWrapper outputViewWrapper = new DataOutputViewStreamWrapper(bos);
serializer.serialize(record, outputViewWrapper);
return bos.toByteArray();
}
public static <T> T deserializeFromByteArray(TypeSerializer<T> serializer, byte[] buf)
throws IOException {
if (buf == null) {
throw new NullPointerException("Byte array to deserialize from must not be null.");
}
DataInputViewStreamWrapper inputViewWrapper =
new DataInputViewStreamWrapper(new ByteArrayInputStream(buf));
return serializer.deserialize(inputViewWrapper);
}
public static <T> T deserializeFromByteArray(TypeSerializer<T> serializer, T reuse, byte[] buf)
throws IOException {
if (buf == null) {
throw new NullPointerException("Byte array to deserialize from must not be null.");
}
DataInputViewStreamWrapper inputViewWrapper =
new DataInputViewStreamWrapper(new ByteArrayInputStream(buf));
return serializer.deserialize(reuse, inputViewWrapper);
}
public static <T> T deserializeObject(byte[] bytes, ClassLoader cl)
throws IOException, ClassNotFoundException {
return deserializeObject(new ByteArrayInputStream(bytes), cl);
}
public static <T> T deserializeObject(InputStream in, ClassLoader cl)
throws IOException, ClassNotFoundException {
return deserializeObject(in, cl, false);
}
@SuppressWarnings("unchecked")
public static <T> T deserializeObject(
InputStream in, ClassLoader cl, boolean tolerateKnownVersionMismatch)
throws IOException, ClassNotFoundException {
final ClassLoader old = Thread.currentThread().getContextClassLoader();
// not using resource try to avoid AutoClosable's close() on the given stream
try {
ObjectInputStream oois =
tolerateKnownVersionMismatch
? new InstantiationUtil.FailureTolerantObjectInputStream(in, cl)
: new InstantiationUtil.ClassLoaderObjectInputStream(in, cl);
Thread.currentThread().setContextClassLoader(cl);
return (T) oois.readObject();
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
public static <T> T decompressAndDeserializeObject(byte[] bytes, ClassLoader cl)
throws IOException, ClassNotFoundException {
return deserializeObject(new InflaterInputStream(new ByteArrayInputStream(bytes)), cl);
}
public static byte[] serializeObject(Object o) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(o);
oos.flush();
return baos.toByteArray();
}
}
public static void serializeObject(OutputStream out, Object o) throws IOException {
ObjectOutputStream oos =
out instanceof ObjectOutputStream
? (ObjectOutputStream) out
: new ObjectOutputStream(out);
oos.writeObject(o);
}
public static byte[] serializeObjectAndCompress(Object o) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
DeflaterOutputStream dos = new DeflaterOutputStream(baos);
ObjectOutputStream oos = new ObjectOutputStream(dos)) {
oos.writeObject(o);
oos.flush();
dos.close();
return baos.toByteArray();
}
}
public static boolean isSerializable(Object o) {
try {
serializeObject(o);
} catch (IOException e) {
return false;
}
return true;
}
/**
* Clones the given serializable object using Java serialization.
*
* @param obj Object to clone
* @param <T> Type of the object to clone
* @return The cloned object
* @throws IOException Thrown if the serialization or deserialization process fails.
* @throws ClassNotFoundException Thrown if any of the classes referenced by the object cannot
* be resolved during deserialization.
*/
public static <T extends Serializable> T clone(T obj)
throws IOException, ClassNotFoundException {
if (obj == null) {
return null;
} else {
return clone(obj, obj.getClass().getClassLoader());
}
}
/**
* Clones the given serializable object using Java serialization, using the given classloader to
* resolve the cloned classes.
*
* @param obj Object to clone
* @param classLoader The classloader to resolve the classes during deserialization.
* @param <T> Type of the object to clone
* @return Cloned object
* @throws IOException Thrown if the serialization or deserialization process fails.
* @throws ClassNotFoundException Thrown if any of the classes referenced by the object cannot
* be resolved during deserialization.
*/
public static <T extends Serializable> T clone(T obj, ClassLoader classLoader)
throws IOException, ClassNotFoundException {
if (obj == null) {
return null;
} else {
final byte[] serializedObject = serializeObject(obj);
return deserializeObject(serializedObject, classLoader);
}
}
/**
* Unchecked equivalent of {@link #clone(Serializable)}.
*
* @param obj Object to clone
* @param <T> Type of the object to clone
* @return The cloned object
*/
public static <T extends Serializable> T cloneUnchecked(T obj) {
try {
return clone(obj, obj.getClass().getClassLoader());
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(
String.format("Unable to clone instance of %s.", obj.getClass().getName()), e);
}
}
/**
* Clones the given writable using the {@link IOReadableWritable serialization}.
*
* @param original Object to clone
* @param <T> Type of the object to clone
* @return Cloned object
* @throws IOException Thrown is the serialization fails.
*/
public static <T extends IOReadableWritable> T createCopyWritable(T original)
throws IOException {
if (original == null) {
return null;
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (DataOutputViewStreamWrapper out = new DataOutputViewStreamWrapper(baos)) {
original.write(out);
}
final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
try (DataInputViewStreamWrapper in = new DataInputViewStreamWrapper(bais)) {
@SuppressWarnings("unchecked")
T copy = (T) instantiate(original.getClass());
copy.read(in);
return copy;
}
}
/**
* Loads a | has |
java | elastic__elasticsearch | modules/lang-painless/src/test/java/org/elasticsearch/painless/FactoryTests.java | {
"start": 5101,
"end": 5449
} | interface ____ {
FactoryTestScript newInstance(Map<String, Object> params);
boolean needsTest();
boolean needsNothing();
}
public static final ScriptContext<FactoryTestScript.Factory> CONTEXT = new ScriptContext<>("test", FactoryTestScript.Factory.class);
}
public abstract static | Factory |
java | apache__camel | dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesHelper.java | {
"start": 2136,
"end": 2259
} | class ____ access to cached Kubernetes client. Also provides access to generic Json and Yaml mappers.
*/
public final | provides |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/nullness/NullArgumentForNonNullParameterTest.java | {
"start": 2375,
"end": 2755
} | class ____ {
void consume(@Nonnull String s) {}
void foo() {
consume(null);
}
}
""")
.doTest();
}
@Test
public void positiveJavaOptionalOf() {
conservativeHelper
.addSourceLines(
"Foo.java",
"""
import java.util.Optional;
| Foo |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableAddExtPartition.java | {
"start": 416,
"end": 1073
} | class ____ extends SQLObjectImpl implements SQLAlterTableItem, MySqlObject {
private MySqlExtPartition extPartition;
@Override
public void accept0(MySqlASTVisitor visitor) {
visitor.visit(this);
visitor.endVisit(this);
}
@Override
protected void accept0(SQLASTVisitor visitor) {
visitor.visit(this);
visitor.endVisit(this);
}
public void setExPartition(MySqlExtPartition x) {
if (x != null) {
x.setParent(this);
}
this.extPartition = x;
}
public MySqlExtPartition getExtPartition() {
return extPartition;
}
}
| SQLAlterTableAddExtPartition |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/admin/indices/close/TransportVerifyShardBeforeCloseActionTests.java | {
"start": 18164,
"end": 19220
} | class ____ implements ReplicationOperation.PrimaryResult<TransportVerifyShardBeforeCloseAction.ShardRequest> {
private final TransportVerifyShardBeforeCloseAction.ShardRequest replicaRequest;
private final SetOnce<ReplicationResponse.ShardInfo> shardInfo;
private PrimaryResult(final TransportVerifyShardBeforeCloseAction.ShardRequest replicaRequest) {
this.replicaRequest = replicaRequest;
this.shardInfo = new SetOnce<>();
}
@Override
public TransportVerifyShardBeforeCloseAction.ShardRequest replicaRequest() {
return replicaRequest;
}
@Override
public void setShardInfo(ReplicationResponse.ShardInfo shardInfo) {
this.shardInfo.set(shardInfo);
}
@Override
public void runPostReplicationActions(ActionListener<Void> listener) {
listener.onResponse(null);
}
public ReplicationResponse.ShardInfo getShardInfo() {
return shardInfo.get();
}
}
}
| PrimaryResult |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/SecuredConfigFileSettingAccessPermission.java | {
"start": 1172,
"end": 1351
} | class ____ extends BasicPermission {
public SecuredConfigFileSettingAccessPermission(String setting) {
super(setting, "");
}
}
| SecuredConfigFileSettingAccessPermission |
java | apache__camel | dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java | {
"start": 90430,
"end": 91314
} | class ____ use.", displayName = "Class Type"),
@YamlProperty(name = "id", type = "string", description = "The id of this node", displayName = "Id"),
@YamlProperty(name = "locale", type = "string", description = "To configure a default locale to use, such as us for united states. To use the JVM platform default locale then use the name default", displayName = "Locale"),
@YamlProperty(name = "type", type = "enum:Csv,Fixed,KeyValue", description = "Whether to use Csv, Fixed, or KeyValue.", displayName = "Type"),
@YamlProperty(name = "unwrapSingleInstance", type = "boolean", defaultValue = "true", description = "When unmarshalling should a single instance be unwrapped and returned instead of wrapped in a java.util.List.", displayName = "Unwrap Single Instance")
}
)
public static | to |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java | {
"start": 75469,
"end": 75564
} | interface ____ extends BaseDefaultMethods {
}
@Configuration
public static | DefaultMethodsConfig |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/rest/ChunkedZipResponseIT.java | {
"start": 3637,
"end": 3997
} | class ____ extends ESIntegTestCase {
@Override
protected boolean addMockHttpTransport() {
return false;
}
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return CollectionUtils.appendToCopyNoNullElements(super.nodePlugins(), RandomZipResponsePlugin.class);
}
public static | ChunkedZipResponseIT |
java | quarkusio__quarkus | extensions/jdbc/jdbc-mysql/deployment/src/main/java/io/quarkus/jdbc/mysql/deployment/MySQLJDBCReflections.java | {
"start": 2625,
"end": 9596
} | class ____ {
@BuildStep
void registerDriverForReflection(BuildProducer<ReflectiveClassBuildItem> reflectiveClass) {
reflectiveClass.produce(ReflectiveClassBuildItem.builder(Driver.class.getName()).build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(FailoverDnsSrvConnectionUrl.class.getName())
.build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(FailoverConnectionUrl.class.getName()).build());
reflectiveClass
.produce(ReflectiveClassBuildItem.builder(SingleConnectionUrl.class.getName())
.build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(LoadBalanceConnectionUrl.class.getName())
.build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(LoadBalanceDnsSrvConnectionUrl.class.getName())
.build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(ReplicationDnsSrvConnectionUrl.class.getName())
.build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(ReplicationConnectionUrl.class.getName())
.build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(XDevApiConnectionUrl.class.getName()).build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(XDevApiDnsSrvConnectionUrl.class.getName())
.build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(com.mysql.cj.jdbc.ha.LoadBalancedAutoCommitInterceptor.class.getName())
.build());
reflectiveClass
.produce(ReflectiveClassBuildItem.builder(StandardLogger.class.getName()).build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(Wrapper.class.getName()).build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(com.mysql.cj.jdbc.MysqlDataSource.class.getName())
.methods().build());
}
@BuildStep
void registerSocketFactoryForReflection(BuildProducer<ReflectiveClassBuildItem> reflectiveClass) {
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(NamedPipeSocketFactory.class.getName()).build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(StandardSocketFactory.class.getName()).build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(SocksProxySocketFactory.class.getName()).build());
}
@BuildStep
void registerExceptionsForReflection(BuildProducer<ReflectiveClassBuildItem> reflectiveClass) {
reflectiveClass.produce(ReflectiveClassBuildItem.builder(CJCommunicationsException.class.getName())
.build());
reflectiveClass
.produce(ReflectiveClassBuildItem.builder(CJConnectionFeatureNotAvailableException.class.getName())
.build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(CJOperationNotSupportedException.class.getName())
.build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(CJTimeoutException.class.getName()).build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(CJPacketTooBigException.class.getName()).build());
reflectiveClass
.produce(ReflectiveClassBuildItem.builder(CJException.class.getName()).build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(AssertionFailedException.class.getName())
.build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(CJOperationNotSupportedException.class.getName())
.build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(ClosedOnExpiredPasswordException.class.getName())
.build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(ConnectionIsClosedException.class.getName())
.build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(DataConversionException.class.getName()).build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(DataReadException.class.getName()).build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(DataTruncationException.class.getName()).build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(DeadlockTimeoutRollbackMarker.class.getName())
.build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(FeatureNotAvailableException.class.getName())
.build());
reflectiveClass
.produce(ReflectiveClassBuildItem.builder(InvalidConnectionAttributeException.class.getName())
.build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(NumberOutOfRange.class.getName()).build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(OperationCancelledException.class.getName())
.build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(PasswordExpiredException.class.getName())
.build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(PropertyNotModifiableException.class.getName())
.build());
reflectiveClass
.produce(ReflectiveClassBuildItem.builder(RSAException.class.getName()).build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(SSLParamsException.class.getName()).build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(StatementIsClosedException.class.getName())
.build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(StreamingNotifiable.class.getName()).build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(UnableToConnectException.class.getName())
.build());
reflectiveClass
.produce(ReflectiveClassBuildItem.builder(UnsupportedConnectionStringException.class.getName())
.build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(WrongArgumentException.class.getName()).build());
reflectiveClass.produce(
ReflectiveClassBuildItem.builder("com.mysql.cj.jdbc.MysqlXAException").methods().fields().build());
reflectiveClass
.produce(ReflectiveClassBuildItem.builder(StandardLoadBalanceExceptionChecker.class.getName())
.build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder(NdbLoadBalanceExceptionChecker.class.getName())
.build());
}
}
| MySQLJDBCReflections |
java | elastic__elasticsearch | modules/data-streams/src/internalClusterTest/java/org/elasticsearch/datastreams/LazyRolloverDuringDisruptionIT.java | {
"start": 1895,
"end": 6645
} | class ____ extends ESIntegTestCase {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return List.of(DataStreamsPlugin.class);
}
public void testRolloverIsExecutedOnce() throws ExecutionException, InterruptedException {
internalCluster().startMasterOnlyNode();
internalCluster().startDataOnlyNodes(3);
ensureStableCluster(4);
String dataStreamName = "my-data-stream";
createDataStream(dataStreamName);
// Mark it to lazy rollover
safeGet(new RolloverRequestBuilder(client()).setRolloverTarget(dataStreamName).lazy(true).execute());
// Verify that the data stream is marked for rollover and that it has currently one index
DataStream dataStream = getDataStream(dataStreamName);
assertThat(dataStream.rolloverOnWrite(), equalTo(true));
assertThat(dataStream.getDataComponent().getIndices().size(), equalTo(1));
// Introduce a disruption to the master node that should delay the rollover execution
final var barrier = new CyclicBarrier(2);
internalCluster().getCurrentMasterNodeInstance(ClusterService.class)
.submitUnbatchedStateUpdateTask("block", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
safeAwait(barrier);
safeAwait(barrier);
return currentState;
}
@Override
public void onFailure(Exception e) {
fail(e);
}
});
safeAwait(barrier);
// Start indexing operations
int docs = randomIntBetween(5, 10);
CountDownLatch countDownLatch = new CountDownLatch(docs);
for (int i = 0; i < docs; i++) {
var indexRequest = new IndexRequest(dataStreamName).opType(DocWriteRequest.OpType.CREATE);
final String doc = "{ \"@timestamp\": \"2099-05-06T16:21:15.000Z\", \"message\": \"something cool happened\" }";
indexRequest.source(doc, XContentType.JSON);
client().index(indexRequest, new ActionListener<>() {
@Override
public void onResponse(DocWriteResponse docWriteResponse) {
countDownLatch.countDown();
}
@Override
public void onFailure(Exception e) {
fail("Indexing request should have succeeded eventually, failed with " + e.getMessage());
}
});
}
// End the disruption so that all pending tasks will complete
safeAwait(barrier);
// Wait for all the indexing requests to be processed successfully
safeAwait(countDownLatch);
// Verify that the rollover has happened once
dataStream = getDataStream(dataStreamName);
assertThat(dataStream.rolloverOnWrite(), equalTo(false));
assertThat(dataStream.getDataComponent().getIndices().size(), equalTo(2));
}
private DataStream getDataStream(String dataStreamName) {
return safeGet(
client().execute(
GetDataStreamAction.INSTANCE,
new GetDataStreamAction.Request(TEST_REQUEST_TIMEOUT, new String[] { dataStreamName })
)
).getDataStreams().get(0).getDataStream();
}
private void createDataStream(String dataStreamName) throws InterruptedException, ExecutionException {
final TransportPutComposableIndexTemplateAction.Request putComposableTemplateRequest =
new TransportPutComposableIndexTemplateAction.Request("my-template");
putComposableTemplateRequest.indexTemplate(
ComposableIndexTemplate.builder()
.indexPatterns(List.of(dataStreamName))
.dataStreamTemplate(new ComposableIndexTemplate.DataStreamTemplate(false, false))
.build()
);
final AcknowledgedResponse putComposableTemplateResponse = safeGet(
client().execute(TransportPutComposableIndexTemplateAction.TYPE, putComposableTemplateRequest)
);
assertThat(putComposableTemplateResponse.isAcknowledged(), is(true));
final CreateDataStreamAction.Request createDataStreamRequest = new CreateDataStreamAction.Request(
TEST_REQUEST_TIMEOUT,
TEST_REQUEST_TIMEOUT,
dataStreamName
);
final AcknowledgedResponse createDataStreamResponse = safeGet(
client().execute(CreateDataStreamAction.INSTANCE, createDataStreamRequest)
);
assertThat(createDataStreamResponse.isAcknowledged(), is(true));
}
}
| LazyRolloverDuringDisruptionIT |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/testkit/TypeCanonizerTest.java | {
"start": 1238,
"end": 6540
} | class ____ {
public static <T> Asssert<T> m(List<? extends T> in) {
return null;
}
public static <T> Asssert<T> mSame(List<? extends T> in) {
return null;
}
public static <T> Asssert<? extends T> mExtends(List<? extends T> in) {
return null;
}
public static <ELEMENT> Asssert<? extends ELEMENT> mExtendsElement(List<? extends ELEMENT> in) {
return null;
}
public static <T> Asssert<? super T> mSuper(List<? extends T> in) {
return null;
}
public static <ELEMENT> Asssert<? super ELEMENT> mSuperElement(List<? extends ELEMENT> in) {
return null;
}
public static <T> AbstractListAssert<?, List<? extends T>, T, ObjectAssert<T>> complex1(List<? extends T> in) {
return null;
}
public static <T> AbstractListAssert<?, List<? extends T>, T, ObjectAssert<T>> complex2(List<? extends T> in) {
return null;
}
public static <T extends AssertDelegateTarget> T returnsT(T assertion) {
return null;
}
public static <T extends AssertDelegateTarget> T returnsT2(T assertion) {
return null;
}
public static <K, V> MapAssert<K, V> doubleTypeVariables(Map<K, V> actual) {
return null;
}
public static <K, V> MapAssert<K, V> doubleTypeVariables2(Map<K, V> actual) {
return null;
}
public static <ELEMENT> ListAssert<ELEMENT> listAssert(List<? extends ELEMENT> actual) {
return null;
}
public static <T> ListAssert<T> listAssert2(List<? extends T> actual) {
return null;
}
public static <T> T[] genericArray(T[] actual) {
return null;
}
public static <ELEMENT> ELEMENT[] genericArray2(ELEMENT[] actual) {
return null;
}
public static <T> T[][] doubleGenericArray(T[] actual) {
return null;
}
public static <ELEMENT> ELEMENT[][] doubleGenericArray2(ELEMENT[] actual) {
return null;
}
}
@Test
void T_and_T_are_equals() {
Type m = resolveGenericReturnType(Api.class, "m");
Type mSame = resolveGenericReturnType(Api.class, "mSame");
assertThat(m).isEqualTo(mSame);
}
@Test
void T_and_QUESTION_MARK_extends_T_are_not_equals() {
assertThat(resolveGenericReturnType(Api.class, "m"))
.isNotEqualTo(resolveGenericReturnType(Api.class, "mExtends"));
}
@Test
void QUESTION_MARK_extends_T_and_QUESTION_MARK_extends_ELEMENT_are_equal() {
assertThat(resolveGenericReturnType(Api.class, "mExtends"))
.isEqualTo(resolveGenericReturnType(Api.class, "mExtendsElement"));
}
@Test
void QUESTION_MARK_super_T_and_QUESTION_MARK_super_ELEMENT_are_equal() {
assertThat(resolveGenericReturnType(Api.class, "mSuper"))
.isEqualTo(resolveGenericReturnType(Api.class, "mSuperElement"));
}
@Test
void T_and_QUESTION_MARK_super_T_are_not_equals() {
assertThat(resolveGenericReturnType(Api.class, "m"))
.isNotEqualTo(resolveGenericReturnType(Api.class, "mSuper"));
}
@Test
void T_extends_something_returns_T_are_equal() {
assertThat(resolveGenericReturnType(Api.class, "returnsT"))
.isEqualTo(resolveGenericReturnType(Api.class, "returnsT2"));
}
@Test
void list_asserts_are_equal() {
assertThat(resolveGenericReturnType(Api.class, "listAssert"))
.isEqualTo(resolveGenericReturnType(Api.class, "listAssert2"));
}
@Test
void K_and_V_and_K_and_V_are_equal() {
assertThat(resolveGenericReturnType(Api.class, "doubleTypeVariables"))
.isEqualTo(resolveGenericReturnType(Api.class,
"doubleTypeVariables2"));
}
@Test
void generic_array_T_and_generic_array_ELEMENT_are_equal() {
assertThat(resolveGenericReturnType(Api.class, "genericArray"))
.isEqualTo(resolveGenericReturnType(Api.class,
"genericArray2"));
}
@Test
void double_generic_array_T_and_double_generic_array_ELEMENT_are_equal() {
assertThat(resolveGenericReturnType(Api.class, "doubleGenericArray"))
.isEqualTo(resolveGenericReturnType(Api.class,
"doubleGenericArray2"));
}
private static Type resolveGenericReturnType(Class<?> cls, String methodName) {
return Arrays.stream(cls.getMethods())
.filter(method -> method.getName().equals(methodName))
.map(method -> TypeCanonizer.canonize(method.getGenericReturnType()))
.findAny()
.orElseThrow(() -> new RuntimeException("Method not found: class=" + cls + " name=" + methodName));
}
}
| Api |
java | apache__maven | impl/maven-impl/src/main/java/org/apache/maven/impl/util/PhasingExecutor.java | {
"start": 2192,
"end": 6788
} | class ____ implements Executor, AutoCloseable {
private static final AtomicInteger ID = new AtomicInteger(0);
private static final Logger LOGGER = LoggerFactory.getLogger(PhasingExecutor.class);
private final ExecutorService executor;
private final AtomicBoolean shutdownInitiated = new AtomicBoolean(false);
private final AtomicBoolean inPhase = new AtomicBoolean(false);
private final AtomicInteger activeTaskCount = new AtomicInteger(0);
private final AtomicInteger completedTaskCount = new AtomicInteger(0);
private final int id = ID.incrementAndGet();
private final ReentrantLock lock = new ReentrantLock();
private final Condition taskCompletionCondition = lock.newCondition();
public PhasingExecutor(ExecutorService executor) {
this.executor = executor;
log("[{}][general] PhasingExecutor created.");
}
@Override
public void execute(Runnable command) {
activeTaskCount.incrementAndGet();
log("[{}][task] Task submitted. Active tasks: {}", activeTaskCount.get());
executor.execute(() -> {
try {
log("[{}][task] Task executing. Active tasks: {}", activeTaskCount.get());
command.run();
} finally {
lock.lock();
try {
completedTaskCount.incrementAndGet();
activeTaskCount.decrementAndGet();
log("[{}][task] Task completed. Active tasks: {}", activeTaskCount.get());
taskCompletionCondition.signalAll();
if (activeTaskCount.get() == 0 && shutdownInitiated.get()) {
log("[{}][task] Last task completed. Initiating executor shutdown.");
executor.shutdown();
}
} finally {
lock.unlock();
}
}
});
}
public AutoCloseable phase() {
if (inPhase.getAndSet(true)) {
throw new IllegalStateException("Already in a phase");
}
int phaseNumber = completedTaskCount.get();
log("[{}][phase] Entering phase {}. Active tasks: {}", phaseNumber, activeTaskCount.get());
return () -> {
try {
int tasksAtPhaseStart = completedTaskCount.get();
log("[{}][phase] Closing phase {}. Waiting for all tasks to complete.", phaseNumber);
lock.lock();
try {
while (activeTaskCount.get() > 0
&& completedTaskCount.get() - tasksAtPhaseStart < activeTaskCount.get()) {
taskCompletionCondition.await(100, TimeUnit.MILLISECONDS);
}
} finally {
lock.unlock();
}
log("[{}][phase] Phase {} completed. Total completed tasks: {}", phaseNumber, completedTaskCount.get());
} catch (InterruptedException e) {
log("[{}][phase] Phase {} was interrupted.", phaseNumber);
Thread.currentThread().interrupt();
throw new RuntimeException("Phase interrupted", e);
} finally {
inPhase.set(false);
}
};
}
@Override
public void close() {
log("[{}][close] Closing PhasingExecutor. Active tasks: {}", activeTaskCount.get());
if (shutdownInitiated.getAndSet(true)) {
log("[{}][close] Shutdown already initiated. Returning.");
return;
}
lock.lock();
try {
while (activeTaskCount.get() > 0) {
log("[{}][close] Waiting for {} active tasks to complete.", activeTaskCount.get());
taskCompletionCondition.await(100, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e) {
log("[{}][close] Interrupted while waiting for tasks to complete.");
Thread.currentThread().interrupt();
} finally {
lock.unlock();
log("[{}][close] All tasks completed. Shutting down executor.");
executor.shutdown();
}
log("[{}][close] PhasingExecutor closed. Total completed tasks: {}", completedTaskCount.get());
}
private void log(String message) {
LOGGER.debug(message, id);
}
private void log(String message, Object o1) {
LOGGER.debug(message, id, o1);
}
private void log(String message, Object o1, Object o2) {
LOGGER.debug(message, id, o1, o2);
}
}
| PhasingExecutor |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/SmartLifecycle.java | {
"start": 709,
"end": 1328
} | interface ____ those objects that require
* to be started upon {@code ApplicationContext} refresh and/or shutdown in a
* particular order.
*
* <p>The {@link #isAutoStartup()} return value indicates whether this object should
* be started at the time of a context refresh. The callback-accepting
* {@link #stop(Runnable)} method is useful for objects that have an asynchronous
* shutdown process. Any implementation of this interface <i>must</i> invoke the
* callback's {@code run()} method upon shutdown completion to avoid unnecessary
* delays in the overall {@code ApplicationContext} shutdown.
*
* <p>This | for |
java | spring-projects__spring-security | messaging/src/test/java/org/springframework/security/messaging/util/matcher/OrMessageMatcherTests.java | {
"start": 1283,
"end": 3774
} | class ____ {
@Mock
private MessageMatcher<Object> delegate;
@Mock
private MessageMatcher<Object> delegate2;
@Mock
private Message<Object> message;
private MessageMatcher<Object> matcher;
@Test
public void constructorNullArray() {
assertThatNullPointerException().isThrownBy(() -> new OrMessageMatcher<>((MessageMatcher<Object>[]) null));
}
@Test
public void constructorArrayContainsNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new OrMessageMatcher<>((MessageMatcher<Object>) null));
}
@Test
@SuppressWarnings("unchecked")
public void constructorEmptyArray() {
assertThatIllegalArgumentException().isThrownBy(() -> new OrMessageMatcher<>(new MessageMatcher[0]));
}
@Test
public void constructorNullList() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OrMessageMatcher<>((List<MessageMatcher<Object>>) null));
}
@Test
public void constructorListContainsNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OrMessageMatcher<>(Arrays.asList((MessageMatcher<Object>) null)));
}
@Test
public void constructorEmptyList() {
assertThatIllegalArgumentException().isThrownBy(() -> new OrMessageMatcher<>(Collections.emptyList()));
}
@Test
public void matchesSingleTrue() {
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new OrMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isTrue();
}
@Test
public void matchesMultiTrue() {
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
@Test
public void matchesSingleFalse() {
given(this.delegate.matches(this.message)).willReturn(false);
this.matcher = new OrMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isFalse();
}
@Test
public void matchesMultiBothFalse() {
given(this.delegate.matches(this.message)).willReturn(false);
given(this.delegate2.matches(this.message)).willReturn(false);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
@Test
public void matchesMultiSingleFalse() {
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
}
| OrMessageMatcherTests |
java | google__guice | core/src/com/google/inject/spi/TypeEncounter.java | {
"start": 1280,
"end": 4810
} | interface ____<I> {
/**
* Records an error message for type {@code I} which will be presented to the user at a later
* time. Unlike throwing an exception, this enable us to continue configuring the Injector and
* discover more errors. Uses {@link String#format(String, Object[])} to insert the arguments into
* the message.
*/
void addError(String message, Object... arguments);
/**
* Records an exception for type {@code I}, the full details of which will be logged, and the
* message of which will be presented to the user at a later time. If your type listener calls
* something that you worry may fail, you should catch the exception and pass it to this method.
*/
void addError(Throwable t);
/** Records an error message to be presented to the user at a later time. */
void addError(Message message);
/**
* Returns the provider used to obtain instances for the given injection key. The returned
* provider will not be valid until the injector has been created. The provider will throw an
* {@code IllegalStateException} if you try to use it beforehand.
*/
<T> Provider<T> getProvider(Key<T> key);
/**
* Returns the provider used to obtain instances for the given injection type. The returned
* provider will not be valid until the injector has been created. The provider will throw an
* {@code IllegalStateException} if you try to use it beforehand.
*/
<T> Provider<T> getProvider(Class<T> type);
/**
* Returns the members injector used to inject dependencies into methods and fields on instances
* of the given type {@code T}. The returned members injector will not be valid until the main
* injector has been created. The members injector will throw an {@code IllegalStateException} if
* you try to use it beforehand.
*
* @param typeLiteral type to get members injector for
*/
<T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral);
/**
* Returns the members injector used to inject dependencies into methods and fields on instances
* of the given type {@code T}. The returned members injector will not be valid until the main
* injector has been created. The members injector will throw an {@code IllegalStateException} if
* you try to use it beforehand.
*
* @param type type to get members injector for
*/
<T> MembersInjector<T> getMembersInjector(Class<T> type);
/**
* Registers a members injector for type {@code I}. Guice will use the members injector after its
* performed its own injections on an instance of {@code I}.
*/
void register(MembersInjector<? super I> membersInjector);
/**
* Registers an injection listener for type {@code I}. Guice will notify the listener after all
* injections have been performed on an instance of {@code I}.
*/
void register(InjectionListener<? super I> listener);
/**
* Binds method interceptor[s] to methods matched in type {@code I} and its supertypes. A method
* is eligible for interception if:
*
* <ul>
* <li>Guice created the instance the method is on
* <li>Neither the enclosing type nor the method is final
* <li>And the method is package-private or more accessible
* </ul>
*
* @param methodMatcher matches methods the interceptor should apply to. For example: {@code
* annotatedWith(Transactional.class)}.
* @param interceptors to bind
*/
void bindInterceptor(Matcher<? super Method> methodMatcher, MethodInterceptor... interceptors);
}
| TypeEncounter |
java | apache__flink | flink-core/src/main/java/org/apache/flink/types/LongValue.java | {
"start": 1195,
"end": 4911
} | class ____
implements NormalizableKey<LongValue>,
ResettableValue<LongValue>,
CopyableValue<LongValue> {
private static final long serialVersionUID = 1L;
private long value;
/** Initializes the encapsulated long with 0. */
public LongValue() {
this.value = 0;
}
/**
* Initializes the encapsulated long with the specified value.
*
* @param value Initial value of the encapsulated long.
*/
public LongValue(final long value) {
this.value = value;
}
/**
* Returns the value of the encapsulated long.
*
* @return The value of the encapsulated long.
*/
public long getValue() {
return this.value;
}
/**
* Sets the value of the encapsulated long to the specified value.
*
* @param value The new value of the encapsulated long.
*/
public void setValue(final long value) {
this.value = value;
}
@Override
public void setValue(LongValue value) {
this.value = value.value;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.valueOf(this.value);
}
// --------------------------------------------------------------------------------------------
@Override
public void read(final DataInputView in) throws IOException {
this.value = in.readLong();
}
@Override
public void write(final DataOutputView out) throws IOException {
out.writeLong(this.value);
}
// --------------------------------------------------------------------------------------------
@Override
public int compareTo(LongValue o) {
final long other = o.value;
return this.value < other ? -1 : this.value > other ? 1 : 0;
}
@Override
public int hashCode() {
return 43 + (int) (this.value ^ this.value >>> 32);
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj instanceof LongValue) {
return ((LongValue) obj).value == this.value;
}
return false;
}
// --------------------------------------------------------------------------------------------
@Override
public int getMaxNormalizedKeyLen() {
return 8;
}
@Override
public void copyNormalizedKey(MemorySegment target, int offset, int len) {
// see IntValue for an explanation of the logic
if (len == 8) {
// default case, full normalized key
target.putLongBigEndian(offset, value - Long.MIN_VALUE);
} else if (len <= 0) {
} else if (len < 8) {
long value = this.value - Long.MIN_VALUE;
for (int i = 0; len > 0; len--, i++) {
target.put(offset + i, (byte) (value >>> ((7 - i) << 3)));
}
} else {
target.putLongBigEndian(offset, value - Long.MIN_VALUE);
for (int i = 8; i < len; i++) {
target.put(offset + i, (byte) 0);
}
}
}
// --------------------------------------------------------------------------------------------
@Override
public int getBinaryLength() {
return 8;
}
@Override
public void copyTo(LongValue target) {
target.value = this.value;
}
@Override
public LongValue copy() {
return new LongValue(this.value);
}
@Override
public void copy(DataInputView source, DataOutputView target) throws IOException {
target.write(source, 8);
}
}
| LongValue |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/SealedTypesWithJsonTypeInfoSimpleClassName4061Test.java | {
"start": 1719,
"end": 1798
} | class ____ extends MinimalInnerSuper4061 {
}
static final | MinimalInnerSub4061A |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/aggfunctions/LastValueWithRetractAggFunctionWithOrderTest.java | {
"start": 12575,
"end": 13836
} | class ____<T>
extends LastValueWithRetractAggFunctionWithOrderTestBase<T> {
protected abstract T getValue(String v);
@Override
protected List<List<T>> getInputValueSets() {
return Arrays.asList(
Arrays.asList(
getValue("1"),
null,
getValue("-99"),
getValue("3"),
null,
getValue("3"),
getValue("2"),
getValue("-99")),
Arrays.asList(null, null, null, null),
Arrays.asList(null, getValue("10"), null, getValue("5")));
}
@Override
protected List<List<Long>> getInputOrderSets() {
return Arrays.asList(
Arrays.asList(10L, 2L, 5L, 6L, 11L, 13L, 7L, 5L),
Arrays.asList(8L, 6L, 9L, 5L),
Arrays.asList(null, 6L, 4L, 3L));
}
@Override
protected List<T> getExpectedResults() {
return Arrays.asList(getValue("3"), null, getValue("10"));
}
}
}
| NumberLastValueWithRetractAggFunctionWithOrderTestBase |
java | jhy__jsoup | src/main/java/org/jsoup/select/Elements.java | {
"start": 6064,
"end": 23660
} | class ____ to check for
@return true if any do, false if none do
*/
public boolean hasClass(String className) {
for (Element element : this) {
if (element.hasClass(className))
return true;
}
return false;
}
/**
* Get the form element's value of the first matched element.
* @return The form element's value, or empty if not set.
* @see Element#val()
*/
public String val() {
if (size() > 0)
//noinspection ConstantConditions
return first().val(); // first() != null as size() > 0
else
return "";
}
/**
* Set the form element's value in each of the matched elements.
* @param value The value to set into each matched element
* @return this (for chaining)
*/
public Elements val(String value) {
for (Element element : this)
element.val(value);
return this;
}
/**
* Get the combined text of all the matched elements.
* <p>
* Note that it is possible to get repeats if the matched elements contain both parent elements and their own
* children, as the Element.text() method returns the combined text of a parent and all its children.
* @return string of all text: unescaped and no HTML.
* @see Element#text()
* @see #eachText()
*/
public String text() {
return stream()
.map(Element::text)
.collect(StringUtil.joining(" "));
}
/**
Test if any matched Element has any text content, that is not just whitespace.
@return true if any element has non-blank text content.
@see Element#hasText()
*/
public boolean hasText() {
for (Element element: this) {
if (element.hasText())
return true;
}
return false;
}
/**
* Get the text content of each of the matched elements. If an element has no text, then it is not included in the
* result.
* @return A list of each matched element's text content.
* @see Element#text()
* @see Element#hasText()
* @see #text()
*/
public List<String> eachText() {
ArrayList<String> texts = new ArrayList<>(size());
for (Element el: this) {
if (el.hasText())
texts.add(el.text());
}
return texts;
}
/**
* Get the combined inner HTML of all matched elements.
* @return string of all element's inner HTML.
* @see #text()
* @see #outerHtml()
*/
public String html() {
return stream()
.map(Element::html)
.collect(StringUtil.joining("\n"));
}
/**
* Update (rename) the tag name of each matched element. For example, to change each {@code <i>} to a {@code <em>}, do
* {@code doc.select("i").tagName("em");}
*
* @param tagName the new tag name
* @return this, for chaining
* @see Element#tagName(String)
*/
public Elements tagName(String tagName) {
for (Element element : this) {
element.tagName(tagName);
}
return this;
}
/**
* Set the inner HTML of each matched element.
* @param html HTML to parse and set into each matched element.
* @return this, for chaining
* @see Element#html(String)
*/
public Elements html(String html) {
for (Element element : this) {
element.html(html);
}
return this;
}
/**
* Add the supplied HTML to the start of each matched element's inner HTML.
* @param html HTML to add inside each element, before the existing HTML
* @return this, for chaining
* @see Element#prepend(String)
*/
public Elements prepend(String html) {
for (Element element : this) {
element.prepend(html);
}
return this;
}
/**
* Add the supplied HTML to the end of each matched element's inner HTML.
* @param html HTML to add inside each element, after the existing HTML
* @return this, for chaining
* @see Element#append(String)
*/
public Elements append(String html) {
for (Element element : this) {
element.append(html);
}
return this;
}
/**
Insert the supplied HTML before each matched element's outer HTML.
@param html HTML to insert before each element
@return this, for chaining
@see Element#before(String)
*/
@Override
public Elements before(String html) {
super.before(html);
return this;
}
/**
Insert the supplied HTML after each matched element's outer HTML.
@param html HTML to insert after each element
@return this, for chaining
@see Element#after(String)
*/
@Override
public Elements after(String html) {
super.after(html);
return this;
}
/**
Wrap the supplied HTML around each matched elements. For example, with HTML
{@code <p><b>This</b> is <b>Jsoup</b></p>},
<code>doc.select("b").wrap("<i></i>");</code>
becomes {@code <p><i><b>This</b></i> is <i><b>jsoup</b></i></p>}
@param html HTML to wrap around each element, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep.
@return this (for chaining)
@see Element#wrap
*/
@Override
public Elements wrap(String html) {
super.wrap(html);
return this;
}
/**
* Removes the matched elements from the DOM, and moves their children up into their parents. This has the effect of
* dropping the elements but keeping their children.
* <p>
* This is useful for e.g removing unwanted formatting elements but keeping their contents.
* </p>
*
* E.g. with HTML: <p>{@code <div><font>One</font> <font><a href="/">Two</a></font></div>}</p>
* <p>{@code doc.select("font").unwrap();}</p>
* <p>HTML = {@code <div>One <a href="/">Two</a></div>}</p>
*
* @return this (for chaining)
* @see Node#unwrap
*/
public Elements unwrap() {
for (Element element : this) {
element.unwrap();
}
return this;
}
/**
* Empty (remove all child nodes from) each matched element. This is similar to setting the inner HTML of each
* element to nothing.
* <p>
* E.g. HTML: {@code <div><p>Hello <b>there</b></p> <p>now</p></div>}<br>
* <code>doc.select("p").empty();</code><br>
* HTML = {@code <div><p></p> <p></p></div>}
* @return this, for chaining
* @see Element#empty()
* @see #remove()
*/
public Elements empty() {
for (Element element : this) {
element.empty();
}
return this;
}
/**
* Remove each matched element from the DOM. This is similar to setting the outer HTML of each element to nothing.
* <p>The elements will still be retained in this list, in case further processing of them is desired.</p>
* <p>
* E.g. HTML: {@code <div><p>Hello</p> <p>there</p> <img /></div>}<br>
* <code>doc.select("p").remove();</code><br>
* HTML = {@code <div> <img /></div>}
* <p>
* Note that this method should not be used to clean user-submitted HTML; rather, use {@link org.jsoup.safety.Cleaner} to clean HTML.
* @return this, for chaining
* @see Element#empty()
* @see #empty()
* @see #clear()
*/
@Override
public Elements remove() {
super.remove();
return this;
}
// filters
/**
* Find matching elements within this element list.
* @param query A {@link Selector} query
* @return the filtered list of elements, or an empty list if none match.
*/
public Elements select(String query) {
return Selector.select(query, this);
}
/**
Find the first Element that matches the {@link Selector} CSS query within this element list.
<p>This is effectively the same as calling {@code elements.select(query).first()}, but is more efficient as query
execution stops on the first hit.</p>
@param cssQuery a {@link Selector} query
@return the first matching element, or <b>{@code null}</b> if there is no match.
@see #expectFirst(String)
@since 1.19.1
*/
public @Nullable Element selectFirst(String cssQuery) {
return Selector.selectFirst(cssQuery, this);
}
/**
Just like {@link #selectFirst(String)}, but if there is no match, throws an {@link IllegalArgumentException}.
@param cssQuery a {@link Selector} query
@return the first matching element
@throws IllegalArgumentException if no match is found
@since 1.19.1
*/
public Element expectFirst(String cssQuery) {
return Validate.expectNotNull(
Selector.selectFirst(cssQuery, this),
"No elements matched the query '%s' in the elements.", cssQuery
);
}
/**
* Remove elements from this list that match the {@link Selector} query.
* <p>
* E.g. HTML: {@code <div class=logo>One</div> <div>Two</div>}<br>
* <code>Elements divs = doc.select("div").not(".logo");</code><br>
* Result: {@code divs: [<div>Two</div>]}
* <p>
* @param query the selector query whose results should be removed from these elements
* @return a new elements list that contains only the filtered results
*/
public Elements not(String query) {
Elements out = Selector.select(query, this);
return Selector.filterOut(this, out);
}
/**
* Get the <i>nth</i> matched element as an Elements object.
* <p>
* See also {@link #get(int)} to retrieve an Element.
* @param index the (zero-based) index of the element in the list to retain
* @return Elements containing only the specified element, or, if that element did not exist, an empty list.
*/
public Elements eq(int index) {
return size() > index ? new Elements(get(index)) : new Elements();
}
/**
* Test if any of the matched elements match the supplied query.
* @param query A selector
* @return true if at least one element in the list matches the query.
*/
public boolean is(String query) {
Evaluator eval = Selector.evaluatorOf(query);
for (Element e : this) {
if (e.is(eval))
return true;
}
return false;
}
/**
* Get the immediate next element sibling of each element in this list.
* @return next element siblings.
*/
public Elements next() {
return siblings(null, true, false);
}
/**
* Get the immediate next element sibling of each element in this list, filtered by the query.
* @param query CSS query to match siblings against
* @return next element siblings.
*/
public Elements next(String query) {
return siblings(query, true, false);
}
/**
* Get each of the following element siblings of each element in this list.
* @return all following element siblings.
*/
public Elements nextAll() {
return siblings(null, true, true);
}
/**
* Get each of the following element siblings of each element in this list, that match the query.
* @param query CSS query to match siblings against
* @return all following element siblings.
*/
public Elements nextAll(String query) {
return siblings(query, true, true);
}
/**
* Get the immediate previous element sibling of each element in this list.
* @return previous element siblings.
*/
public Elements prev() {
return siblings(null, false, false);
}
/**
* Get the immediate previous element sibling of each element in this list, filtered by the query.
* @param query CSS query to match siblings against
* @return previous element siblings.
*/
public Elements prev(String query) {
return siblings(query, false, false);
}
/**
* Get each of the previous element siblings of each element in this list.
* @return all previous element siblings.
*/
public Elements prevAll() {
return siblings(null, false, true);
}
/**
* Get each of the previous element siblings of each element in this list, that match the query.
* @param query CSS query to match siblings against
* @return all previous element siblings.
*/
public Elements prevAll(String query) {
return siblings(query, false, true);
}
private Elements siblings(@Nullable String query, boolean next, boolean all) {
Elements els = new Elements();
Evaluator eval = query != null? Selector.evaluatorOf(query) : null;
for (Element e : this) {
do {
Element sib = next ? e.nextElementSibling() : e.previousElementSibling();
if (sib == null) break;
if (eval == null || sib.is(eval)) els.add(sib);
e = sib;
} while (all);
}
return els;
}
/**
* Get all of the parents and ancestor elements of the matched elements.
* @return all of the parents and ancestor elements of the matched elements
*/
public Elements parents() {
HashSet<Element> combo = new LinkedHashSet<>();
for (Element e: this) {
combo.addAll(e.parents());
}
return new Elements(combo);
}
// list-like methods
/**
Get the first matched element.
@return The first matched element, or <code>null</code> if contents is empty.
*/
@Override
public @Nullable Element first() {
return super.first();
}
/**
Get the last matched element.
@return The last matched element, or <code>null</code> if contents is empty.
*/
@Override
public @Nullable Element last() {
return super.last();
}
/**
* Perform a depth-first traversal on each of the selected elements.
* @param nodeVisitor the visitor callbacks to perform on each node
* @return this, for chaining
*/
public Elements traverse(NodeVisitor nodeVisitor) {
NodeTraversor.traverse(nodeVisitor, this);
return this;
}
/**
* Perform a depth-first filtering on each of the selected elements.
* @param nodeFilter the filter callbacks to perform on each node
* @return this, for chaining
*/
public Elements filter(NodeFilter nodeFilter) {
NodeTraversor.filter(nodeFilter, this);
return this;
}
/**
* Get the {@link FormElement} forms from the selected elements, if any.
* @return a list of {@link FormElement}s pulled from the matched elements. The list will be empty if the elements contain
* no forms.
*/
public List<FormElement> forms() {
ArrayList<FormElement> forms = new ArrayList<>();
for (Element el: this)
if (el instanceof FormElement)
forms.add((FormElement) el);
return forms;
}
/**
* Get {@link Comment} nodes that are direct child nodes of the selected elements.
* @return Comment nodes, or an empty list if none.
*/
public List<Comment> comments() {
return childNodesOfType(Comment.class);
}
/**
* Get {@link TextNode} nodes that are direct child nodes of the selected elements.
* @return TextNode nodes, or an empty list if none.
*/
public List<TextNode> textNodes() {
return childNodesOfType(TextNode.class);
}
/**
* Get {@link DataNode} nodes that are direct child nodes of the selected elements. DataNode nodes contain the
* content of tags such as {@code script}, {@code style} etc and are distinct from {@link TextNode}s.
* @return Comment nodes, or an empty list if none.
*/
public List<DataNode> dataNodes() {
return childNodesOfType(DataNode.class);
}
private <T extends Node> List<T> childNodesOfType(Class<T> tClass) {
ArrayList<T> nodes = new ArrayList<>();
for (Element el: this) {
for (int i = 0; i < el.childNodeSize(); i++) {
Node node = el.childNode(i);
if (tClass.isInstance(node))
nodes.add(tClass.cast(node));
}
}
return nodes;
}
// list methods that update the DOM:
/**
Replace the Element at the specified index in this list, and in the DOM.
@param index index of the element to replace
@param element element to be stored at the specified position
@return the old Element at this index
@since 1.17.1
*/
@Override
public Element set(int index, Element element) {
return super.set(index, element);
}
/**
Remove the Element at the specified index in this ist, and from the DOM.
@param index the index of the element to be removed
@return the old element at this index
@see #deselect(int)
@since 1.17.1
*/
@Override
public Element remove(int index) {
return super.remove(index);
}
/**
Remove the Element at the specified index in this list, but not from the DOM.
@param index the index of the element to be removed
@return the old element at this index
@see #remove(int)
@since 1.19.2
*/
@Override
public Element deselect(int index) {
return super.deselect(index);
}
}
| name |
java | square__retrofit | retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/FlowableTest.java | {
"start": 1264,
"end": 5443
} | interface ____ {
@GET("/")
Flowable<String> body();
@GET("/")
Flowable<Response<String>> response();
@GET("/")
Flowable<Result<String>> result();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodySuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
RecordingSubscriber<String> subscriber = subscriberRule.create();
service.body().subscribe(subscriber);
subscriber.assertValue("Hi").assertComplete();
}
@Test
public void bodySuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingSubscriber<String> subscriber = subscriberRule.create();
service.body().subscribe(subscriber);
// Required for backwards compatibility.
subscriber.assertError(HttpException.class, "HTTP 404 Client Error");
}
@Test
public void bodyFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingSubscriber<String> subscriber = subscriberRule.create();
service.body().subscribe(subscriber);
subscriber.assertError(IOException.class);
}
@Test
public void responseSuccess200() {
server.enqueue(new MockResponse());
RecordingSubscriber<Response<String>> subscriber = subscriberRule.create();
service.response().subscribe(subscriber);
assertThat(subscriber.takeValue().isSuccessful()).isTrue();
subscriber.assertComplete();
}
@Test
public void responseSuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingSubscriber<Response<String>> subscriber = subscriberRule.create();
service.response().subscribe(subscriber);
assertThat(subscriber.takeValue().isSuccessful()).isFalse();
subscriber.assertComplete();
}
@Test
public void responseFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingSubscriber<Response<String>> subscriber = subscriberRule.create();
service.response().subscribe(subscriber);
subscriber.assertError(IOException.class);
}
@Test
public void resultSuccess200() {
server.enqueue(new MockResponse());
RecordingSubscriber<Result<String>> subscriber = subscriberRule.create();
service.result().subscribe(subscriber);
Result<String> result = subscriber.takeValue();
assertThat(result.isError()).isFalse();
assertThat(result.response().isSuccessful()).isTrue();
subscriber.assertComplete();
}
@Test
public void resultSuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingSubscriber<Result<String>> subscriber = subscriberRule.create();
service.result().subscribe(subscriber);
Result<String> result = subscriber.takeValue();
assertThat(result.isError()).isFalse();
assertThat(result.response().isSuccessful()).isFalse();
subscriber.assertComplete();
}
@Test
public void resultFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingSubscriber<Result<String>> subscriber = subscriberRule.create();
service.result().subscribe(subscriber);
Result<String> result = subscriber.takeValue();
assertThat(result.isError()).isTrue();
assertThat(result.error()).isInstanceOf(IOException.class);
subscriber.assertComplete();
}
@Test
public void subscribeTwice() {
server.enqueue(new MockResponse().setBody("Hi"));
server.enqueue(new MockResponse().setBody("Hey"));
Flowable<String> observable = service.body();
RecordingSubscriber<Object> subscriber1 = subscriberRule.create();
observable.subscribe(subscriber1);
subscriber1.assertValue("Hi").assertComplete();
RecordingSubscriber<Object> subscriber2 = subscriberRule.create();
observable.subscribe(subscriber2);
subscriber2.assertValue("Hey").assertComplete();
}
}
| Service |
java | apache__flink | flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/history/HistoryServerStaticFileServerHandler.java | {
"start": 4653,
"end": 12827
} | class ____
extends SimpleChannelInboundHandler<RoutedRequest> {
/** Default logger, if none is specified. */
private static final Logger LOG =
LoggerFactory.getLogger(HistoryServerStaticFileServerHandler.class);
// ------------------------------------------------------------------------
/** The path in which the static documents are. */
private final File rootPath;
public HistoryServerStaticFileServerHandler(File rootPath) throws IOException {
this.rootPath = checkNotNull(rootPath).getCanonicalFile();
}
// ------------------------------------------------------------------------
// Responses to requests
// ------------------------------------------------------------------------
@Override
public void channelRead0(ChannelHandlerContext ctx, RoutedRequest routedRequest)
throws Exception {
String requestPath = routedRequest.getPath();
try {
respondWithFile(ctx, routedRequest.getRequest(), requestPath);
} catch (RestHandlerException rhe) {
HandlerUtils.sendErrorResponse(
ctx,
routedRequest.getRequest(),
new ErrorResponseBody(rhe.getMessage()),
rhe.getHttpResponseStatus(),
Collections.emptyMap());
}
}
/** Response when running with leading JobManager. */
private void respondWithFile(ChannelHandlerContext ctx, HttpRequest request, String requestPath)
throws IOException, ParseException, RestHandlerException {
// make sure we request the "index.html" in case there is a directory request
if (requestPath.endsWith("/")) {
requestPath = requestPath + "index.html";
}
if (!requestPath.contains(".")) { // we assume that the path ends in either .html or .js
requestPath = requestPath + ".json";
}
// convert to absolute path
final File file = new File(rootPath, requestPath);
if (!file.exists()) {
// file does not exist. Try to load it with the classloader
ClassLoader cl = HistoryServerStaticFileServerHandler.class.getClassLoader();
try (InputStream resourceStream = cl.getResourceAsStream("web" + requestPath)) {
boolean success = false;
try {
if (resourceStream != null) {
URL root = cl.getResource("web");
URL requested = cl.getResource("web" + requestPath);
if (root != null && requested != null) {
URI rootURI = new URI(root.getPath()).normalize();
URI requestedURI = new URI(requested.getPath()).normalize();
// Check that we don't load anything from outside of the
// expected scope.
if (!rootURI.relativize(requestedURI).equals(requestedURI)) {
LOG.debug("Loading missing file from classloader: {}", requestPath);
// ensure that directory to file exists.
file.getParentFile().mkdirs();
Files.copy(resourceStream, file.toPath());
success = true;
}
}
}
} catch (Throwable t) {
LOG.error("error while responding", t);
} finally {
if (!success) {
LOG.debug("Unable to load requested file {} from classloader", requestPath);
throw new NotFoundException("File not found.");
}
}
}
}
StaticFileServerHandler.checkFileValidity(file, rootPath, LOG);
// cache validation
final String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
SimpleDateFormat dateFormatter =
new SimpleDateFormat(StaticFileServerHandler.HTTP_DATE_FORMAT, Locale.US);
Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
// Only compare up to the second because the datetime format we send to the client
// does not have milliseconds
long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
long fileLastModifiedSeconds = file.lastModified() / 1000;
if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
if (LOG.isDebugEnabled()) {
LOG.debug(
"Responding 'NOT MODIFIED' for file '" + file.getAbsolutePath() + '\'');
}
StaticFileServerHandler.sendNotModified(ctx);
return;
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Responding with file '" + file.getAbsolutePath() + '\'');
}
// Don't need to close this manually. Netty's DefaultFileRegion will take care of it.
final RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "r");
} catch (FileNotFoundException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Could not find file {}.", file.getAbsolutePath());
}
HandlerUtils.sendErrorResponse(
ctx,
request,
new ErrorResponseBody("File not found."),
NOT_FOUND,
Collections.emptyMap());
return;
}
try {
long fileLength = raf.length();
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
StaticFileServerHandler.setContentTypeHeader(response, file);
// the job overview should be updated as soon as possible
if (!requestPath.equals("/joboverview.json")) {
StaticFileServerHandler.setDateAndCacheHeaders(response, file);
}
if (HttpUtil.isKeepAlive(request)) {
response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
}
HttpUtil.setContentLength(response, fileLength);
// write the initial line and the header.
ctx.write(response);
// write the content.
ChannelFuture lastContentFuture;
if (ctx.pipeline().get(SslHandler.class) == null) {
ctx.write(
new DefaultFileRegion(raf.getChannel(), 0, fileLength),
ctx.newProgressivePromise());
lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
} else {
lastContentFuture =
ctx.writeAndFlush(
new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
ctx.newProgressivePromise());
// HttpChunkedInput will write the end marker (LastHttpContent) for us.
}
// close the connection, if no keep-alive is needed
if (!HttpUtil.isKeepAlive(request)) {
lastContentFuture.addListener(ChannelFutureListener.CLOSE);
}
} catch (Exception e) {
raf.close();
LOG.error("Failed to serve file.", e);
throw new RestHandlerException("Internal server error.", INTERNAL_SERVER_ERROR);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
if (ctx.channel().isActive()) {
LOG.error("Caught exception", cause);
HandlerUtils.sendErrorResponse(
ctx,
false,
new ErrorResponseBody("Internal server error."),
INTERNAL_SERVER_ERROR,
Collections.emptyMap());
}
}
}
| HistoryServerStaticFileServerHandler |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ForOverrideCheckerTest.java | {
"start": 8298,
"end": 9021
} | class ____ extends test.ExtendMe {
// BUG: Diagnostic contains: overrides @ForOverride method test.ExtendMe.overrideMe
public int overrideMe() {
return 1;
}
// BUG: Diagnostic contains: overrides @ForOverride method test.ExtendMe.overrideMe
public int overrideMe(int a) {
return 1;
}
}
""")
.doTest();
}
@Test
public void definerCanCallFromInnerClass() {
compilationHelper
.addSourceLines(
"test/OuterClass.java",
"""
package test;
import com.google.errorprone.annotations.ForOverride;
public | Test |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/BenchmarkThroughput.java | {
"start": 1530,
"end": 1696
} | class ____ the performance of the local file system, raw local
* file system and HDFS at reading and writing files. The user should invoke
* the main of this | benchmarks |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/type/descriptor/java/spi/JdbcTypeRecommendationException.java | {
"start": 403,
"end": 659
} | class ____ extends HibernateException {
public JdbcTypeRecommendationException(String message) {
super( message );
}
public JdbcTypeRecommendationException(String message, Throwable cause) {
super( message, cause );
}
}
| JdbcTypeRecommendationException |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/assertion/RecursiveAssertionDriver_JavaClassLibraryRecursionTest.java | {
"start": 1098,
"end": 2841
} | class ____ extends AbstractRecursiveAssertionDriverTestBase {
@Test
void should_assert_over_but_not_recurse_into_jcl_classes_when_configured_not_to_recurse_into_JCL() {
// GIVEN
RecursiveAssertionDriver objectUnderTest = testSubjectWithDefaultConfiguration();
Object testObject = jclReferencingObject();
// WHEN
List<FieldLocation> failedFields = objectUnderTest.assertOverObjectGraph(failingMockPredicate, testObject);
// THEN
then(failedFields).containsOnly(rootFieldLocation().field("jclField"));
}
@Test
void should_assert_over_and_recurse_into_jcl_classes_when_configured_to_recurse_into_JCL() {
// GIVEN
RecursiveAssertionConfiguration configuration = RecursiveAssertionConfiguration.builder()
.withRecursionIntoJavaClassLibraryTypes(true)
.build();
RecursiveAssertionDriver objectUnderTest = new RecursiveAssertionDriver(configuration);
Object testObject = jclReferencingObject();
// WHEN
List<FieldLocation> failedFields = objectUnderTest.assertOverObjectGraph(failingMockPredicate, testObject);
// THEN
then(failedFields).hasSizeGreaterThanOrEqualTo(3)
.contains(rootFieldLocation().field("jclField"),
// OOOOH, knowledge of String internals! this is why recursion into JCL types is off by default
rootFieldLocation().field("jclField").field("coder"));
}
private Object jclReferencingObject() {
return new ClassWithAFieldWithATypeFromTheJCL();
}
| RecursiveAssertionDriver_JavaClassLibraryRecursionTest |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/processor/utils/TopologyGraphTest.java | {
"start": 1273,
"end": 6821
} | class ____ {
private TestingBatchExecNode[] buildLinkedNodes() {
// 0 -> 1 -> 2 --------> 5
// \-> 3 -> 4 ----/
// \
// \-> 6 -> 7
TestingBatchExecNode[] nodes = new TestingBatchExecNode[8];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = new TestingBatchExecNode("TestingBatchExecNode" + i);
}
nodes[1].addInput(nodes[0]);
nodes[2].addInput(nodes[1]);
nodes[3].addInput(nodes[1]);
nodes[4].addInput(nodes[3]);
nodes[5].addInput(nodes[2]);
nodes[5].addInput(nodes[4]);
nodes[6].addInput(nodes[3]);
nodes[7].addInput(nodes[6]);
return nodes;
}
private Tuple2<TopologyGraph, TestingBatchExecNode[]> buildTopologyGraph() {
TestingBatchExecNode[] nodes = buildLinkedNodes();
return Tuple2.of(new TopologyGraph(Arrays.asList(nodes[5], nodes[7])), nodes);
}
private Tuple2<TopologyGraph, TestingBatchExecNode[]> buildBoundedTopologyGraph() {
// bounded at nodes 2 and 3
TestingBatchExecNode[] nodes = buildLinkedNodes();
return Tuple2.of(
new TopologyGraph(
Arrays.asList(nodes[5], nodes[7]),
new HashSet<>(Arrays.asList(nodes[2], nodes[3]))),
nodes);
}
@Test
void testCanReach() {
Tuple2<TopologyGraph, TestingBatchExecNode[]> tuple2 = buildTopologyGraph();
TopologyGraph graph = tuple2.f0;
TestingBatchExecNode[] nodes = tuple2.f1;
String[] canReach =
new String[] {
"11111111",
"01111111",
"00100100",
"00011111",
"00001100",
"00000100",
"00000011",
"00000001"
};
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (canReach[i].charAt(j) == '1') {
assertThat(graph.canReach(nodes[i], nodes[j])).isTrue();
} else {
assertThat(graph.canReach(nodes[i], nodes[j])).isFalse();
}
}
}
}
@Test
void testLink() {
Tuple2<TopologyGraph, TestingBatchExecNode[]> tuple2 = buildTopologyGraph();
TopologyGraph graph = tuple2.f0;
TestingBatchExecNode[] nodes = tuple2.f1;
assertThat(graph.link(nodes[2], nodes[4])).isTrue();
assertThat(graph.link(nodes[3], nodes[5])).isTrue();
assertThat(graph.link(nodes[5], nodes[6])).isTrue();
assertThat(graph.link(nodes[7], nodes[2])).isFalse();
assertThat(graph.link(nodes[7], nodes[4])).isFalse();
assertThat(graph.link(nodes[0], nodes[7])).isTrue();
}
@Test
void testUnlink() {
Tuple2<TopologyGraph, TestingBatchExecNode[]> tuple2 = buildTopologyGraph();
TopologyGraph graph = tuple2.f0;
TestingBatchExecNode[] nodes = tuple2.f1;
graph.unlink(nodes[2], nodes[5]);
assertThat(graph.canReach(nodes[0], nodes[5])).isTrue();
graph.unlink(nodes[4], nodes[5]);
assertThat(graph.canReach(nodes[0], nodes[5])).isFalse();
graph.unlink(nodes[3], nodes[6]);
assertThat(graph.canReach(nodes[0], nodes[7])).isFalse();
}
@Test
void testCalculateMaximumDistance() {
Tuple2<TopologyGraph, TestingBatchExecNode[]> tuple2 = buildTopologyGraph();
TopologyGraph graph = tuple2.f0;
TestingBatchExecNode[] nodes = tuple2.f1;
Map<ExecNode<?>, Integer> result = graph.calculateMaximumDistance();
assertThat(result).hasSize(8);
assertThat(result.get(nodes[0]).intValue()).isEqualTo(0);
assertThat(result.get(nodes[1]).intValue()).isEqualTo(1);
assertThat(result.get(nodes[2]).intValue()).isEqualTo(2);
assertThat(result.get(nodes[3]).intValue()).isEqualTo(2);
assertThat(result.get(nodes[4]).intValue()).isEqualTo(3);
assertThat(result.get(nodes[6]).intValue()).isEqualTo(3);
assertThat(result.get(nodes[5]).intValue()).isEqualTo(4);
assertThat(result.get(nodes[7]).intValue()).isEqualTo(4);
}
@Test
void testBoundedCalculateMaximumDistance() {
Tuple2<TopologyGraph, TestingBatchExecNode[]> tuple2 = buildBoundedTopologyGraph();
TopologyGraph graph = tuple2.f0;
TestingBatchExecNode[] nodes = tuple2.f1;
Map<ExecNode<?>, Integer> result = graph.calculateMaximumDistance();
assertThat(result).hasSize(6);
assertThat(result.get(nodes[2]).intValue()).isEqualTo(0);
assertThat(result.get(nodes[3]).intValue()).isEqualTo(0);
assertThat(result.get(nodes[4]).intValue()).isEqualTo(1);
assertThat(result.get(nodes[6]).intValue()).isEqualTo(1);
assertThat(result.get(nodes[5]).intValue()).isEqualTo(2);
assertThat(result.get(nodes[7]).intValue()).isEqualTo(2);
}
@Test
void testMakeAsFarAs() {
Tuple2<TopologyGraph, TestingBatchExecNode[]> tuple2 = buildTopologyGraph();
TopologyGraph graph = tuple2.f0;
TestingBatchExecNode[] nodes = tuple2.f1;
graph.makeAsFarAs(nodes[4], nodes[7]);
Map<ExecNode<?>, Integer> distances = graph.calculateMaximumDistance();
assertThat(distances.get(nodes[7]).intValue()).isEqualTo(4);
assertThat(distances.get(nodes[4]).intValue()).isEqualTo(4);
}
}
| TopologyGraphTest |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerApplication.java | {
"start": 1143,
"end": 2596
} | class ____<T extends SchedulerApplicationAttempt> {
private Queue queue;
private final String user;
private volatile T currentAttempt;
private volatile Priority priority;
private boolean unmanagedAM;
public SchedulerApplication(Queue queue, String user, boolean unmanagedAM) {
this.queue = queue;
this.user = user;
this.unmanagedAM = unmanagedAM;
this.priority = null;
}
public SchedulerApplication(Queue queue, String user, Priority priority,
boolean unmanagedAM) {
this.queue = queue;
this.user = user;
this.unmanagedAM = unmanagedAM;
this.priority = priority;
}
public Queue getQueue() {
return queue;
}
public void setQueue(Queue queue) {
this.queue = queue;
}
public String getUser() {
return user;
}
public T getCurrentAppAttempt() {
return currentAttempt;
}
public void setCurrentAppAttempt(T currentAttempt) {
this.currentAttempt = currentAttempt;
}
public void stop(RMAppState rmAppFinalState) {
queue.getMetrics().finishApp(user, rmAppFinalState, isUnmanagedAM());
}
public Priority getPriority() {
return priority;
}
public void setPriority(Priority priority) {
this.priority = priority;
// Also set priority in current running attempt
if (null != currentAttempt) {
currentAttempt.setPriority(priority);
}
}
public boolean isUnmanagedAM() {
return unmanagedAM;
}
}
| SchedulerApplication |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isBetween_Test.java | {
"start": 820,
"end": 1214
} | class ____ extends AbstractZonedDateTimeAssertBaseTest {
@Override
protected ZonedDateTimeAssert invoke_api_method() {
return assertions.isBetween(YESTERDAY, TOMORROW);
}
@Override
protected void verify_internal_effects() {
verify(comparables).assertIsBetween(getInfo(assertions), getActual(assertions), YESTERDAY, TOMORROW, true, true);
}
}
| ZonedDateTimeAssert_isBetween_Test |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/cdi/lifecycle/ExtendedBeanManagerNoCallbackTest.java | {
"start": 1580,
"end": 1686
} | class ____ {
@Id
@GeneratedValue
private Integer id;
private String name;
}
public static | TheEntity |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/serializer/filters/ValueClassLevelTest_private.java | {
"start": 260,
"end": 1402
} | class ____ extends TestCase {
public void test_0() throws Exception {
Object[] array = { new ModelA(), new ModelB() };
SerializeConfig config = new SerializeConfig();
config.addFilter(ModelA.class, //
new ValueFilter() {
@Override
public Object process(Object object, String name, Object value) {
return 30001;
}
});
config.addFilter(ModelB.class, //
new ValueFilter() {
@Override
public Object process(Object object, String name, Object value) {
return 20001;
}
});
String text2 = JSON.toJSONString(array, config);
Assert.assertEquals("[{\"id\":30001},{\"id\":20001}]", text2);
String text = JSON.toJSONString(array);
Assert.assertEquals("[{\"id\":1001},{\"id\":1002}]", text);
}
private static | ValueClassLevelTest_private |
java | quarkusio__quarkus | integration-tests/test-extension/extension-that-defines-junit-test-extensions/runtime/src/main/java/org/acme/CallbackInvokingInterceptor.java | {
"start": 268,
"end": 1444
} | class ____ implements BeforeEachCallback {
@Override
public void beforeEach(ExtensionContext context) throws Exception {
Class testClass = context.getRequiredTestClass();
// Find everything annotated @Callback
List<Method> callbacks = getMethodsAnnotatedWith(testClass, Callback.class);
for (Method m : callbacks) {
m.invoke(context.getRequiredTestInstance());
}
}
protected static List<Method> getMethodsAnnotatedWith(Class<?> clazz, final Class<? extends Annotation> annotationClass) {
final List<Method> methods = new ArrayList<Method>();
while (clazz != Object.class) {
for (final Method method : clazz.getDeclaredMethods()) {
// Check by name since we could have some classloader mismatches
Annotation[] allAnnotations = method.getAnnotations();
for (Annotation annotation : allAnnotations) {
if (annotation.annotationType().getName().equals(annotationClass.getName()))
methods.add(method);
}
}
// move to the upper | CallbackInvokingInterceptor |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/cluster/CamelClusterView.java | {
"start": 2225,
"end": 2739
} | interface ____ the underlying concrete CamelClusterView.
* @return an instance of the underlying concrete CamelClusterView as the required type.
*/
default <T extends CamelClusterView> T unwrap(Class<T> clazz) {
if (CamelClusterView.class.isAssignableFrom(clazz)) {
return clazz.cast(this);
}
throw new IllegalArgumentException(
"Unable to unwrap this CamelClusterView type (" + getClass() + ") to the required type (" + clazz + ")");
}
}
| of |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/indices/ExecutorSelector.java | {
"start": 1027,
"end": 4510
} | class ____ {
private final SystemIndices systemIndices;
/**
* Package-private constructor; in general it's best to get an ExecutorSelector
* from {@link SystemIndices#getExecutorSelector()}.
* @param systemIndices A system indices object that this ExecutorSelector will
* use to match system index names to system index descriptors.
*/
ExecutorSelector(SystemIndices systemIndices) {
this.systemIndices = systemIndices;
}
/**
* The "get" executor should be used when retrieving documents by ID.
* @param indexName Name of the index
* @return Name of the executor to use for a get operation.
*/
public String executorForGet(String indexName) {
SystemIndexDescriptor indexDescriptor = systemIndices.findMatchingDescriptor(indexName);
if (Objects.nonNull(indexDescriptor)) {
return indexDescriptor.getThreadPoolNames().threadPoolForGet();
}
SystemDataStreamDescriptor dataStreamDescriptor = systemIndices.findMatchingDataStreamDescriptor(indexName);
if (Objects.nonNull(dataStreamDescriptor)) {
return dataStreamDescriptor.getThreadPoolNames().threadPoolForGet();
}
return ThreadPool.Names.GET;
}
/**
* The "search" executor should be used for search or aggregation operations.
* @param indexName Name of the index
* @return Name of the executor to use for a search operation.
*/
public String executorForSearch(String indexName) {
SystemIndexDescriptor indexDescriptor = systemIndices.findMatchingDescriptor(indexName);
if (Objects.nonNull(indexDescriptor)) {
return indexDescriptor.getThreadPoolNames().threadPoolForSearch();
}
SystemDataStreamDescriptor dataStreamDescriptor = systemIndices.findMatchingDataStreamDescriptor(indexName);
if (Objects.nonNull(dataStreamDescriptor)) {
return dataStreamDescriptor.getThreadPoolNames().threadPoolForSearch();
}
return ThreadPool.Names.SEARCH;
}
/**
* The "write" executor should be used for operations that write new documents or
* update existing ones.
* @param indexName Name of the index
* @return Name of the executor to use for a search operation.
*/
public String executorForWrite(String indexName) {
SystemIndexDescriptor indexDescriptor = systemIndices.findMatchingDescriptor(indexName);
if (Objects.nonNull(indexDescriptor)) {
return indexDescriptor.getThreadPoolNames().threadPoolForWrite();
}
SystemDataStreamDescriptor dataStreamDescriptor = systemIndices.findMatchingDataStreamDescriptor(indexName);
if (Objects.nonNull(dataStreamDescriptor)) {
return dataStreamDescriptor.getThreadPoolNames().threadPoolForWrite();
}
return ThreadPool.Names.WRITE;
}
/**
* This is a convenience method for the case when we need to find an executor for a shard.
* @return a {@link java.util.function.BiFunction} which returns the executor that should be used for write operations on this shard.
*/
public static BiFunction<ExecutorSelector, IndexShard, Executor> getWriteExecutorForShard(ThreadPool threadPool) {
return (executorSelector, indexShard) -> threadPool.executor(
executorSelector.executorForWrite(indexShard.shardId().getIndexName())
);
}
}
| ExecutorSelector |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/reduce/WrappedReducer.java | {
"start": 2476,
"end": 9147
} | class ____
extends Reducer<KEYIN, VALUEIN, KEYOUT, VALUEOUT>.Context {
protected ReduceContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT> reduceContext;
public Context(ReduceContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT> reduceContext)
{
this.reduceContext = reduceContext;
}
@Override
public KEYIN getCurrentKey() throws IOException, InterruptedException {
return reduceContext.getCurrentKey();
}
@Override
public VALUEIN getCurrentValue() throws IOException, InterruptedException {
return reduceContext.getCurrentValue();
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
return reduceContext.nextKeyValue();
}
@Override
public Counter getCounter(Enum counterName) {
return reduceContext.getCounter(counterName);
}
@Override
public Counter getCounter(String groupName, String counterName) {
return reduceContext.getCounter(groupName, counterName);
}
@Override
public OutputCommitter getOutputCommitter() {
return reduceContext.getOutputCommitter();
}
@Override
public void write(KEYOUT key, VALUEOUT value) throws IOException,
InterruptedException {
reduceContext.write(key, value);
}
@Override
public String getStatus() {
return reduceContext.getStatus();
}
@Override
public TaskAttemptID getTaskAttemptID() {
return reduceContext.getTaskAttemptID();
}
@Override
public void setStatus(String msg) {
reduceContext.setStatus(msg);
}
@Override
public Path[] getArchiveClassPaths() {
return reduceContext.getArchiveClassPaths();
}
@Override
public String[] getArchiveTimestamps() {
return reduceContext.getArchiveTimestamps();
}
@Override
public URI[] getCacheArchives() throws IOException {
return reduceContext.getCacheArchives();
}
@Override
public URI[] getCacheFiles() throws IOException {
return reduceContext.getCacheFiles();
}
@Override
public Class<? extends Reducer<?, ?, ?, ?>> getCombinerClass()
throws ClassNotFoundException {
return reduceContext.getCombinerClass();
}
@Override
public Configuration getConfiguration() {
return reduceContext.getConfiguration();
}
@Override
public Path[] getFileClassPaths() {
return reduceContext.getFileClassPaths();
}
@Override
public String[] getFileTimestamps() {
return reduceContext.getFileTimestamps();
}
@Override
public RawComparator<?> getCombinerKeyGroupingComparator() {
return reduceContext.getCombinerKeyGroupingComparator();
}
@Override
public RawComparator<?> getGroupingComparator() {
return reduceContext.getGroupingComparator();
}
@Override
public Class<? extends InputFormat<?, ?>> getInputFormatClass()
throws ClassNotFoundException {
return reduceContext.getInputFormatClass();
}
@Override
public String getJar() {
return reduceContext.getJar();
}
@Override
public JobID getJobID() {
return reduceContext.getJobID();
}
@Override
public String getJobName() {
return reduceContext.getJobName();
}
@Override
public boolean getJobSetupCleanupNeeded() {
return reduceContext.getJobSetupCleanupNeeded();
}
@Override
public boolean getTaskCleanupNeeded() {
return reduceContext.getTaskCleanupNeeded();
}
@Override
public Path[] getLocalCacheArchives() throws IOException {
return reduceContext.getLocalCacheArchives();
}
@Override
public Path[] getLocalCacheFiles() throws IOException {
return reduceContext.getLocalCacheFiles();
}
@Override
public Class<?> getMapOutputKeyClass() {
return reduceContext.getMapOutputKeyClass();
}
@Override
public Class<?> getMapOutputValueClass() {
return reduceContext.getMapOutputValueClass();
}
@Override
public Class<? extends Mapper<?, ?, ?, ?>> getMapperClass()
throws ClassNotFoundException {
return reduceContext.getMapperClass();
}
@Override
public int getMaxMapAttempts() {
return reduceContext.getMaxMapAttempts();
}
@Override
public int getMaxReduceAttempts() {
return reduceContext.getMaxReduceAttempts();
}
@Override
public int getNumReduceTasks() {
return reduceContext.getNumReduceTasks();
}
@Override
public Class<? extends OutputFormat<?, ?>> getOutputFormatClass()
throws ClassNotFoundException {
return reduceContext.getOutputFormatClass();
}
@Override
public Class<?> getOutputKeyClass() {
return reduceContext.getOutputKeyClass();
}
@Override
public Class<?> getOutputValueClass() {
return reduceContext.getOutputValueClass();
}
@Override
public Class<? extends Partitioner<?, ?>> getPartitionerClass()
throws ClassNotFoundException {
return reduceContext.getPartitionerClass();
}
@Override
public Class<? extends Reducer<?, ?, ?, ?>> getReducerClass()
throws ClassNotFoundException {
return reduceContext.getReducerClass();
}
@Override
public RawComparator<?> getSortComparator() {
return reduceContext.getSortComparator();
}
@Override
public boolean getSymlink() {
return reduceContext.getSymlink();
}
@Override
public Path getWorkingDirectory() throws IOException {
return reduceContext.getWorkingDirectory();
}
@Override
public void progress() {
reduceContext.progress();
}
@Override
public Iterable<VALUEIN> getValues() throws IOException,
InterruptedException {
return reduceContext.getValues();
}
@Override
public boolean nextKey() throws IOException, InterruptedException {
return reduceContext.nextKey();
}
@Override
public boolean getProfileEnabled() {
return reduceContext.getProfileEnabled();
}
@Override
public String getProfileParams() {
return reduceContext.getProfileParams();
}
@Override
public IntegerRanges getProfileTaskRange(boolean isMap) {
return reduceContext.getProfileTaskRange(isMap);
}
@Override
public String getUser() {
return reduceContext.getUser();
}
@Override
public Credentials getCredentials() {
return reduceContext.getCredentials();
}
@Override
public float getProgress() {
return reduceContext.getProgress();
}
}
}
| Context |
java | apache__kafka | metadata/src/test/java/org/apache/kafka/image/AclsDeltaTest.java | {
"start": 1478,
"end": 5043
} | class ____ {
private final Uuid aclId = Uuid.fromString("iOZpss6VQUmD6blnqzl50g");
@Test
public void testRemovesDeleteIfNotInImage() {
AclsImage image = new AclsImage(Map.of());
AclsDelta delta = new AclsDelta(image);
AccessControlEntryRecord inputAclRecord = testAccessControlEntryRecord();
assertEquals(0, delta.changes().size());
delta.replay(inputAclRecord);
assertEquals(Optional.of(testStandardAcl()), delta.changes().get(aclId));
RemoveAccessControlEntryRecord inputRemoveAclRecord = testRemoveAccessControlEntryRecord();
delta.replay(inputRemoveAclRecord);
assertFalse(delta.changes().containsKey(aclId));
}
@Test
public void testKeepsDeleteIfInImage() {
Map<Uuid, StandardAcl> initialImageMap = new HashMap<>();
initialImageMap.put(aclId, testStandardAcl());
AclsImage image = new AclsImage(initialImageMap);
AclsDelta delta = new AclsDelta(image);
assertEquals(0, delta.changes().size());
RemoveAccessControlEntryRecord removeAccessControlEntryRecord = testRemoveAccessControlEntryRecord();
delta.replay(removeAccessControlEntryRecord);
assertTrue(delta.changes().containsKey(aclId));
assertEquals(Optional.empty(), delta.changes().get(aclId));
}
@Test
public void testThrowsExceptionOnInvalidStateWhenImageIsEmpty() {
AclsImage image = new AclsImage(Map.of());
AclsDelta delta = new AclsDelta(image);
RemoveAccessControlEntryRecord removeAccessControlEntryRecord = testRemoveAccessControlEntryRecord();
assertThrows(IllegalStateException.class, () -> delta.replay(removeAccessControlEntryRecord));
}
@Test
public void testThrowsExceptionOnInvalidStateWhenImageHasOtherAcls() {
Uuid id = Uuid.fromString("nGiNMQHwRgmgsIlfu73aJQ");
AccessControlEntryRecord record = new AccessControlEntryRecord();
record.setId(id);
record.setResourceType((byte) 1);
record.setResourceName("foo");
record.setPatternType((byte) 1);
record.setPrincipal("User:user");
record.setHost("host");
record.setOperation((byte) 1);
record.setPermissionType((byte) 1);
Map<Uuid, StandardAcl> initialImageMap = new HashMap<>();
initialImageMap.put(id, StandardAcl.fromRecord(record));
AclsImage image = new AclsImage(initialImageMap);
AclsDelta delta = new AclsDelta(image);
RemoveAccessControlEntryRecord removeAccessControlEntryRecord = testRemoveAccessControlEntryRecord();
assertThrows(IllegalStateException.class, () -> delta.replay(removeAccessControlEntryRecord));
}
private AccessControlEntryRecord testAccessControlEntryRecord() {
AccessControlEntryRecord record = new AccessControlEntryRecord();
record.setId(aclId);
record.setResourceType((byte) 1);
record.setResourceName("foo");
record.setPatternType((byte) 1);
record.setPrincipal("User:user");
record.setHost("host");
record.setOperation((byte) 1);
record.setPermissionType((byte) 1);
return record;
}
private RemoveAccessControlEntryRecord testRemoveAccessControlEntryRecord() {
RemoveAccessControlEntryRecord record = new RemoveAccessControlEntryRecord();
record.setId(aclId);
return record;
}
private StandardAcl testStandardAcl() {
return StandardAcl.fromRecord(testAccessControlEntryRecord());
}
}
| AclsDeltaTest |
java | quarkusio__quarkus | core/runtime/src/main/java/io/quarkus/logging/Log.java | {
"start": 92867,
"end": 93536
} | class ____
* @param level the level
* @param t the throwable
* @param format the message format string
* @param param1 the first parameter
* @param param2 the second parameter
*/
public static void logv(String loggerFqcn, Logger.Level level, Throwable t, String format, Object param1, Object param2) {
if (shouldFail) {
throw fail();
}
Logger.getLogger(stackWalker.getCallerClass()).logv(loggerFqcn, level, t, format, param1, param2);
}
/**
* Issue a log message at the given log level using {@link java.text.MessageFormat}-style formatting.
*
* @param loggerFqcn the logger | name |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/util/ClassUtils.java | {
"start": 19768,
"end": 20014
} | class ____ a primitive array class
*/
public static boolean isPrimitiveArray(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
return (clazz.isArray() && clazz.componentType().isPrimitive());
}
/**
* Check if the given | is |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/utils/ExitTest.java | {
"start": 1021,
"end": 2943
} | class ____ {
@Test
public void shouldHaltImmediately() {
List<Object> list = new ArrayList<>();
Exit.setHaltProcedure((statusCode, message) -> {
list.add(statusCode);
list.add(message);
});
try {
int statusCode = 0;
String message = "message";
Exit.halt(statusCode);
Exit.halt(statusCode, message);
assertEquals(Arrays.asList(statusCode, null, statusCode, message), list);
} finally {
Exit.resetHaltProcedure();
}
}
@Test
public void shouldExitImmediately() {
List<Object> list = new ArrayList<>();
Exit.setExitProcedure((statusCode, message) -> {
list.add(statusCode);
list.add(message);
});
try {
int statusCode = 0;
String message = "message";
Exit.exit(statusCode);
Exit.exit(statusCode, message);
assertEquals(Arrays.asList(statusCode, null, statusCode, message), list);
} finally {
Exit.resetExitProcedure();
}
}
@Test
public void shouldAddShutdownHookImmediately() {
List<Object> list = new ArrayList<>();
Exit.setShutdownHookAdder((name, runnable) -> {
list.add(name);
list.add(runnable);
});
try {
Runnable runnable = () -> { };
String name = "name";
Exit.addShutdownHook(name, runnable);
assertEquals(Arrays.asList(name, runnable), list);
} finally {
Exit.resetShutdownHookAdder();
}
}
@Test
public void shouldNotInvokeShutdownHookImmediately() {
List<Object> list = new ArrayList<>();
Runnable runnable = () -> list.add(this);
Exit.addShutdownHook("message", runnable);
assertEquals(0, list.size());
}
}
| ExitTest |
java | junit-team__junit5 | junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/discovery/AbstractAnnotatedDescriptorWrapper.java | {
"start": 680,
"end": 782
} | class ____ wrappers for test descriptors based on annotated
* elements.
*
* @since 5.8
*/
abstract | for |
java | apache__kafka | server-common/src/main/java/org/apache/kafka/server/share/persister/InitializeShareGroupStateResult.java | {
"start": 3193,
"end": 3582
} | class ____ {
private List<TopicData<PartitionErrorData>> topicsData;
public Builder setTopicsData(List<TopicData<PartitionErrorData>> topicsData) {
this.topicsData = topicsData;
return this;
}
public InitializeShareGroupStateResult build() {
return new InitializeShareGroupStateResult(topicsData);
}
}
}
| Builder |
java | google__guice | core/test/com/google/inject/util/OverrideModuleTest.java | {
"start": 2093,
"end": 6787
} | class ____ extends TestCase {
private static final Key<String> key2 = Key.get(String.class, named("2"));
private static final Key<String> key3 = Key.get(String.class, named("3"));
private static final Module EMPTY_MODULE =
new Module() {
@Override
public void configure(Binder binder) {}
};
public void testOverride() {
Injector injector = createInjector(Modules.override(newModule("A")).with(newModule("B")));
assertEquals("B", injector.getInstance(String.class));
}
public void testOverrideMultiple() {
Module module =
Modules.override(newModule("A"), newModule(1), newModule(0.5f))
.with(newModule("B"), newModule(2), newModule(1.5d));
Injector injector = createInjector(module);
assertEquals("B", injector.getInstance(String.class));
assertEquals(2, injector.getInstance(Integer.class).intValue());
assertEquals(0.5f, injector.getInstance(Float.class), 0.0f);
assertEquals(1.5d, injector.getInstance(Double.class), 0.0);
}
public void testOverrideUnmatchedTolerated() {
Injector injector = createInjector(Modules.override(EMPTY_MODULE).with(newModule("B")));
assertEquals("B", injector.getInstance(String.class));
}
public void testOverrideConstant() {
Module original =
new AbstractModule() {
@Override
protected void configure() {
bindConstant().annotatedWith(named("Test")).to("A");
}
};
Module replacements =
new AbstractModule() {
@Override
protected void configure() {
bindConstant().annotatedWith(named("Test")).to("B");
}
};
Injector injector = createInjector(Modules.override(original).with(replacements));
assertEquals("B", injector.getInstance(Key.get(String.class, named("Test"))));
}
public void testGetProviderInModule() {
Module original =
new AbstractModule() {
@Override
protected void configure() {
bind(String.class).toInstance("A");
bind(key2).toProvider(getProvider(String.class));
}
};
Injector injector = createInjector(Modules.override(original).with(EMPTY_MODULE));
assertEquals("A", injector.getInstance(String.class));
assertEquals("A", injector.getInstance(key2));
}
public void testOverrideWhatGetProviderProvided() {
Module original =
new AbstractModule() {
@Override
protected void configure() {
bind(String.class).toInstance("A");
bind(key2).toProvider(getProvider(String.class));
}
};
Module replacements = newModule("B");
Injector injector = createInjector(Modules.override(original).with(replacements));
assertEquals("B", injector.getInstance(String.class));
assertEquals("B", injector.getInstance(key2));
}
public void testOverrideUsingOriginalsGetProvider() {
Module original =
new AbstractModule() {
@Override
protected void configure() {
bind(String.class).toInstance("A");
bind(key2).toInstance("B");
}
};
Module replacements =
new AbstractModule() {
@Override
protected void configure() {
bind(String.class).toProvider(getProvider(key2));
}
};
Injector injector = createInjector(Modules.override(original).with(replacements));
assertEquals("B", injector.getInstance(String.class));
assertEquals("B", injector.getInstance(key2));
}
public void testOverrideOfOverride() {
Module original =
new AbstractModule() {
@Override
protected void configure() {
bind(String.class).toInstance("A1");
bind(key2).toInstance("A2");
bind(key3).toInstance("A3");
}
};
Module replacements1 =
new AbstractModule() {
@Override
protected void configure() {
bind(String.class).toInstance("B1");
bind(key2).toInstance("B2");
}
};
Module overrides = Modules.override(original).with(replacements1);
Module replacements2 =
new AbstractModule() {
@Override
protected void configure() {
bind(String.class).toInstance("C1");
bind(key3).toInstance("C3");
}
};
Injector injector = createInjector(Modules.override(overrides).with(replacements2));
assertEquals("C1", injector.getInstance(String.class));
assertEquals("B2", injector.getInstance(key2));
assertEquals("C3", injector.getInstance(key3));
}
static | OverrideModuleTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/MappedSuperclassWithIdOnSubclassesTest.java | {
"start": 3604,
"end": 4137
} | class ____ extends Customer {
private Integer id;
private String taxId;
public DomesticCustomer() {
}
public DomesticCustomer(Integer id, String name, String taxId) {
super( name );
this.id = id;
this.taxId = taxId;
}
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTaxId() {
return taxId;
}
public void setTaxId(String taxId) {
this.taxId = taxId;
}
}
@Entity(name = "ForeignCustomer")
public static | DomesticCustomer |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/annotations/FetchProfile.java | {
"start": 3564,
"end": 4655
} | interface ____ {
/**
* The name of the fetch profile. Must be unique within a persistence
* unit.
*
* @see org.hibernate.SessionFactory#getDefinedFetchProfileNames()
*/
String name();
/**
* The list of association fetching strategy overrides.
* <p>
* Additional overrides may be specified by marking the
* fetched associations themselves with the {@link Fetch @Fetch}
* annotation.
*/
FetchOverride[] fetchOverrides() default {};
/**
* Overrides the fetching strategy for a particular association in
* the named fetch profile being defined. A "strategy" is a fetching
* {@linkplain #mode method}, together with the {@linkplain #fetch
* timing}. If {@link #mode} and {@link #fetch} are both unspecified,
* the strategy defaults to {@linkplain FetchType#EAGER eager}
* {@linkplain FetchMode#JOIN join} fetching.
* <p>
* Additional fetch strategy overrides may be specified using the
* {@link FetchProfileOverride @FetchProfileOverride} annotation.
*
* @see FetchProfileOverride
*/
@Target({ TYPE, PACKAGE })
@Retention(RUNTIME)
@ | FetchProfile |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/oauth2/OAuth2Constants.java | {
"start": 1103,
"end": 1855
} | class ____ {
private OAuth2Constants() { /** Private constructor. **/ }
public static final String URLENCODED
= "application/x-www-form-urlencoded; charset=utf-8";
/* Constants for OAuth protocol */
public static final String ACCESS_TOKEN = "access_token";
public static final String BEARER = "bearer";
public static final String CLIENT_CREDENTIALS = "client_credentials";
public static final String CLIENT_ID = "client_id";
public static final String CLIENT_SECRET = "client_secret";
public static final String EXPIRES_IN = "expires_in";
public static final String GRANT_TYPE = "grant_type";
public static final String REFRESH_TOKEN = "refresh_token";
public static final String TOKEN_TYPE = "token_type";
}
| OAuth2Constants |
java | quarkusio__quarkus | extensions/panache/panache-hibernate-common/deployment/src/main/java/io/quarkus/panache/hibernate/common/deployment/PanacheJpaEntityAccessorsEnhancer.java | {
"start": 461,
"end": 1192
} | class ____
implements BiFunction<String, ClassVisitor, ClassVisitor> {
private final IndexView indexView;
private final MetamodelInfo modelInfo;
public PanacheJpaEntityAccessorsEnhancer(IndexView index, MetamodelInfo modelInfo) {
this.indexView = index;
this.modelInfo = modelInfo;
}
@Override
public ClassVisitor apply(String className, ClassVisitor outputClassVisitor) {
ClassInfo entityInfo = indexView.getClassByName(DotName.createSimple(className));
EntityModel entityModel = modelInfo.getEntityModel(className);
return new PanacheEntityClassAccessorGenerationVisitor(outputClassVisitor, entityInfo, entityModel);
}
}
| PanacheJpaEntityAccessorsEnhancer |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/BraintreeComponentBuilderFactory.java | {
"start": 1376,
"end": 1844
} | interface ____ {
/**
* Braintree (camel-braintree)
* Process payments using Braintree Payments.
*
* Category: saas
* Since: 2.17
* Maven coordinates: org.apache.camel:camel-braintree
*
* @return the dsl builder
*/
static BraintreeComponentBuilder braintree() {
return new BraintreeComponentBuilderImpl();
}
/**
* Builder for the Braintree component.
*/
| BraintreeComponentBuilderFactory |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/operators/CoGroupRawDriver.java | {
"start": 3723,
"end": 4185
} | class ____<IN> implements Iterable<IN> {
private IN reuse;
private final MutableObjectIterator<IN> iterator;
public SimpleIterable(IN reuse, MutableObjectIterator<IN> iterator) throws IOException {
this.iterator = iterator;
this.reuse = reuse;
}
@Override
public Iterator<IN> iterator() {
return new SimpleIterator<IN>(reuse, iterator);
}
protected | SimpleIterable |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/search/slice/SliceBuilderTests.java | {
"start": 2784,
"end": 16578
} | class ____ extends ESTestCase {
private static final int MAX_SLICE = 20;
private static SliceBuilder randomSliceBuilder() {
int max = randomIntBetween(2, MAX_SLICE);
int id = randomIntBetween(1, max - 1);
String field = randomBoolean() ? randomAlphaOfLengthBetween(5, 20) : null;
return new SliceBuilder(field, id, max);
}
private static SliceBuilder serializedCopy(SliceBuilder original) throws IOException {
return copyWriteable(original, new NamedWriteableRegistry(Collections.emptyList()), SliceBuilder::new);
}
private static SliceBuilder mutate(SliceBuilder original) {
switch (randomIntBetween(0, 2)) {
case 0:
String newField;
if (original.getField() == null) {
newField = randomAlphaOfLength(5);
} else {
newField = randomBoolean() ? original.getField() + "_xyz" : null;
}
return new SliceBuilder(newField, original.getId(), original.getMax());
case 1:
return new SliceBuilder(original.getField(), original.getId() - 1, original.getMax());
case 2:
default:
return new SliceBuilder(original.getField(), original.getId(), original.getMax() + 1);
}
}
private IndexSettings createIndexSettings(IndexVersion indexVersionCreated) {
IndexMetadata indexState = IndexMetadata.builder("index").settings(indexSettings(indexVersionCreated, 1, 0)).build();
return new IndexSettings(indexState, Settings.EMPTY);
}
private ShardSearchRequest createPointInTimeRequest(int shardIndex, int numShards) {
SearchRequest searchRequest = new SearchRequest().allowPartialSearchResults(true)
.source(new SearchSourceBuilder().pointInTimeBuilder(new PointInTimeBuilder(new BytesArray("1m"))));
return new ShardSearchRequest(
OriginalIndices.NONE,
searchRequest,
new ShardId("index", "index", 0),
shardIndex,
numShards,
null,
0f,
System.currentTimeMillis(),
null
);
}
private ShardSearchRequest createScrollRequest(int shardIndex, int numShards) {
SearchRequest searchRequest = new SearchRequest().allowPartialSearchResults(true).scroll(TimeValue.timeValueMinutes(1));
return new ShardSearchRequest(
OriginalIndices.NONE,
searchRequest,
new ShardId("index", "index", 0),
shardIndex,
numShards,
null,
0f,
System.currentTimeMillis(),
null
);
}
private SearchExecutionContext createShardContext(
IndexVersion indexVersionCreated,
IndexReader reader,
String fieldName,
DocValuesType dvType
) {
IndexType indexType = IndexType.terms(false, dvType != null);
MappedFieldType fieldType = new MappedFieldType(fieldName, indexType, false, Collections.emptyMap()) {
@Override
public ValueFetcher valueFetcher(SearchExecutionContext context, String format) {
throw new UnsupportedOperationException();
}
@Override
public String typeName() {
return null;
}
@Override
public Query termQuery(Object value, @Nullable SearchExecutionContext context) {
return null;
}
public Query existsQuery(SearchExecutionContext context) {
return null;
}
};
SearchExecutionContext context = mock(SearchExecutionContext.class);
when(context.getFieldType(fieldName)).thenReturn(fieldType);
when(context.getIndexReader()).thenReturn(reader);
IndexSettings indexSettings = createIndexSettings(indexVersionCreated);
when(context.getIndexSettings()).thenReturn(indexSettings);
if (dvType != null) {
IndexNumericFieldData fd = mock(IndexNumericFieldData.class);
when(context.getForField(fieldType, MappedFieldType.FielddataOperation.SEARCH)).thenReturn(fd);
}
return context;
}
public void testSerialization() throws Exception {
SliceBuilder original = randomSliceBuilder();
SliceBuilder deserialized = serializedCopy(original);
assertEquals(deserialized, original);
assertEquals(deserialized.hashCode(), original.hashCode());
assertNotSame(deserialized, original);
}
public void testEqualsAndHashcode() throws Exception {
checkEqualsAndHashCode(randomSliceBuilder(), SliceBuilderTests::serializedCopy, SliceBuilderTests::mutate);
}
public void testFromXContent() throws Exception {
SliceBuilder sliceBuilder = randomSliceBuilder();
XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
if (randomBoolean()) {
builder.prettyPrint();
}
builder.startObject();
sliceBuilder.innerToXContent(builder);
builder.endObject();
try (XContentParser parser = createParser(shuffleXContent(builder))) {
SliceBuilder secondSliceBuilder = SliceBuilder.fromXContent(parser);
assertNotSame(sliceBuilder, secondSliceBuilder);
assertEquals(sliceBuilder, secondSliceBuilder);
assertEquals(sliceBuilder.hashCode(), secondSliceBuilder.hashCode());
}
}
public void testInvalidArguments() throws Exception {
Exception e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", -1, 10));
assertEquals("id must be greater than or equal to 0", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", 10, -1));
assertEquals("max must be greater than 1", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", 10, 0));
assertEquals("max must be greater than 1", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", 10, 5));
assertEquals("max must be greater than id", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", 1000, 1000));
assertEquals("max must be greater than id", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", 1001, 1000));
assertEquals("max must be greater than id", e.getMessage());
}
public void testToFilterSimple() throws IOException {
Directory dir = new ByteBuffersDirectory();
try (IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())))) {
writer.commit();
}
try (IndexReader reader = DirectoryReader.open(dir)) {
SearchExecutionContext context = createShardContext(IndexVersion.current(), reader, "field", null);
SliceBuilder builder = new SliceBuilder(5, 10);
Query query = builder.toFilter(createPointInTimeRequest(0, 1), context);
assertThat(query, instanceOf(DocIdSliceQuery.class));
assertThat(builder.toFilter(createPointInTimeRequest(0, 1), context), equalTo(query));
try (IndexReader newReader = DirectoryReader.open(dir)) {
when(context.getIndexReader()).thenReturn(newReader);
assertThat(builder.toFilter(createPointInTimeRequest(0, 1), context), equalTo(query));
}
}
}
public void testToFilterSimpleWithScroll() throws IOException {
Directory dir = new ByteBuffersDirectory();
try (IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())))) {
writer.commit();
}
try (IndexReader reader = DirectoryReader.open(dir)) {
SearchExecutionContext context = createShardContext(IndexVersion.current(), reader, "_id", null);
SliceBuilder builder = new SliceBuilder(5, 10);
Query query = builder.toFilter(createScrollRequest(0, 1), context);
assertThat(query, instanceOf(TermsSliceQuery.class));
assertThat(builder.toFilter(createScrollRequest(0, 1), context), equalTo(query));
try (IndexReader newReader = DirectoryReader.open(dir)) {
when(context.getIndexReader()).thenReturn(newReader);
assertThat(builder.toFilter(createScrollRequest(0, 1), context), equalTo(query));
}
}
}
public void testToFilterRandom() throws IOException {
Directory dir = new ByteBuffersDirectory();
try (IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())))) {
writer.commit();
}
try (IndexReader reader = DirectoryReader.open(dir)) {
SearchExecutionContext context = createShardContext(IndexVersion.current(), reader, "field", DocValuesType.SORTED_NUMERIC);
SliceBuilder builder = new SliceBuilder("field", 5, 10);
Query query = builder.toFilter(createScrollRequest(0, 1), context);
assertThat(query, instanceOf(DocValuesSliceQuery.class));
assertThat(builder.toFilter(createScrollRequest(0, 1), context), equalTo(query));
try (IndexReader newReader = DirectoryReader.open(dir)) {
when(context.getIndexReader()).thenReturn(newReader);
assertThat(builder.toFilter(createScrollRequest(0, 1), context), equalTo(query));
}
// numSlices > numShards
int numSlices = randomIntBetween(10, 100);
int numShards = randomIntBetween(1, 9);
Map<Integer, AtomicInteger> numSliceMap = new HashMap<>();
for (int i = 0; i < numSlices; i++) {
for (int j = 0; j < numShards; j++) {
SliceBuilder slice = new SliceBuilder("_id", i, numSlices);
context = createShardContext(IndexVersion.current(), reader, "_id", null);
Query q = slice.toFilter(createScrollRequest(j, numShards), context);
if (q instanceof TermsSliceQuery || q instanceof MatchAllDocsQuery) {
AtomicInteger count = numSliceMap.get(j);
if (count == null) {
count = new AtomicInteger(0);
numSliceMap.put(j, count);
}
count.incrementAndGet();
if (q instanceof MatchAllDocsQuery) {
assertThat(count.get(), equalTo(1));
}
} else {
assertThat(q, instanceOf(MatchNoDocsQuery.class));
}
}
}
int total = 0;
for (Map.Entry<Integer, AtomicInteger> e : numSliceMap.entrySet()) {
total += e.getValue().get();
}
assertThat(total, equalTo(numSlices));
// numShards > numSlices
numShards = randomIntBetween(4, 100);
numSlices = randomIntBetween(2, numShards - 1);
List<Integer> targetShards = new ArrayList<>();
for (int i = 0; i < numSlices; i++) {
for (int j = 0; j < numShards; j++) {
SliceBuilder slice = new SliceBuilder("_id", i, numSlices);
context = createShardContext(IndexVersion.current(), reader, "_id", null);
Query q = slice.toFilter(createScrollRequest(j, numShards), context);
if (q instanceof MatchNoDocsQuery == false) {
assertThat(q, instanceOf(MatchAllDocsQuery.class));
targetShards.add(j);
}
}
}
assertThat(targetShards.size(), equalTo(numShards));
assertThat(new HashSet<>(targetShards).size(), equalTo(numShards));
// numShards == numSlices
numShards = randomIntBetween(2, 10);
numSlices = numShards;
for (int i = 0; i < numSlices; i++) {
for (int j = 0; j < numShards; j++) {
SliceBuilder slice = new SliceBuilder("_id", i, numSlices);
context = createShardContext(IndexVersion.current(), reader, "_id", null);
Query q = slice.toFilter(createScrollRequest(j, numShards), context);
if (i == j) {
assertThat(q, instanceOf(MatchAllDocsQuery.class));
} else {
assertThat(q, instanceOf(MatchNoDocsQuery.class));
}
}
}
}
}
public void testInvalidField() throws IOException {
Directory dir = new ByteBuffersDirectory();
try (IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())))) {
writer.commit();
}
try (IndexReader reader = DirectoryReader.open(dir)) {
SearchExecutionContext context = createShardContext(IndexVersion.current(), reader, "field", null);
SliceBuilder builder = new SliceBuilder("field", 5, 10);
IllegalArgumentException exc = expectThrows(
IllegalArgumentException.class,
() -> builder.toFilter(createScrollRequest(0, 1), context)
);
assertThat(exc.getMessage(), containsString("cannot load numeric doc values"));
}
}
}
| SliceBuilderTests |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/SubQueryExpression.java | {
"start": 616,
"end": 2082
} | class ____ extends Expression {
private final LogicalPlan query;
private final NameId id;
public SubQueryExpression(Source source, LogicalPlan query) {
this(source, query, null);
}
public SubQueryExpression(Source source, LogicalPlan query, NameId id) {
super(source, Collections.emptyList());
this.query = query;
this.id = id == null ? new NameId() : id;
}
@Override
public final Expression replaceChildren(List<Expression> newChildren) {
throw new UnsupportedOperationException("this type of node doesn't have any children to replace");
}
public LogicalPlan query() {
return query;
}
public NameId id() {
return id;
}
@Override
public boolean resolved() {
return false;
}
public SubQueryExpression withQuery(LogicalPlan newQuery) {
return (Objects.equals(query, newQuery) ? this : clone(newQuery));
}
protected abstract SubQueryExpression clone(LogicalPlan newQuery);
@Override
public int hashCode() {
return Objects.hash(query());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
SubQueryExpression other = (SubQueryExpression) obj;
return Objects.equals(query(), other.query());
}
}
| SubQueryExpression |
java | resilience4j__resilience4j | resilience4j-spring/src/test/java/io/github/resilience4j/utils/AnnotationExtractorTest.java | {
"start": 897,
"end": 980
} | class ____ {
public void withAnnotation() {
}
}
} | NotAnnotatedClass |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointMetadataLoadingTest.java | {
"start": 2502,
"end": 11429
} | class ____ {
private final ClassLoader cl = getClass().getClassLoader();
/** Tests correct savepoint loading. */
@Test
void testAllStateRestored() throws Exception {
final JobID jobId = new JobID();
final OperatorID operatorId = new OperatorID();
final long checkpointId = Integer.MAX_VALUE + 123123L;
final int parallelism = 128128;
final CompletedCheckpointStorageLocation testSavepoint =
createSavepointWithOperatorSubtaskState(checkpointId, operatorId, parallelism);
final Map<JobVertexID, ExecutionJobVertex> tasks =
createTasks(operatorId, parallelism, parallelism);
final CompletedCheckpoint loaded =
Checkpoints.loadAndValidateCheckpoint(
jobId,
tasks,
testSavepoint,
cl,
false,
CheckpointProperties.forSavepoint(false, SavepointFormatType.CANONICAL));
assertThat(loaded.getJobId()).isEqualTo(jobId);
assertThat(loaded.getCheckpointID()).isEqualTo(checkpointId);
}
/** Tests that savepoint loading fails when there is a max-parallelism mismatch. */
@Test
void testMaxParallelismMismatch() throws Exception {
final OperatorID operatorId = new OperatorID();
final int parallelism = 128128;
final CompletedCheckpointStorageLocation testSavepoint =
createSavepointWithOperatorSubtaskState(242L, operatorId, parallelism);
final Map<JobVertexID, ExecutionJobVertex> tasks =
createTasks(operatorId, parallelism, parallelism + 1);
assertThatThrownBy(
() ->
Checkpoints.loadAndValidateCheckpoint(
new JobID(),
tasks,
testSavepoint,
cl,
false,
CheckpointProperties.forSavepoint(
false, SavepointFormatType.CANONICAL)))
.hasMessageContaining("Max parallelism mismatch")
.isInstanceOf(IllegalStateException.class);
}
/**
* Tests that savepoint loading fails when there is non-restored state, but it is not allowed.
*/
@Test
void testNonRestoredStateWhenDisallowed() throws Exception {
final OperatorID operatorId = new OperatorID();
final int parallelism = 9;
final CompletedCheckpointStorageLocation testSavepoint =
createSavepointWithOperatorSubtaskState(242L, operatorId, parallelism);
final Map<JobVertexID, ExecutionJobVertex> tasks = Collections.emptyMap();
assertThatThrownBy(
() ->
Checkpoints.loadAndValidateCheckpoint(
new JobID(),
tasks,
testSavepoint,
cl,
false,
CheckpointProperties.forSavepoint(
false, SavepointFormatType.CANONICAL)))
.hasMessageContaining("allowNonRestoredState")
.isInstanceOf(IllegalStateException.class);
}
/**
* Tests that savepoint loading succeeds when there is non-restored state and it is not allowed.
*/
@Test
void testNonRestoredStateWhenAllowed() throws Exception {
final OperatorID operatorId = new OperatorID();
final int parallelism = 9;
final CompletedCheckpointStorageLocation testSavepoint =
createSavepointWithOperatorSubtaskState(242L, operatorId, parallelism);
final Map<JobVertexID, ExecutionJobVertex> tasks = Collections.emptyMap();
final CompletedCheckpoint loaded =
Checkpoints.loadAndValidateCheckpoint(
new JobID(),
tasks,
testSavepoint,
cl,
true,
CheckpointProperties.forSavepoint(false, SavepointFormatType.CANONICAL));
assertThat(loaded.getOperatorStates()).isEmpty();
}
/**
* Tests that savepoint loading fails when there is non-restored coordinator state only, and
* non-restored state is not allowed.
*/
@Test
void testUnmatchedCoordinatorOnlyStateFails() throws Exception {
final OperatorID operatorID = new OperatorID();
final int maxParallelism = 1234;
final OperatorState state =
new OperatorState(null, null, operatorID, maxParallelism / 2, maxParallelism);
state.setCoordinatorState(new ByteStreamStateHandle("coordinatorState", new byte[0]));
final CompletedCheckpointStorageLocation testSavepoint =
createSavepointWithOperatorState(42L, state);
final Map<JobVertexID, ExecutionJobVertex> tasks = Collections.emptyMap();
assertThatThrownBy(
() ->
Checkpoints.loadAndValidateCheckpoint(
new JobID(),
tasks,
testSavepoint,
cl,
false,
CheckpointProperties.forSavepoint(
false, SavepointFormatType.CANONICAL)))
.hasMessageContaining("allowNonRestoredState")
.isInstanceOf(IllegalStateException.class);
}
// ------------------------------------------------------------------------
// setup utils
// ------------------------------------------------------------------------
private static CompletedCheckpointStorageLocation createSavepointWithOperatorState(
final long checkpointId, final OperatorState state) throws IOException {
final CheckpointMetadata savepoint =
new CheckpointMetadata(
checkpointId, Collections.singletonList(state), Collections.emptyList());
final StreamStateHandle serializedMetadata;
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
Checkpoints.storeCheckpointMetadata(savepoint, os);
serializedMetadata = new ByteStreamStateHandle("checkpoint", os.toByteArray());
}
return new TestCompletedCheckpointStorageLocation(serializedMetadata, "dummy/pointer");
}
private static CompletedCheckpointStorageLocation createSavepointWithOperatorSubtaskState(
final long checkpointId, final OperatorID operatorId, final int parallelism)
throws IOException {
final Random rnd = new Random();
final OperatorSubtaskState subtaskState =
OperatorSubtaskState.builder()
.setManagedOperatorState(
new OperatorStreamStateHandle(
Collections.emptyMap(),
new ByteStreamStateHandle("testHandler", new byte[0])))
.setInputChannelState(singleton(createNewInputChannelStateHandle(10, rnd)))
.setResultSubpartitionState(
singleton(createNewResultSubpartitionStateHandle(10, rnd)))
.build();
final OperatorState state =
new OperatorState(null, null, operatorId, parallelism, parallelism);
state.putState(0, subtaskState);
return createSavepointWithOperatorState(checkpointId, state);
}
private static Map<JobVertexID, ExecutionJobVertex> createTasks(
OperatorID operatorId, int parallelism, int maxParallelism) {
final JobVertexID vertexId =
new JobVertexID(operatorId.getLowerPart(), operatorId.getUpperPart());
ExecutionJobVertex vertex = mock(ExecutionJobVertex.class);
when(vertex.getParallelism()).thenReturn(parallelism);
when(vertex.getMaxParallelism()).thenReturn(maxParallelism);
when(vertex.getOperatorIDs())
.thenReturn(Collections.singletonList(OperatorIDPair.generatedIDOnly(operatorId)));
if (parallelism != maxParallelism) {
when(vertex.canRescaleMaxParallelism(anyInt())).thenReturn(false);
}
Map<JobVertexID, ExecutionJobVertex> tasks = new HashMap<>();
tasks.put(vertexId, vertex);
return tasks;
}
}
| CheckpointMetadataLoadingTest |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/inputstream/InputStreamAssert_hasBinaryContent_Test.java | {
"start": 1423,
"end": 4720
} | class ____ {
@Test
void should_fail_if_actual_is_null() {
// GIVEN
InputStream actual = null;
byte[] expected = new byte[0];
// WHEN
var assertionError = expectAssertionError(() -> assertThat(actual).hasBinaryContent(expected));
// THEN
then(assertionError).hasMessage(shouldNotBeNull().create());
}
@Test
void should_fail_if_expected_is_null() {
// GIVEN
InputStream actual = new ByteArrayInputStream(new byte[0]);
byte[] expected = null;
// WHEN
Exception exception = catchException(() -> assertThat(actual).hasBinaryContent(expected));
// THEN
then(exception).isInstanceOf(NullPointerException.class)
.hasMessage(shouldNotBeNull("expected").create());
}
@Test
void should_rethrow_IOException() throws Exception {
// GIVEN
@SuppressWarnings("resource")
InputStream actual = mock();
byte[] expected = new byte[0];
IOException cause = new IOException();
given(actual.read()).willThrow(cause);
// WHEN
Exception exception = catchException(() -> assertThat(actual).hasBinaryContent(expected));
// THEN
then(exception).isInstanceOf(UncheckedIOException.class)
.hasCause(cause);
}
@Test
void should_pass_resetting_actual_if_actual_has_expected_content_and_supports_marking() {
// GIVEN
InputStream actual = new ByteArrayInputStream("12345".getBytes());
byte[] expected = "12345".getBytes();
// WHEN
assertThat(actual).hasBinaryContent(expected);
// THEN
then(actual).isNotEmpty();
}
@Test
void should_pass_without_resetting_if_actual_has_expected_content_and_does_not_supports_marking() {
// GIVEN
InputStream actual = new UnmarkableByteArrayInputStream("12345".getBytes());
byte[] expected = "12345".getBytes();
// WHEN
assertThat(actual).hasBinaryContent(expected);
// THEN
then(actual).isEmpty();
}
@Test
void should_fail_resetting_actual_if_actual_does_not_have_expected_content_and_supports_marking() throws Exception {
// GIVEN
InputStream actual = new ByteArrayInputStream("12345".getBytes());
byte[] expected = "67890".getBytes();
// WHEN
var assertionError = expectAssertionError(() -> assertThat(actual).hasBinaryContent(expected));
// THEN
then(assertionError).hasMessage(shouldHaveBinaryContent(actual, diff("12345", "67890")).create());
then(actual.read()).isEqualTo('1');
}
@Test
void should_fail_without_resetting_if_actual_does_not_have_expected_content_and_does_not_support_marking() throws Exception {
// GIVEN
InputStream actual = new UnmarkableByteArrayInputStream("12345".getBytes());
byte[] expected = "67890".getBytes();
// WHEN
var assertionError = expectAssertionError(() -> assertThat(actual).hasBinaryContent(expected));
// THEN
then(assertionError).hasMessage(shouldHaveBinaryContent(actual, diff("12345", "67890")).create());
then(actual.read()).isEqualTo('2');
}
private static BinaryDiffResult diff(String actual, String expected) {
try {
return new BinaryDiff().diff(new ByteArrayInputStream(actual.getBytes()), expected.getBytes());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
| InputStreamAssert_hasBinaryContent_Test |
java | apache__commons-lang | src/test/java/org/apache/commons/lang3/ClassUtilsTest.java | {
"start": 4051,
"end": 13393
} | class ____ \"" + className + "\".");
}
private void assertGetClassThrowsNullPointerException(final String className) {
assertGetClassThrowsException(className, NullPointerException.class);
}
private int getDimension(final Class<?> clazz) {
Objects.requireNonNull(clazz);
if (!clazz.isArray()) {
fail("Not an array: " + clazz);
}
final String className = clazz.getName();
int dimension = 0;
for (final char c : className.toCharArray()) {
if (c != '[') {
break;
}
dimension++;
}
return dimension;
}
@Test
void test_convertClassesToClassNames_List() {
final List<Class<?>> list = new ArrayList<>();
List<String> result = ClassUtils.convertClassesToClassNames(list);
assertEquals(0, result.size());
list.add(String.class);
list.add(null);
list.add(Object.class);
result = ClassUtils.convertClassesToClassNames(list);
assertEquals(3, result.size());
assertEquals("java.lang.String", result.get(0));
assertNull(result.get(1));
assertEquals(OBJECT_CANONICAL_NAME, result.get(2));
@SuppressWarnings("unchecked") // test what happens when non-generic code adds wrong type of element
final List<Object> olist = (List<Object>) (List<?>) list;
olist.add(new Object());
assertThrows(ClassCastException.class, () -> ClassUtils.convertClassesToClassNames(list), "Should not have been able to convert list");
assertNull(ClassUtils.convertClassesToClassNames(null));
}
@Test
void test_convertClassNamesToClasses_List() {
final List<String> list = new ArrayList<>();
List<Class<?>> result = ClassUtils.convertClassNamesToClasses(list);
assertEquals(0, result.size());
list.add("java.lang.String");
list.add("java.lang.xxx");
list.add(OBJECT_CANONICAL_NAME);
result = ClassUtils.convertClassNamesToClasses(list);
assertEquals(3, result.size());
assertEquals(String.class, result.get(0));
assertNull(result.get(1));
assertEquals(Object.class, result.get(2));
@SuppressWarnings("unchecked") // test what happens when non-generic code adds wrong type of element
final List<Object> olist = (List<Object>) (List<?>) list;
olist.add(new Object());
assertThrows(ClassCastException.class, () -> ClassUtils.convertClassNamesToClasses(list), "Should not have been able to convert list");
assertNull(ClassUtils.convertClassNamesToClasses(null));
}
@Test
void test_getAbbreviatedName_Class() {
assertEquals("", ClassUtils.getAbbreviatedName((Class<?>) null, 1));
assertEquals("j.l.String", ClassUtils.getAbbreviatedName(String.class, 1));
assertEquals("j.l.String", ClassUtils.getAbbreviatedName(String.class, 5));
assertEquals("o.a.c.l.ClassUtils", ClassUtils.getAbbreviatedName(ClassUtils.class, 18));
assertEquals("j.lang.String", ClassUtils.getAbbreviatedName(String.class, 13));
assertEquals("j.lang.String", ClassUtils.getAbbreviatedName(String.class, 15));
assertEquals("java.lang.String", ClassUtils.getAbbreviatedName(String.class, 20));
}
@Test
@DisplayName("When the desired length is negative then exception is thrown")
void test_getAbbreviatedName_Class_NegativeLen() {
assertIllegalArgumentException(() -> ClassUtils.getAbbreviatedName(String.class, -10));
}
@Test
@DisplayName("When the desired length is zero then exception is thrown")
void test_getAbbreviatedName_Class_ZeroLen() {
assertIllegalArgumentException(() -> ClassUtils.getAbbreviatedName(String.class, 0));
}
@Test
void test_getAbbreviatedName_String() {
assertEquals("", ClassUtils.getAbbreviatedName((String) null, 1));
assertEquals("", ClassUtils.getAbbreviatedName("", 1));
assertEquals("WithoutPackage", ClassUtils.getAbbreviatedName("WithoutPackage", 1));
assertEquals("j.l.String", ClassUtils.getAbbreviatedName("java.lang.String", 1));
assertEquals("o.a.c.l.ClassUtils", ClassUtils.getAbbreviatedName("org.apache.commons.lang3.ClassUtils", 18));
assertEquals("org.apache.commons.lang3.ClassUtils",
ClassUtils.getAbbreviatedName("org.apache.commons.lang3.ClassUtils", "org.apache.commons.lang3.ClassUtils".length()));
assertEquals("o.a.c.l.ClassUtils", ClassUtils.getAbbreviatedName("o.a.c.l.ClassUtils", 18));
assertEquals("o..c.l.ClassUtils", ClassUtils.getAbbreviatedName("o..c.l.ClassUtils", 18));
assertEquals(".", ClassUtils.getAbbreviatedName(".", 18));
assertEquals(".", ClassUtils.getAbbreviatedName(".", 1));
assertEquals("..", ClassUtils.getAbbreviatedName("..", 1));
assertEquals("...", ClassUtils.getAbbreviatedName("...", 2));
assertEquals("...", ClassUtils.getAbbreviatedName("...", 3));
assertEquals("java.lang.String", ClassUtils.getAbbreviatedName("java.lang.String", Integer.MAX_VALUE));
assertEquals("j.lang.String", ClassUtils.getAbbreviatedName("java.lang.String", "j.lang.String".length()));
assertEquals("j.l.String", ClassUtils.getAbbreviatedName("java.lang.String", "j.lang.String".length() - 1));
assertEquals("j.l.String", ClassUtils.getAbbreviatedName("java.lang.String", "j.l.String".length()));
assertEquals("j.l.String", ClassUtils.getAbbreviatedName("java.lang.String", "j.l.String".length() - 1));
}
/**
* Test that in case the required length is larger than the name and thus there is no need for any shortening then the
* returned string object is the same as the one passed as argument. Note, however, that this is tested as an internal
* implementation detail, but it is not a guaranteed feature of the implementation.
*/
@Test
@DisplayName("When the length hint is longer than the actual length then the same String object is returned")
void test_getAbbreviatedName_TooLongHint() {
final String className = "java.lang.String";
Assertions.assertSame(className, ClassUtils.getAbbreviatedName(className, className.length() + 1));
Assertions.assertSame(className, ClassUtils.getAbbreviatedName(className, className.length()));
}
@Test
void test_getAllInterfaces_Class() {
final List<?> list = ClassUtils.getAllInterfaces(CY.class);
assertEquals(6, list.size());
assertEquals(IB.class, list.get(0));
assertEquals(IC.class, list.get(1));
assertEquals(ID.class, list.get(2));
assertEquals(IE.class, list.get(3));
assertEquals(IF.class, list.get(4));
assertEquals(IA.class, list.get(5));
assertNull(ClassUtils.getAllInterfaces(null));
}
@Test
void test_getAllSuperclasses_Class() {
final List<?> list = ClassUtils.getAllSuperclasses(CY.class);
assertEquals(2, list.size());
assertEquals(CX.class, list.get(0));
assertEquals(Object.class, list.get(1));
assertNull(ClassUtils.getAllSuperclasses(null));
}
@Test
void test_getCanonicalName_Class() {
assertEquals("org.apache.commons.lang3.ClassUtils", ClassUtils.getCanonicalName(ClassUtils.class));
assertEquals("java.util.Map.Entry", ClassUtils.getCanonicalName(Map.Entry.class));
assertEquals("", ClassUtils.getCanonicalName((Class<?>) null));
assertEquals("java.lang.String[]", ClassUtils.getCanonicalName(String[].class));
assertEquals("java.util.Map.Entry[]", ClassUtils.getCanonicalName(Map.Entry[].class));
// Primitives
assertEquals("boolean", ClassUtils.getCanonicalName(boolean.class));
assertEquals("byte", ClassUtils.getCanonicalName(byte.class));
assertEquals("char", ClassUtils.getCanonicalName(char.class));
assertEquals("short", ClassUtils.getCanonicalName(short.class));
assertEquals("int", ClassUtils.getCanonicalName(int.class));
assertEquals("long", ClassUtils.getCanonicalName(long.class));
assertEquals("float", ClassUtils.getCanonicalName(float.class));
assertEquals("double", ClassUtils.getCanonicalName(double.class));
// Primitive Arrays
assertEquals("boolean[]", ClassUtils.getCanonicalName(boolean[].class));
assertEquals("byte[]", ClassUtils.getCanonicalName(byte[].class));
assertEquals("char[]", ClassUtils.getCanonicalName(char[].class));
assertEquals("short[]", ClassUtils.getCanonicalName(short[].class));
assertEquals("int[]", ClassUtils.getCanonicalName(int[].class));
assertEquals("long[]", ClassUtils.getCanonicalName(long[].class));
assertEquals("float[]", ClassUtils.getCanonicalName(float[].class));
assertEquals("double[]", ClassUtils.getCanonicalName(double[].class));
// Arrays of arrays of ...
assertEquals("java.lang.String[][]", ClassUtils.getCanonicalName(String[][].class));
assertEquals("java.lang.String[][][]", ClassUtils.getCanonicalName(String[][][].class));
assertEquals("java.lang.String[][][][]", ClassUtils.getCanonicalName(String[][][][].class));
// Inner types
final | name |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/initializers/annotation/InitializerConfiguredViaMetaAnnotationTests.java | {
"start": 2512,
"end": 2839
} | class ____ {
@Autowired
String foo;
@Autowired
String bar;
@Autowired
List<String> strings;
@Test
public void beansFromInitializerAndComposedAnnotation() {
assertThat(strings).hasSize(2);
assertThat(foo).isEqualTo("foo");
assertThat(bar).isEqualTo("bar");
}
static | InitializerConfiguredViaMetaAnnotationTests |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/io/FileInputFormat.java | {
"start": 37529,
"end": 41422
} | class ____ extends Thread {
private final FileInputSplit split;
private final long timeout;
private volatile FSDataInputStream fdis;
private volatile Throwable error;
private volatile boolean aborted;
public InputSplitOpenThread(FileInputSplit split, long timeout) {
super("Transient InputSplit Opener");
setDaemon(true);
this.split = split;
this.timeout = timeout;
}
@Override
public void run() {
try {
final FileSystem fs = FileSystem.get(this.split.getPath().toUri());
this.fdis = fs.open(this.split.getPath());
// check for canceling and close the stream in that case, because no one will obtain
// it
if (this.aborted) {
final FSDataInputStream f = this.fdis;
this.fdis = null;
f.close();
}
} catch (Throwable t) {
this.error = t;
}
}
public FSDataInputStream waitForCompletion() throws Throwable {
final long start = System.currentTimeMillis();
long remaining = this.timeout;
do {
try {
// wait for the task completion
this.join(remaining);
} catch (InterruptedException iex) {
// we were canceled, so abort the procedure
abortWait();
throw iex;
}
} while (this.error == null
&& this.fdis == null
&& (remaining = this.timeout + start - System.currentTimeMillis()) > 0);
if (this.error != null) {
throw this.error;
}
if (this.fdis != null) {
return this.fdis;
} else {
// double-check that the stream has not been set by now. we don't know here whether
// a) the opener thread recognized the canceling and closed the stream
// b) the flag was set such that the stream did not see it and we have a valid
// stream
// In any case, close the stream and throw an exception.
abortWait();
final boolean stillAlive = this.isAlive();
final StringBuilder bld = new StringBuilder(256);
for (StackTraceElement e : this.getStackTrace()) {
bld.append("\tat ").append(e.toString()).append('\n');
}
throw new IOException(
"Input opening request timed out. Opener was "
+ (stillAlive ? "" : "NOT ")
+ " alive. Stack of split open thread:\n"
+ bld.toString());
}
}
/** Double checked procedure setting the abort flag and closing the stream. */
private void abortWait() {
this.aborted = true;
final FSDataInputStream inStream = this.fdis;
this.fdis = null;
if (inStream != null) {
try {
inStream.close();
} catch (Throwable t) {
}
}
}
}
// ============================================================================================
// Parameterization via configuration
// ============================================================================================
// ------------------------------------- Config Keys ------------------------------------------
/** The config parameter which defines the input file path. */
private static final String FILE_PARAMETER_KEY = "input.file.path";
}
| InputSplitOpenThread |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestCapacitySchedulerAutoCreatedQueueBase.java | {
"start": 10072,
"end": 39721
} | class ____ implements EventHandler<Event> {
public void handle(Event event) {
eventQueue.add(event);
}
}
@Override
protected void dispatch(Event event) {
eventQueue.add(event);
}
@Override
public EventHandler<Event> getEventHandler() {
return rmAppEventEventHandler;
}
void spyOnNextEvent(Event expectedEvent, long timeout)
throws InterruptedException {
Event event = eventQueue.poll(timeout, TimeUnit.MILLISECONDS);
assertEquals(expectedEvent.getType(), event.getType());
assertEquals(expectedEvent.getClass(), event.getClass());
}
}
@BeforeEach
public void setUp() throws Exception {
QueueMetrics.clearQueueMetrics();
CapacitySchedulerConfiguration conf = setupSchedulerConfiguration();
setupQueueConfiguration(conf);
conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class,
ResourceScheduler.class);
setupQueueMappings(conf, PARENT_QUEUE, true, new int[] { 0, 1, 2, 3 });
dispatcher = new SpyDispatcher();
rmAppEventEventHandler = new SpyDispatcher.SpyRMAppEventHandler();
dispatcher.register(RMAppEventType.class, rmAppEventEventHandler);
RMNodeLabelsManager mgr = setupNodeLabelManager(conf);
mockRM = new MockRM(conf) {
protected RMNodeLabelsManager createNodeLabelManager() {
return mgr;
}
};
cs = (CapacityScheduler) mockRM.getResourceScheduler();
cs.updatePlacementRules();
mockRM.start();
cs.start();
setupNodes(mockRM);
}
protected void setupNodes(MockRM newMockRM) throws Exception {
NodeLabel ssdLabel = Records.newRecord(NodeLabel.class);
ssdLabel.setName(NODEL_LABEL_SSD);
ssdLabel.setExclusivity(true);
nm1 = // label = SSD
new MockNM("h1:1234",
Resource.newInstance(NODE_MEMORY * GB, NODE1_VCORES),
newMockRM.getResourceTrackerService(),
YarnVersionInfo.getVersion(),
new HashSet<NodeLabel>() {{ add(ssdLabel); }});
nm1.registerNode();
NodeLabel gpuLabel = Records.newRecord(NodeLabel.class);
gpuLabel.setName(NODEL_LABEL_GPU);
gpuLabel.setExclusivity(true);
//Label = GPU
nm2 = new MockNM("h2:1234",
Resource.newInstance(NODE_MEMORY * GB, NODE2_VCORES),
newMockRM.getResourceTrackerService(),
YarnVersionInfo.getVersion(),
new HashSet<NodeLabel>() {{ add(gpuLabel); }});
nm2.registerNode();
nm3 = // label = ""
new MockNM("h3:1234", NODE_MEMORY * GB, NODE3_VCORES, newMockRM
.getResourceTrackerService
());
nm3.registerNode();
}
public static CapacitySchedulerConfiguration setupQueueMappings(
CapacitySchedulerConfiguration conf, String parentQueue, boolean
overrideWithQueueMappings, int[] userIds) {
List<String> queuePlacementRules = new ArrayList<>();
queuePlacementRules.add(YarnConfiguration.USER_GROUP_PLACEMENT_RULE);
conf.setQueuePlacementRules(queuePlacementRules);
List<QueueMapping> existingMappings = conf.getQueueMappings();
//set queue mapping
List<QueueMapping> queueMappings = new ArrayList<>();
for (int i = 0; i < userIds.length; i++) {
//Set C as parent queue name for auto queue creation
QueueMapping userQueueMapping = QueueMappingBuilder.create()
.type(QueueMapping.MappingType.USER)
.source(USER + userIds[i])
.queue(
getQueueMapping(parentQueue,
USER + userIds[i]))
.build();
queueMappings.add(userQueueMapping);
}
existingMappings.addAll(queueMappings);
conf.setQueueMappings(existingMappings);
//override with queue mappings
conf.setOverrideWithQueueMappings(overrideWithQueueMappings);
return conf;
}
public static CapacitySchedulerConfiguration setupGroupQueueMappings
(String parentQueue, CapacitySchedulerConfiguration conf, String
leafQueueName) {
List<QueueMapping> existingMappings = conf.getQueueMappings();
//set queue mapping
List<QueueMapping> queueMappings = new ArrayList<>();
//setup group mapping
conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING,
TestGroupsCaching.FakeunPrivilegedGroupMapping.class, ShellBasedUnixGroupsMapping.class);
conf.set(CommonConfigurationKeys.HADOOP_USER_GROUP_STATIC_OVERRIDES,
TEST_GROUPUSER +"=" + TEST_GROUP + ";" + TEST_GROUPUSER1 +"="
+ TEST_GROUP1 + ";" + TEST_GROUPUSER2 + "=" + TEST_GROUP2 + ";invalid_user=invalid_group");
Groups.getUserToGroupsMappingServiceWithLoadedConfiguration(conf);
QueueMapping userQueueMapping = QueueMappingBuilder.create()
.type(QueueMapping.MappingType.GROUP)
.source(TEST_GROUP)
.queue(
getQueueMapping(parentQueue,
leafQueueName))
.build();
QueueMapping userQueueMapping1 = QueueMappingBuilder.create()
.type(QueueMapping.MappingType.GROUP)
.source(TEST_GROUP1)
.queue(
getQueueMapping(parentQueue,
leafQueueName))
.build();
QueueMapping userQueueMapping2 = QueueMappingBuilder.create()
.type(QueueMapping.MappingType.GROUP)
.source(TEST_GROUP2)
.queue(
getQueueMapping(parentQueue,
leafQueueName))
.build();
queueMappings.add(userQueueMapping);
queueMappings.add(userQueueMapping1);
queueMappings.add(userQueueMapping2);
existingMappings.addAll(queueMappings);
conf.setQueueMappings(existingMappings);
return conf;
}
/**
* @param conf, to be modified
* @return, CS configuration which has C
* as an auto creation enabled parent queue
* <p>
* root
* / \ \ \
* a b c d
* / \ / | \
* a1 a2 b1 b2 b3
*/
public static CapacitySchedulerConfiguration setupQueueConfiguration(
CapacitySchedulerConfiguration conf) {
//setup new queues with one of them auto enabled
// Define top-level queues
// Set childQueue for root
conf.setQueues(ROOT,
new String[] {"a", "b", "c", "d", "esubgroup1", "esubgroup2", "fgroup",
"a1group", "ggroup", "g"});
conf.setCapacity(A, A_CAPACITY);
conf.setCapacity(B, B_CAPACITY);
conf.setCapacity(C, C_CAPACITY);
conf.setCapacity(D, D_CAPACITY);
conf.setCapacity(E_GROUP, ESUBGROUP1_CAPACITY);
conf.setCapacity(F_GROUP, FGROUP_CAPACITY);
// Define 2nd-level queues
conf.setQueues(A, new String[] { "a1", "a2" });
conf.setCapacity(A1, A1_CAPACITY);
conf.setUserLimitFactor(A1, 100.0f);
conf.setCapacity(A2, A2_CAPACITY);
conf.setUserLimitFactor(A2, 100.0f);
conf.setQueues(B, new String[] { "b1", "b2", "b3", "b4subgroup1" });
conf.setCapacity(B1, B1_CAPACITY);
conf.setUserLimitFactor(B1, 100.0f);
conf.setCapacity(B2, B2_CAPACITY);
conf.setUserLimitFactor(B2, 100.0f);
conf.setCapacity(B3, B3_CAPACITY);
conf.setUserLimitFactor(B3, 100.0f);
conf.setCapacity(B4, B4_CAPACITY);
conf.setUserLimitFactor(B4, 100.0f);
conf.setQueues(E_GROUP, new String[] {"e"});
conf.setCapacity(E_SG, 100f);
conf.setUserLimitFactor(E_SG, 100.0f);
conf.setQueues(F_GROUP, new String[] {"f"});
conf.setCapacity(F_SG, 100f);
conf.setUserLimitFactor(F_SG, 100.0f);
conf.setUserLimitFactor(C, 1.0f);
conf.setAutoCreateChildQueueEnabled(C, true);
//Setup leaf queue template configs
conf.setAutoCreatedLeafQueueConfigCapacity(C, 50.0f);
conf.setAutoCreatedLeafQueueConfigMaxCapacity(C, 100.0f);
conf.setAutoCreatedLeafQueueConfigUserLimit(C, 100);
conf.setAutoCreatedLeafQueueConfigUserLimitFactor(C, 3.0f);
conf.setAutoCreatedLeafQueueConfigUserLimitFactor(C, 3.0f);
conf.setAutoCreatedLeafQueueConfigMaximumAllocation(C,
"memory-mb=10240,vcores=6");
conf.setAutoCreatedLeafQueueTemplateCapacityByLabel(C, NODEL_LABEL_GPU,
NODE_LABEL_GPU_TEMPLATE_CAPACITY);
conf.setAutoCreatedLeafQueueTemplateMaxCapacity(C, NODEL_LABEL_GPU, 100.0f);
conf.setAutoCreatedLeafQueueTemplateCapacityByLabel(C, NODEL_LABEL_SSD,
NODEL_LABEL_SSD_TEMPLATE_CAPACITY);
conf.setAutoCreatedLeafQueueTemplateMaxCapacity(C, NODEL_LABEL_SSD,
100.0f);
conf.setDefaultNodeLabelExpression(C, NODEL_LABEL_GPU);
conf.setAutoCreatedLeafQueueConfigDefaultNodeLabelExpression
(C, NODEL_LABEL_SSD);
LOG.info("Setup " + D + " as an auto leaf creation enabled parent queue");
conf.setUserLimitFactor(D, 1.0f);
conf.setAutoCreateChildQueueEnabled(D, true);
conf.setUserLimit(D, 100);
conf.setUserLimitFactor(D, 3.0f);
//Setup leaf queue template configs
conf.setAutoCreatedLeafQueueConfigCapacity(D, 10.0f);
conf.setAutoCreatedLeafQueueConfigMaxCapacity(D, 100.0f);
conf.setAutoCreatedLeafQueueConfigUserLimit(D, 3);
conf.setAutoCreatedLeafQueueConfigUserLimitFactor(D, 100);
conf.set(CapacitySchedulerConfiguration.PREFIX + C + DOT
+ CapacitySchedulerConfiguration
.AUTO_CREATED_LEAF_QUEUE_TEMPLATE_PREFIX
+ DOT + CapacitySchedulerConfiguration.ORDERING_POLICY,
FAIR_APP_ORDERING_POLICY);
accessibleNodeLabelsOnC.add(NODEL_LABEL_GPU);
accessibleNodeLabelsOnC.add(NODEL_LABEL_SSD);
accessibleNodeLabelsOnC.add(NO_LABEL);
conf.setAccessibleNodeLabels(C, accessibleNodeLabelsOnC);
conf.setAccessibleNodeLabels(ROOT, accessibleNodeLabelsOnC);
conf.setCapacityByLabel(ROOT, NODEL_LABEL_GPU, 100f);
conf.setCapacityByLabel(ROOT, NODEL_LABEL_SSD, 100f);
conf.setAccessibleNodeLabels(C, accessibleNodeLabelsOnC);
conf.setCapacityByLabel(C, NODEL_LABEL_GPU, 100f);
conf.setCapacityByLabel(C, NODEL_LABEL_SSD, 100f);
LOG.info("Setup " + D + " as an auto leaf creation enabled parent queue");
return conf;
}
public static CapacitySchedulerConfiguration
setupQueueConfigurationForSingleAutoCreatedLeafQueue(
CapacitySchedulerConfiguration conf) {
//setup new queues with one of them auto enabled
// Define top-level queues
// Set childQueue for root
conf.setQueues(ROOT,
new String[] {"c"});
conf.setCapacity(C, 100f);
conf.setUserLimitFactor(C, 1.0f);
conf.setAutoCreateChildQueueEnabled(C, true);
//Setup leaf queue template configs
conf.setAutoCreatedLeafQueueConfigCapacity(C, 100f);
conf.setAutoCreatedLeafQueueConfigMaxCapacity(C, 100.0f);
conf.setAutoCreatedLeafQueueConfigUserLimit(C, 100);
conf.setAutoCreatedLeafQueueConfigUserLimitFactor(C, 3.0f);
return conf;
}
public static void setupQueueConfigurationForSingleFlexibleAutoCreatedLeafQueue(
CapacitySchedulerConfiguration conf) {
//setup new queues with one of them auto enabled
// Define top-level queues
// Set childQueue for root
conf.setQueues(ROOT,
new String[] {"c"});
conf.setCapacity(C, 100f);
conf.setUserLimitFactor(C, 1.0f);
conf.setAutoQueueCreationV2Enabled(C, true);
}
@AfterEach
public void tearDown() throws Exception {
if (mockRM != null) {
mockRM.stop();
}
}
protected void validateCapacities(AutoCreatedLeafQueue autoCreatedLeafQueue,
float capacity, float absCapacity, float maxCapacity,
float absMaxCapacity) {
assertEquals(capacity, autoCreatedLeafQueue.getCapacity(), EPSILON);
assertEquals(absCapacity, autoCreatedLeafQueue.getAbsoluteCapacity(),
EPSILON);
assertEquals(maxCapacity, autoCreatedLeafQueue.getMaximumCapacity(),
EPSILON);
assertEquals(absMaxCapacity,
autoCreatedLeafQueue.getAbsoluteMaximumCapacity(), EPSILON);
}
protected void cleanupQueue(String queueName) throws YarnException {
AutoCreatedLeafQueue queue = (AutoCreatedLeafQueue) cs.getQueue(queueName);
if (queue != null) {
setEntitlement(queue, new QueueEntitlement(0.0f, 0.0f));
((ManagedParentQueue) queue.getParent()).removeChildQueue(
queue.getQueuePath());
cs.getCapacitySchedulerQueueManager().removeQueue(queue.getQueuePath());
}
}
protected ApplicationId submitApp(MockRM rm, CSQueue parentQueue,
String leafQueueName, String user, int expectedNumAppsInParentQueue,
int expectedNumAppsInLeafQueue) throws Exception {
CapacityScheduler capacityScheduler =
(CapacityScheduler) rm.getResourceScheduler();
// submit an app
MockRMAppSubmissionData data =
MockRMAppSubmissionData.Builder.createWithMemory(GB, rm)
.withAppName("test-auto-queue-activation")
.withUser(user)
.withAcls(null)
.withQueue(leafQueueName)
.withUnmanagedAM(false)
.build();
RMApp rmApp = MockRMAppSubmitter.submit(rm, data);
// check preconditions
List<ApplicationAttemptId> appsInParentQueue =
capacityScheduler.getAppsInQueue(parentQueue.getQueuePath());
assertEquals(expectedNumAppsInParentQueue, appsInParentQueue.size());
List<ApplicationAttemptId> appsInLeafQueue =
capacityScheduler.getAppsInQueue(leafQueueName);
assertEquals(expectedNumAppsInLeafQueue, appsInLeafQueue.size());
return rmApp.getApplicationId();
}
protected List<QueueMapping> setupQueueMapping(
CapacityScheduler newCS, String user, String parentQueue, String queue) {
List<QueueMapping> queueMappings = new ArrayList<>();
queueMappings.add(QueueMappingBuilder.create()
.type(QueueMapping.MappingType.USER)
.source(user)
.queue(getQueueMapping(parentQueue, queue))
.build());
newCS.getConfiguration().setQueueMappings(queueMappings);
return queueMappings;
}
protected CapacitySchedulerConfiguration setupSchedulerConfiguration() {
Configuration schedConf = new Configuration();
schedConf.setInt(YarnConfiguration.RESOURCE_TYPES
+ ".vcores.minimum-allocation", 1);
schedConf.setInt(YarnConfiguration.RESOURCE_TYPES
+ ".vcores.maximum-allocation", 8);
schedConf.setInt(YarnConfiguration.RESOURCE_TYPES
+ ".memory-mb.minimum-allocation", 1024);
schedConf.setInt(YarnConfiguration.RESOURCE_TYPES
+ ".memory-mb.maximum-allocation", 16384);
return new CapacitySchedulerConfiguration(schedConf);
}
protected void setSchedulerMinMaxAllocation(CapacitySchedulerConfiguration conf) {
unsetMinMaxAllocation(conf);
conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES, 1);
conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, 8);
conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 1024);
conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, 18384);
}
private void unsetMinMaxAllocation(CapacitySchedulerConfiguration conf) {
conf.unset(YarnConfiguration.RESOURCE_TYPES
+ ".vcores.minimum-allocation");
conf.unset(YarnConfiguration.RESOURCE_TYPES
+ ".vcores.maximum-allocation");
conf.unset(YarnConfiguration.RESOURCE_TYPES
+ ".memory-mb.minimum-allocation");
conf.unset(YarnConfiguration.RESOURCE_TYPES
+ ".memory-mb.maximum-allocation");
}
protected MockRM setupSchedulerInstance() throws Exception {
if (mockRM != null) {
mockRM.stop();
}
CapacitySchedulerConfiguration conf = setupSchedulerConfiguration();
setupQueueConfiguration(conf);
conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class,
ResourceScheduler.class);
setupQueueMappings(conf, PARENT_QUEUE, true, new int[] {0, 1, 2, 3});
RMNodeLabelsManager mgr = setupNodeLabelManager(conf);
MockRM newMockRM = new MockRM(conf) {
protected RMNodeLabelsManager createNodeLabelManager() {
return mgr;
}
};
newMockRM.start();
((CapacityScheduler) newMockRM.getResourceScheduler()).start();
setupNodes(newMockRM);
return newMockRM;
}
static String getQueueMapping(String parentQueue, String leafQueue) {
return parentQueue + DOT + leafQueue;
}
protected RMNodeLabelsManager setupNodeLabelManager(
CapacitySchedulerConfiguration conf) throws IOException {
final RMNodeLabelsManager mgr = new NullRMNodeLabelsManager();
mgr.init(conf);
mgr.addToCluserNodeLabelsWithDefaultExclusivity(
ImmutableSet.of(NODEL_LABEL_SSD, NODEL_LABEL_GPU));
mgr.addLabelsToNode(ImmutableMap
.of(NodeId.newInstance("h1", 0),
TestUtils.toSet(NODEL_LABEL_SSD)));
mgr.addLabelsToNode(ImmutableMap
.of(NodeId.newInstance("h2", 0),
TestUtils.toSet(NODEL_LABEL_GPU)));
return mgr;
}
protected ApplicationAttemptId submitApp(CapacityScheduler newCS, String user,
String queue, String parentQueue) {
ApplicationId appId = BuilderUtils.newApplicationId(1, 1);
SchedulerEvent addAppEvent = new AppAddedSchedulerEvent(appId, queue, user,
new ApplicationPlacementContext(queue, parentQueue));
ApplicationAttemptId appAttemptId = BuilderUtils.newApplicationAttemptId(
appId, 1);
SchedulerEvent addAttemptEvent = new AppAttemptAddedSchedulerEvent(
appAttemptId, false);
newCS.handle(addAppEvent);
newCS.handle(addAttemptEvent);
return appAttemptId;
}
protected RMApp submitApp(String user, String queue, String nodeLabel)
throws Exception {
MockRMAppSubmissionData data =
MockRMAppSubmissionData.Builder.createWithMemory(GB, mockRM)
.withAppName("test-auto-queue-creation" + RandomUtils.nextInt(0, 100))
.withUser(user)
.withAcls(null)
.withQueue(queue)
.withAmLabel(nodeLabel)
.build();
RMApp app = MockRMAppSubmitter.submit(mockRM, data);
assertEquals(app.getAmNodeLabelExpression(), nodeLabel);
// check preconditions
List<ApplicationAttemptId> appsInC = cs.getAppsInQueue(PARENT_QUEUE);
assertEquals(1, appsInC.size());
assertNotNull(cs.getQueue(queue));
return app;
}
void setEntitlement(AutoCreatedLeafQueue queue,
QueueEntitlement entitlement) {
queue.setCapacity(entitlement.getCapacity());
queue.setAbsoluteCapacity(
queue.getParent().getAbsoluteCapacity() * entitlement.getCapacity());
// note: we currently set maxCapacity to capacity
// this might be revised later
queue.setMaxCapacity(entitlement.getMaxCapacity());
}
protected void validateUserAndAppLimits(
AutoCreatedLeafQueue autoCreatedLeafQueue, int maxApps,
int maxAppsPerUser) {
assertEquals(maxApps, autoCreatedLeafQueue.getMaxApplications());
assertEquals(maxAppsPerUser,
autoCreatedLeafQueue.getMaxApplicationsPerUser());
}
protected void validateContainerLimits(
AutoCreatedLeafQueue autoCreatedLeafQueue, int vCoreLimit,
long memorySize) {
assertEquals(vCoreLimit,
autoCreatedLeafQueue.getMaximumAllocation().getVirtualCores());
assertEquals(memorySize,
autoCreatedLeafQueue.getMaximumAllocation().getMemorySize());
}
protected void validateInitialQueueEntitlement(CSQueue parentQueue,
String leafQueueName,
Map<String, Float> expectedTotalChildQueueAbsCapacityByLabel,
Set<String> nodeLabels)
throws SchedulerDynamicEditException, InterruptedException {
validateInitialQueueEntitlement(mockRM, cs, parentQueue, leafQueueName,
expectedTotalChildQueueAbsCapacityByLabel, nodeLabels);
}
protected void validateInitialQueueEntitlement(ResourceManager rm,
CSQueue parentQueue, String leafQueueName,
Map<String, Float> expectedTotalChildQueueAbsCapacityByLabel,
Set<String> nodeLabels)
throws SchedulerDynamicEditException, InterruptedException {
validateInitialQueueEntitlement(rm,
(CapacityScheduler) rm.getResourceScheduler(), parentQueue,
leafQueueName, expectedTotalChildQueueAbsCapacityByLabel, nodeLabels);
}
protected void validateInitialQueueEntitlement(ResourceManager rm,
CapacityScheduler capacityScheduler, CSQueue parentQueue,
String leafQueueName,
Map<String, Float> expectedTotalChildQueueAbsCapacityByLabel,
Set<String> nodeLabels)
throws SchedulerDynamicEditException, InterruptedException {
ManagedParentQueue autoCreateEnabledParentQueue =
(ManagedParentQueue) parentQueue;
GuaranteedOrZeroCapacityOverTimePolicy policy =
(GuaranteedOrZeroCapacityOverTimePolicy) autoCreateEnabledParentQueue
.getAutoCreatedQueueManagementPolicy();
AutoCreatedLeafQueue leafQueue =
(AutoCreatedLeafQueue) capacityScheduler.getQueue(leafQueueName);
Map<String, QueueEntitlement> expectedEntitlements = new HashMap<>();
QueueCapacities cap = autoCreateEnabledParentQueue.getLeafQueueTemplate()
.getQueueCapacities();
for (String label : nodeLabels) {
validateCapacitiesByLabel(autoCreateEnabledParentQueue, leafQueue, label);
assertEquals(true, policy.isActive(leafQueue, label));
assertEquals(expectedTotalChildQueueAbsCapacityByLabel.get(label),
policy.getAbsoluteActivatedChildQueueCapacity(label), EPSILON);
QueueEntitlement expectedEntitlement = new QueueEntitlement(
cap.getCapacity(label), cap.getMaximumCapacity(label));
expectedEntitlements.put(label, expectedEntitlement);
validateEffectiveMinResource(rm, capacityScheduler, leafQueue, label,
expectedEntitlements);
}
}
protected void validateCapacitiesByLabel(ManagedParentQueue
autoCreateEnabledParentQueue, AutoCreatedLeafQueue leafQueue, String
label) throws InterruptedException {
assertEquals(autoCreateEnabledParentQueue.getLeafQueueTemplate()
.getQueueCapacities().getCapacity(label),
leafQueue.getQueueCapacities()
.getCapacity(label), EPSILON);
assertEquals(autoCreateEnabledParentQueue.getLeafQueueTemplate()
.getQueueCapacities().getMaximumCapacity(label),
leafQueue.getQueueCapacities()
.getMaximumCapacity(label), EPSILON);
}
protected void validateEffectiveMinResource(ResourceManager rm,
CapacityScheduler cs, CSQueue leafQueue, String label,
Map<String, QueueEntitlement> expectedQueueEntitlements) {
ManagedParentQueue parentQueue = (ManagedParentQueue) leafQueue.getParent();
Resource resourceByLabel = rm.getRMContext().getNodeLabelManager()
.getResourceByLabel(label, cs.getClusterResource());
Resource effMinCapacity = Resources.multiply(resourceByLabel,
expectedQueueEntitlements.get(label).getCapacity()
* parentQueue.getQueueCapacities().getAbsoluteCapacity(label));
assertEquals(effMinCapacity, Resources.multiply(resourceByLabel,
leafQueue.getQueueCapacities().getAbsoluteCapacity(label)));
if (expectedQueueEntitlements.get(label).getCapacity() > EPSILON) {
if (leafQueue.getCapacityConfigType().equals(ABSOLUTE_RESOURCE)) {
QueuePath templatePrefix = QueuePrefixes.getAutoCreatedQueueObjectTemplateConfPrefix(
parentQueue.getQueuePathObject());
Resource resourceTemplate = parentQueue.getLeafQueueTemplate().getLeafQueueConfigs()
.getMinimumResourceRequirement(label, templatePrefix, RESOURCE_TYPES);
assertEquals(resourceTemplate, leafQueue.getEffectiveCapacity(label));
} else {
assertEquals(effMinCapacity, leafQueue.getEffectiveCapacity(label));
}
} else {
assertEquals(Resource.newInstance(0, 0),
leafQueue.getEffectiveCapacity(label));
}
if (leafQueue.getQueueCapacities().getAbsoluteCapacity(label) > 0) {
assertTrue(Resources.greaterThan(cs.getResourceCalculator(),
cs.getClusterResource(), effMinCapacity, Resources.none()));
} else {
assertTrue(Resources.equals(effMinCapacity, Resources.none()));
}
}
protected void validateActivatedQueueEntitlement(CSQueue parentQueue,
String leafQueueName, Map<String, Float>
expectedTotalChildQueueAbsCapacity,
List<QueueManagementChange> queueManagementChanges, Set<String>
expectedNodeLabels)
throws SchedulerDynamicEditException {
ManagedParentQueue autoCreateEnabledParentQueue =
(ManagedParentQueue) parentQueue;
GuaranteedOrZeroCapacityOverTimePolicy policy =
(GuaranteedOrZeroCapacityOverTimePolicy) autoCreateEnabledParentQueue
.getAutoCreatedQueueManagementPolicy();
QueueCapacities cap = autoCreateEnabledParentQueue.getLeafQueueTemplate()
.getQueueCapacities();
AutoCreatedLeafQueue leafQueue = (AutoCreatedLeafQueue)
cs.getQueue(leafQueueName);
Map<String, QueueEntitlement> expectedEntitlements = new HashMap<>();
for (String label : expectedNodeLabels) {
//validate leaf queue state
assertEquals(true, policy.isActive(leafQueue, label));
QueueEntitlement expectedEntitlement = new QueueEntitlement(
cap.getCapacity(label), cap.getMaximumCapacity(label));
//validate parent queue state
assertEquals(expectedTotalChildQueueAbsCapacity.get(label),
policy.getAbsoluteActivatedChildQueueCapacity(label), EPSILON);
expectedEntitlements.put(label, expectedEntitlement);
}
//validate capacity
validateQueueEntitlements(leafQueueName, expectedEntitlements,
queueManagementChanges, expectedNodeLabels);
}
protected void validateDeactivatedQueueEntitlement(CSQueue parentQueue,
String leafQueueName, Map<String, Float>
expectedTotalChildQueueAbsCapacity,
List<QueueManagementChange>
queueManagementChanges)
throws SchedulerDynamicEditException {
QueueEntitlement expectedEntitlement =
new QueueEntitlement(0.0f, 1.0f);
ManagedParentQueue autoCreateEnabledParentQueue =
(ManagedParentQueue) parentQueue;
AutoCreatedLeafQueue leafQueue =
(AutoCreatedLeafQueue) cs.getQueue(leafQueueName);
GuaranteedOrZeroCapacityOverTimePolicy policy =
(GuaranteedOrZeroCapacityOverTimePolicy) autoCreateEnabledParentQueue
.getAutoCreatedQueueManagementPolicy();
Map<String, QueueEntitlement> expectedEntitlements = new HashMap<>();
for (String label : accessibleNodeLabelsOnC) {
//validate parent queue state
LOG.info("Validating label " + label);
assertEquals(expectedTotalChildQueueAbsCapacity.get(label), policy
.getAbsoluteActivatedChildQueueCapacity(label), EPSILON);
//validate leaf queue state
assertEquals(false, policy.isActive(leafQueue, label));
expectedEntitlements.put(label, expectedEntitlement);
}
//validate capacity
validateQueueEntitlements(leafQueueName, expectedEntitlements,
queueManagementChanges, accessibleNodeLabelsOnC);
}
void validateQueueEntitlements(String leafQueueName,
Map<String, QueueEntitlement> expectedEntitlements,
List<QueueManagementChange>
queueEntitlementChanges, Set<String> expectedNodeLabels) {
AutoCreatedLeafQueue leafQueue = (AutoCreatedLeafQueue) cs.getQueue(
leafQueueName);
validateQueueEntitlementChanges(leafQueue, expectedEntitlements,
queueEntitlementChanges, expectedNodeLabels);
}
private void validateQueueEntitlementChanges(AutoCreatedLeafQueue leafQueue,
Map<String, QueueEntitlement> expectedQueueEntitlements,
final List<QueueManagementChange> queueEntitlementChanges, Set<String>
expectedNodeLabels) {
boolean found = false;
for (QueueManagementChange entitlementChange : queueEntitlementChanges) {
if (leafQueue.getQueuePath().equals(
entitlementChange.getQueue().getQueuePath())) {
AutoCreatedLeafQueueConfig updatedQueueTemplate =
entitlementChange.getUpdatedQueueTemplate();
for (String label : expectedNodeLabels) {
QueueEntitlement newEntitlement = new QueueEntitlement(
updatedQueueTemplate.getQueueCapacities().getCapacity(label),
updatedQueueTemplate.getQueueCapacities().getMaximumCapacity
(label));
assertEquals(expectedQueueEntitlements.get(label), newEntitlement);
validateEffectiveMinResource(mockRM, cs, leafQueue, label,
expectedQueueEntitlements);
}
found = true;
break;
}
}
if (!found) {
fail(
"Could not find the specified leaf queue in entitlement changes : "
+ leafQueue.getQueuePath());
}
}
protected Map<String, Float> populateExpectedAbsCapacityByLabelForParentQueue
(int numLeafQueues) {
Map<String, Float> expectedChildQueueAbsCapacity = new HashMap<>();
expectedChildQueueAbsCapacity.put(NODEL_LABEL_GPU,
NODE_LABEL_GPU_TEMPLATE_CAPACITY/100 * numLeafQueues);
expectedChildQueueAbsCapacity.put(NODEL_LABEL_SSD,
NODEL_LABEL_SSD_TEMPLATE_CAPACITY/100 * numLeafQueues);
expectedChildQueueAbsCapacity.put(NO_LABEL, 0.1f * numLeafQueues);
return expectedChildQueueAbsCapacity;
}
}
| SpyRMAppEventHandler |
java | google__guice | extensions/servlet/src/com/google/inject/servlet/ServletScopes.java | {
"start": 5188,
"end": 16067
} | class ____ implements Scope {
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) {
final String name = key.toString();
return new Provider<T>() {
@Override
public T get() {
HttpSession session = GuiceFilter.getRequest(key).getSession();
synchronized (session) {
Object obj = session.getAttribute(name);
if (NullObject.INSTANCE == obj) {
return null;
}
@SuppressWarnings("unchecked")
T t = (T) obj;
if (t == null) {
t = creator.get();
if (!Scopes.isCircularProxy(t)) {
session.setAttribute(name, (t != null) ? t : NullObject.INSTANCE);
}
}
return t;
}
}
@Override
public String toString() {
return String.format("%s[%s]", creator, SESSION);
}
};
}
@Override
public String toString() {
return "ServletScopes.SESSION";
}
}
/**
* Wraps the given callable in a contextual callable that "continues" the HTTP request in another
* thread. This acts as a way of transporting request context data from the request processing
* thread to to worker threads.
*
* <p>There are some limitations:
*
* <ul>
* <li>Derived objects (i.e. anything marked @RequestScoped will not be transported.
* <li>State changes to the HttpServletRequest after this method is called will not be seen in the
* continued thread.
* <li>Only the HttpServletRequest, ServletContext and request parameter map are available in the
* continued thread. The response and session are not available.
* </ul>
*
* <p>The returned callable will throw a {@link ScopingException} when called if the HTTP request
* scope is still active on the current thread.
*
* @param callable code to be executed in another thread, which depends on the request scope.
* @param seedMap the initial set of scoped instances for Guice to seed the request scope with. To
* seed a key with null, use {@code null} as the value.
* @return a callable that will invoke the given callable, making the request context available to
* it.
* @throws OutOfScopeException if this method is called from a non-request thread, or if the
* request has completed.
* @since 3.0
* @deprecated You probably want to use {@code transferRequest} instead
*/
@Deprecated
public static <T> Callable<T> continueRequest(Callable<T> callable, Map<Key<?>, Object> seedMap) {
return wrap(callable, continueRequest(seedMap));
}
private static RequestScoper continueRequest(Map<Key<?>, Object> seedMap) {
Preconditions.checkArgument(
null != seedMap, "Seed map cannot be null, try passing in Collections.emptyMap() instead.");
// Snapshot the seed map and add all the instances to our continuing HTTP request.
final ContinuingHttpServletRequest continuingRequest =
new ContinuingHttpServletRequest(GuiceFilter.getRequest(Key.get(HttpServletRequest.class)));
for (Map.Entry<Key<?>, Object> entry : seedMap.entrySet()) {
Object value = validateAndCanonicalizeValue(entry.getKey(), entry.getValue());
continuingRequest.setAttribute(entry.getKey().toString(), value);
}
return new RequestScoper() {
@Override
public CloseableScope open() {
checkScopingState(
null == GuiceFilter.localContext.get(),
"Cannot continue request in the same thread as a HTTP request!");
return new GuiceFilter.Context(continuingRequest, continuingRequest, null).open();
}
};
}
/**
* Wraps the given callable in a contextual callable that "transfers" the request to another
* thread. This acts as a way of transporting request context data from the current thread to a
* future thread.
*
* <p>As opposed to {@link #continueRequest}, this method propagates all existing scoped objects.
* The primary use case is in server implementations where you can detach the request processing
* thread while waiting for data, and reattach to a different thread to finish processing at a
* later time.
*
* <p>Because request-scoped objects are not typically thread-safe, the callable returned by this
* method must not be run on a different thread until the current request scope has terminated.
* The returned callable will block until the current thread has released the request scope.
*
* @param callable code to be executed in another thread, which depends on the request scope.
* @return a callable that will invoke the given callable, making the request context available to
* it.
* @throws OutOfScopeException if this method is called from a non-request thread, or if the
* request has completed.
* @since 4.0
*/
public static <T> Callable<T> transferRequest(Callable<T> callable) {
return wrap(callable, transferRequest());
}
/**
* Returns an object that "transfers" the request to another thread. This acts as a way of
* transporting request context data from the current thread to a future thread. The transferred
* scope is the one active for the thread that calls this method. A later call to {@code open()}
* activates the transferred the scope, including propagating any objects scoped at that time.
*
* <p>As opposed to {@link #continueRequest}, this method propagates all existing scoped objects.
* The primary use case is in server implementations where you can detach the request processing
* thread while waiting for data, and reattach to a different thread to finish processing at a
* later time.
*
* <p>Because request-scoped objects are not typically thread-safe, it is important to avoid
* applying the same request scope concurrently. The returned Scoper will block on open until the
* current thread has released the request scope.
*
* @return an object that when opened will initiate the request scope
* @throws OutOfScopeException if this method is called from a non-request thread, or if the
* request has completed.
* @since 4.1
*/
public static RequestScoper transferRequest() {
return (GuiceFilter.localContext.get() != null)
? transferHttpRequest()
: transferNonHttpRequest();
}
private static RequestScoper transferHttpRequest() {
final GuiceFilter.Context context = GuiceFilter.localContext.get();
if (context == null) {
throw new OutOfScopeException("Not in a request scope");
}
return context;
}
private static RequestScoper transferNonHttpRequest() {
final Context context = requestScopeContext.get();
if (context == null) {
throw new OutOfScopeException("Not in a request scope");
}
return context;
}
/**
* Returns true if {@code binding} is request-scoped. If the binding is a {@link
* com.google.inject.spi.LinkedKeyBinding linked key binding} and belongs to an injector (i. e. it
* was retrieved via {@link Injector#getBinding Injector.getBinding()}), then this method will
* also return true if the target binding is request-scoped.
*
* @since 4.0
*/
public static boolean isRequestScoped(Binding<?> binding) {
return Scopes.isScoped(binding, ServletScopes.REQUEST, RequestScoped.class);
}
/**
* Scopes the given callable inside a request scope. This is not the same as the HTTP request
* scope, but is used if no HTTP request scope is in progress. In this way, keys can be scoped
* as @RequestScoped and exist in non-HTTP requests (for example: RPC requests) as well as in HTTP
* request threads.
*
* <p>The returned callable will throw a {@link ScopingException} when called if there is a
* request scope already active on the current thread.
*
* @param callable code to be executed which depends on the request scope. Typically in another
* thread, but not necessarily so.
* @param seedMap the initial set of scoped instances for Guice to seed the request scope with. To
* seed a key with null, use {@code null} as the value.
* @return a callable that when called will run inside the a request scope that exposes the
* instances in the {@code seedMap} as scoped keys.
* @since 3.0
*/
public static <T> Callable<T> scopeRequest(Callable<T> callable, Map<Key<?>, Object> seedMap) {
return wrap(callable, scopeRequest(seedMap));
}
/**
* Returns an object that will apply request scope to a block of code. This is not the same as the
* HTTP request scope, but is used if no HTTP request scope is in progress. In this way, keys can
* be scoped as @RequestScoped and exist in non-HTTP requests (for example: RPC requests) as well
* as in HTTP request threads.
*
* <p>The returned object will throw a {@link ScopingException} when opened if there is a request
* scope already active on the current thread.
*
* @param seedMap the initial set of scoped instances for Guice to seed the request scope with. To
* seed a key with null, use {@code null} as the value.
* @return an object that when opened will initiate the request scope
* @since 4.1
*/
public static RequestScoper scopeRequest(Map<Key<?>, Object> seedMap) {
Preconditions.checkArgument(
null != seedMap, "Seed map cannot be null, try passing in Collections.emptyMap() instead.");
// Copy the seed values into our local scope map.
final Context context = new Context();
Map<Key<?>, Object> validatedAndCanonicalizedMap =
Maps.transformEntries(seedMap, ServletScopes::validateAndCanonicalizeValue);
context.map.putAll(validatedAndCanonicalizedMap);
return new RequestScoper() {
@Override
public CloseableScope open() {
checkScopingState(
null == GuiceFilter.localContext.get(),
"An HTTP request is already in progress, cannot scope a new request in this thread.");
checkScopingState(
null == requestScopeContext.get(),
"A request scope is already in progress, cannot scope a new request in this thread.");
return context.open();
}
};
}
/**
* Validates the key and object, ensuring the value matches the key type, and canonicalizing null
* objects to the null sentinel.
*/
private static Object validateAndCanonicalizeValue(Key<?> key, Object object) {
if (object == null || object == NullObject.INSTANCE) {
return NullObject.INSTANCE;
}
Preconditions.checkArgument(
key.getTypeLiteral().getRawType().isInstance(object),
"Value[%s] of type[%s] is not compatible with key[%s]",
object,
object.getClass().getName(),
key);
return object;
}
private static | SessionScope |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/ingest/ValueSource.java | {
"start": 6210,
"end": 6902
} | class ____ implements ValueSource {
private final byte[] value;
ByteValue(byte[] value) {
this.value = value;
}
@Override
public Object copyAndResolve(Map<String, Object> model) {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ByteValue objectValue = (ByteValue) o;
return Arrays.equals(value, objectValue.value);
}
@Override
public int hashCode() {
return Arrays.hashCode(value);
}
}
final | ByteValue |
java | quarkusio__quarkus | integration-tests/jpa/src/main/java/io/quarkus/it/jpa/attributeconverter/MyDataNotRequiringCDI.java | {
"start": 60,
"end": 280
} | class ____ {
private final String content;
public MyDataNotRequiringCDI(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
| MyDataNotRequiringCDI |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/form/ClientFormParamFromPropertyTest.java | {
"start": 798,
"end": 2424
} | class ____ {
private static final String FORM_VALUE = "foo";
@TestHTTPResource
URI baseUri;
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar.addClasses(Client.class, Resource.class)
.addAsResource(
new StringAsset("my.property-value=" + FORM_VALUE),
"application.properties"));
@Test
void shouldSetFromProperties() {
Client client = RestClientBuilder.newBuilder().baseUri(baseUri)
.build(Client.class);
assertThat(client.getWithParam()).isEqualTo(FORM_VALUE);
}
@Test
void shouldFailOnMissingRequiredProperty() {
Client client = RestClientBuilder.newBuilder().baseUri(baseUri)
.build(Client.class);
assertThatThrownBy(client::missingRequiredProperty)
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void shouldSucceedOnMissingNonRequiredProperty() {
Client client = RestClientBuilder.newBuilder().baseUri(baseUri)
.build(Client.class);
assertThat(client.missingNonRequiredProperty()).isEqualTo(FORM_VALUE);
}
@Test
void shouldSucceedOnMissingNonRequiredPropertyAndUseOverriddenValue() {
Client client = RestClientBuilder.newBuilder().baseUri(baseUri)
.build(Client.class);
assertThat(client.missingNonRequiredPropertyAndOverriddenValue()).isEqualTo("other");
}
@Path("/")
@ApplicationScoped
public static | ClientFormParamFromPropertyTest |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/appender/db/jdbc/DataSourceConnectionSource.java | {
"start": 1681,
"end": 3750
} | class ____ extends AbstractConnectionSource {
private static final Logger LOGGER = StatusLogger.getLogger();
private final DataSource dataSource;
private final String description;
private DataSourceConnectionSource(final String dataSourceName, final DataSource dataSource) {
this.dataSource = Objects.requireNonNull(dataSource, "dataSource");
this.description = "dataSource{ name=" + dataSourceName + ", value=" + dataSource + " }";
}
@Override
public Connection getConnection() throws SQLException {
return this.dataSource.getConnection();
}
@Override
public String toString() {
return this.description;
}
/**
* Factory method for creating a connection source within the plugin manager.
*
* @param jndiName The full JNDI path where the data source is bound. Must start with java:/comp/env or environment-equivalent.
* @return the created connection source.
*/
@PluginFactory
public static DataSourceConnectionSource createConnectionSource(
@PluginAttribute("jndiName") final String jndiName) {
if (!JndiManager.isJndiJdbcEnabled()) {
LOGGER.error("JNDI must be enabled by setting log4j2.enableJndiJdbc=true");
return null;
}
if (Strings.isEmpty(jndiName)) {
LOGGER.error("No JNDI name provided.");
return null;
}
try {
@SuppressWarnings("resource")
final DataSource dataSource = JndiManager.getDefaultManager(
DataSourceConnectionSource.class.getCanonicalName())
.lookup(jndiName);
if (dataSource == null) {
LOGGER.error("No DataSource found with JNDI name [" + jndiName + "].");
return null;
}
return new DataSourceConnectionSource(jndiName, dataSource);
} catch (final NamingException e) {
LOGGER.error(e.getMessage(), e);
return null;
}
}
}
| DataSourceConnectionSource |
java | spring-projects__spring-boot | module/spring-boot-webservices/src/main/java/org/springframework/boot/webservices/client/WebServiceMessageSenderFactory.java | {
"start": 1264,
"end": 2927
} | interface ____ {
/**
* Return a new {@link WebServiceMessageSender} instance.
* @return the web service message sender
*/
WebServiceMessageSender getWebServiceMessageSender();
/**
* Returns a factory that will create a {@link ClientHttpRequestMessageSender} backed
* by a detected {@link ClientHttpRequestFactory}.
* @return a new {@link WebServiceMessageSenderFactory}
*/
static WebServiceMessageSenderFactory http() {
return http(ClientHttpRequestFactoryBuilder.detect(), null);
}
/**
* Returns a factory that will create a {@link ClientHttpRequestMessageSender} backed
* by a detected {@link ClientHttpRequestFactory}.
* @param clientSettings the setting to apply
* @return a new {@link WebServiceMessageSenderFactory}
*/
static WebServiceMessageSenderFactory http(HttpClientSettings clientSettings) {
return http(ClientHttpRequestFactoryBuilder.detect(), clientSettings);
}
/**
* Returns a factory that will create a {@link ClientHttpRequestMessageSender} backed
* by a {@link ClientHttpRequestFactory} created from the given
* {@link ClientHttpRequestFactoryBuilder}.
* @param requestFactoryBuilder the request factory builder to use
* @param clientSettings the settings to apply
* @return a new {@link WebServiceMessageSenderFactory}
*/
static WebServiceMessageSenderFactory http(ClientHttpRequestFactoryBuilder<?> requestFactoryBuilder,
@Nullable HttpClientSettings clientSettings) {
Assert.notNull(requestFactoryBuilder, "'requestFactoryBuilder' must not be null");
return () -> new ClientHttpRequestMessageSender(requestFactoryBuilder.build(clientSettings));
}
}
| WebServiceMessageSenderFactory |
java | spring-projects__spring-boot | core/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReport.java | {
"start": 1020,
"end": 4152
} | class ____ {
private final Map<String, LegacyProperties> content = new LinkedHashMap<>();
/**
* Return a report for all the properties that were automatically renamed. If no such
* properties were found, return {@code null}.
* @return a report with the configurations keys that should be renamed
*/
@Nullable String getWarningReport() {
Map<String, List<PropertyMigration>> content = getContent(LegacyProperties::getRenamed);
if (content.isEmpty()) {
return null;
}
StringBuilder report = new StringBuilder();
report.append(String
.format("%nThe use of configuration keys that have been renamed was found in the environment:%n%n"));
append(report, content);
report.append(String.format("%n"));
report.append("Each configuration key has been temporarily mapped to its "
+ "replacement for your convenience. To silence this warning, please "
+ "update your configuration to use the new keys.");
report.append(String.format("%n"));
return report.toString();
}
/**
* Return a report for all the properties that are no longer supported. If no such
* properties were found, return {@code null}.
* @return a report with the configurations keys that are no longer supported
*/
@Nullable String getErrorReport() {
Map<String, List<PropertyMigration>> content = getContent(LegacyProperties::getUnsupported);
if (content.isEmpty()) {
return null;
}
StringBuilder report = new StringBuilder();
report.append(String
.format("%nThe use of configuration keys that are no longer supported was found in the environment:%n%n"));
append(report, content);
report.append(String.format("%n"));
report.append("Please refer to the release notes or reference guide for potential alternatives.");
report.append(String.format("%n"));
return report.toString();
}
private Map<String, List<PropertyMigration>> getContent(
Function<LegacyProperties, List<PropertyMigration>> extractor) {
return this.content.entrySet()
.stream()
.filter((entry) -> !extractor.apply(entry.getValue()).isEmpty())
.collect(
Collectors.toMap(Map.Entry::getKey, (entry) -> new ArrayList<>(extractor.apply(entry.getValue()))));
}
private void append(StringBuilder report, Map<String, List<PropertyMigration>> content) {
content.forEach((name, properties) -> {
report.append(String.format("Property source '%s':%n", name));
properties.sort(PropertyMigration.COMPARATOR);
properties.forEach((property) -> {
report.append(String.format("\tKey: %s%n", property.getProperty().getName()));
if (property.getLineNumber() != null) {
report.append(String.format("\t\tLine: %d%n", property.getLineNumber()));
}
report.append(String.format("\t\t%s%n", property.determineReason()));
});
report.append(String.format("%n"));
});
}
/**
* Register a new property source.
* @param name the name of the property source
* @param properties the {@link PropertyMigration} instances
*/
void add(String name, List<PropertyMigration> properties) {
this.content.put(name, new LegacyProperties(properties));
}
private static | PropertiesMigrationReport |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/stats/Locality.java | {
"start": 175,
"end": 706
} | class ____ {
private Long id;
private String name;
private Country country;
public Locality() {
}
public Locality(String name, Country country) {
this.name = name;
this.country = country;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
}
| Locality |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/azureaistudio/request/AzureAiStudioChatCompletionRequestTests.java | {
"start": 1344,
"end": 19686
} | class ____ extends ESTestCase {
public void testCreateRequest_WithOpenAiProviderTokenEndpoint_NoParams() throws IOException {
var request = createRequest(
"http://openaitarget.local",
AzureAiStudioProvider.OPENAI,
AzureAiStudioEndpointType.TOKEN,
"apikey",
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://openaitarget.local");
validateRequestApiKey(httpPost, AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(1));
assertThat(requestMap.get("messages"), is(List.of(Map.of("role", "user", "content", "abcd"))));
}
public void testCreateRequest_WithOpenAiProviderTokenEndpoint_WithTemperatureParam() throws IOException {
var request = createRequest(
"http://openaitarget.local",
AzureAiStudioProvider.OPENAI,
AzureAiStudioEndpointType.TOKEN,
"apikey",
1.0,
null,
null,
null,
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://openaitarget.local");
validateRequestApiKey(httpPost, AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(2));
assertThat(requestMap.get("messages"), is(List.of(Map.of("role", "user", "content", "abcd"))));
assertThat(requestMap.get("parameters"), is(getParameterMap(1.0, null, null, null)));
}
public void testCreateRequest_WithOpenAiProviderTokenEndpoint_WithTopPParam() throws IOException {
var request = createRequest(
"http://openaitarget.local",
AzureAiStudioProvider.OPENAI,
AzureAiStudioEndpointType.TOKEN,
"apikey",
null,
2.0,
null,
null,
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://openaitarget.local");
validateRequestApiKey(httpPost, AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(2));
assertThat(requestMap.get("messages"), is(List.of(Map.of("role", "user", "content", "abcd"))));
assertThat(requestMap.get("parameters"), is(getParameterMap(null, 2.0, null, null)));
}
public void testCreateRequest_WithOpenAiProviderTokenEndpoint_WithDoSampleParam() throws IOException {
var request = createRequest(
"http://openaitarget.local",
AzureAiStudioProvider.OPENAI,
AzureAiStudioEndpointType.TOKEN,
"apikey",
null,
null,
true,
null,
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://openaitarget.local");
validateRequestApiKey(httpPost, AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(2));
assertThat(requestMap.get("messages"), is(List.of(Map.of("role", "user", "content", "abcd"))));
assertThat(requestMap.get("parameters"), is(getParameterMap(null, null, true, null)));
}
public void testCreateRequest_WithOpenAiProviderTokenEndpoint_WithMaxNewTokensParam() throws IOException {
var request = createRequest(
"http://openaitarget.local",
AzureAiStudioProvider.OPENAI,
AzureAiStudioEndpointType.TOKEN,
"apikey",
null,
null,
null,
512,
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://openaitarget.local");
validateRequestApiKey(httpPost, AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(2));
assertThat(requestMap.get("messages"), is(List.of(Map.of("role", "user", "content", "abcd"))));
assertThat(requestMap.get("parameters"), is(getParameterMap(null, null, null, 512)));
}
public void testCreateRequest_WithCohereProviderTokenEndpoint_NoParams() throws IOException {
var request = createRequest(
"http://coheretarget.local",
AzureAiStudioProvider.COHERE,
AzureAiStudioEndpointType.TOKEN,
"apikey",
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://coheretarget.local/v1/chat/completions");
validateRequestApiKey(httpPost, AzureAiStudioProvider.COHERE, AzureAiStudioEndpointType.TOKEN, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(1));
assertThat(requestMap.get("messages"), is(List.of(Map.of("role", "user", "content", "abcd"))));
}
public void testCreateRequest_WithCohereProviderTokenEndpoint_WithTemperatureParam() throws IOException {
var request = createRequest(
"http://coheretarget.local",
AzureAiStudioProvider.COHERE,
AzureAiStudioEndpointType.TOKEN,
"apikey",
1.0,
null,
null,
null,
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://coheretarget.local/v1/chat/completions");
validateRequestApiKey(httpPost, AzureAiStudioProvider.COHERE, AzureAiStudioEndpointType.TOKEN, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(2));
assertThat(requestMap.get("messages"), is(List.of(Map.of("role", "user", "content", "abcd"))));
assertThat(requestMap.get("parameters"), is(getParameterMap(1.0, null, null, null)));
}
public void testCreateRequest_WithCohereProviderTokenEndpoint_WithTopPParam() throws IOException {
var request = createRequest(
"http://coheretarget.local",
AzureAiStudioProvider.COHERE,
AzureAiStudioEndpointType.TOKEN,
"apikey",
null,
2.0,
null,
null,
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://coheretarget.local/v1/chat/completions");
validateRequestApiKey(httpPost, AzureAiStudioProvider.COHERE, AzureAiStudioEndpointType.TOKEN, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(2));
assertThat(requestMap.get("messages"), is(List.of(Map.of("role", "user", "content", "abcd"))));
assertThat(requestMap.get("parameters"), is(getParameterMap(null, 2.0, null, null)));
}
public void testCreateRequest_WithCohereProviderTokenEndpoint_WithDoSampleParam() throws IOException {
var request = createRequest(
"http://coheretarget.local",
AzureAiStudioProvider.COHERE,
AzureAiStudioEndpointType.TOKEN,
"apikey",
null,
null,
true,
null,
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://coheretarget.local/v1/chat/completions");
validateRequestApiKey(httpPost, AzureAiStudioProvider.COHERE, AzureAiStudioEndpointType.TOKEN, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(2));
assertThat(requestMap.get("messages"), is(List.of(Map.of("role", "user", "content", "abcd"))));
assertThat(requestMap.get("parameters"), is(getParameterMap(null, null, true, null)));
}
public void testCreateRequest_WithCohereProviderTokenEndpoint_WithMaxNewTokensParam() throws IOException {
var request = createRequest(
"http://coheretarget.local",
AzureAiStudioProvider.COHERE,
AzureAiStudioEndpointType.TOKEN,
"apikey",
null,
null,
null,
512,
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://coheretarget.local/v1/chat/completions");
validateRequestApiKey(httpPost, AzureAiStudioProvider.COHERE, AzureAiStudioEndpointType.TOKEN, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(2));
assertThat(requestMap.get("messages"), is(List.of(Map.of("role", "user", "content", "abcd"))));
assertThat(requestMap.get("parameters"), is(getParameterMap(null, null, null, 512)));
}
public void testCreateRequest_WithMistralProviderRealtimeEndpoint_NoParams() throws IOException {
var request = createRequest(
"http://mistral.local/score",
AzureAiStudioProvider.MISTRAL,
AzureAiStudioEndpointType.REALTIME,
"apikey",
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://mistral.local/score");
validateRequestApiKey(httpPost, AzureAiStudioProvider.MISTRAL, AzureAiStudioEndpointType.REALTIME, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(1));
@SuppressWarnings("unchecked")
var input_data = (Map<String, Object>) requestMap.get("input_data");
assertThat(input_data, aMapWithSize(1));
assertThat(input_data.get("input_string"), is(List.of(Map.of("role", "user", "content", "abcd"))));
}
public void testCreateRequest_WithMistralProviderRealtimeEndpoint_WithTemperatureParam() throws IOException {
var request = createRequest(
"http://mistral.local/score",
AzureAiStudioProvider.MISTRAL,
AzureAiStudioEndpointType.REALTIME,
"apikey",
1.0,
null,
null,
null,
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://mistral.local/score");
validateRequestApiKey(httpPost, AzureAiStudioProvider.MISTRAL, AzureAiStudioEndpointType.REALTIME, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(1));
@SuppressWarnings("unchecked")
var input_data = (Map<String, Object>) requestMap.get("input_data");
assertThat(input_data, aMapWithSize(2));
assertThat(input_data.get("input_string"), is(List.of(Map.of("role", "user", "content", "abcd"))));
assertThat(input_data.get("parameters"), is(getParameterMap(1.0, null, null, null)));
}
public void testCreateRequest_WithMistralProviderRealtimeEndpoint_WithTopPParam() throws IOException {
var request = createRequest(
"http://mistral.local/score",
AzureAiStudioProvider.MISTRAL,
AzureAiStudioEndpointType.REALTIME,
"apikey",
null,
2.0,
null,
null,
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://mistral.local/score");
validateRequestApiKey(httpPost, AzureAiStudioProvider.MISTRAL, AzureAiStudioEndpointType.REALTIME, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(1));
@SuppressWarnings("unchecked")
var input_data = (Map<String, Object>) requestMap.get("input_data");
assertThat(input_data, aMapWithSize(2));
assertThat(input_data.get("input_string"), is(List.of(Map.of("role", "user", "content", "abcd"))));
assertThat(input_data.get("parameters"), is(getParameterMap(null, 2.0, null, null)));
}
public void testCreateRequest_WithMistralProviderRealtimeEndpoint_WithDoSampleParam() throws IOException {
var request = createRequest(
"http://mistral.local/score",
AzureAiStudioProvider.MISTRAL,
AzureAiStudioEndpointType.REALTIME,
"apikey",
null,
null,
true,
null,
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://mistral.local/score");
validateRequestApiKey(httpPost, AzureAiStudioProvider.MISTRAL, AzureAiStudioEndpointType.REALTIME, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(1));
@SuppressWarnings("unchecked")
var input_data = (Map<String, Object>) requestMap.get("input_data");
assertThat(input_data, aMapWithSize(2));
assertThat(input_data.get("input_string"), is(List.of(Map.of("role", "user", "content", "abcd"))));
assertThat(input_data.get("parameters"), is(getParameterMap(null, null, true, null)));
}
public void testCreateRequest_WithMistralProviderRealtimeEndpoint_WithMaxNewTokensParam() throws IOException {
var request = createRequest(
"http://mistral.local/score",
AzureAiStudioProvider.MISTRAL,
AzureAiStudioEndpointType.REALTIME,
"apikey",
null,
null,
null,
512,
"abcd"
);
var httpRequest = request.createHttpRequest();
var httpPost = validateRequestUrlAndContentType(httpRequest, "http://mistral.local/score");
validateRequestApiKey(httpPost, AzureAiStudioProvider.MISTRAL, AzureAiStudioEndpointType.REALTIME, "apikey");
var requestMap = entityAsMap(httpPost.getEntity().getContent());
assertThat(requestMap, aMapWithSize(1));
@SuppressWarnings("unchecked")
var input_data = (Map<String, Object>) requestMap.get("input_data");
assertThat(input_data, aMapWithSize(2));
assertThat(input_data.get("input_string"), is(List.of(Map.of("role", "user", "content", "abcd"))));
assertThat(input_data.get("parameters"), is(getParameterMap(null, null, null, 512)));
}
private HttpPost validateRequestUrlAndContentType(HttpRequest request, String expectedUrl) throws IOException {
assertThat(request.httpRequestBase(), instanceOf(HttpPost.class));
var httpPost = (HttpPost) request.httpRequestBase();
assertThat(httpPost.getURI().toString(), is(expectedUrl));
assertThat(httpPost.getLastHeader(HttpHeaders.CONTENT_TYPE).getValue(), is(XContentType.JSON.mediaType()));
return httpPost;
}
private void validateRequestApiKey(
HttpPost httpPost,
AzureAiStudioProvider provider,
AzureAiStudioEndpointType endpointType,
String apiKey
) {
if (endpointType == AzureAiStudioEndpointType.TOKEN) {
if (provider == AzureAiStudioProvider.OPENAI) {
assertThat(httpPost.getLastHeader(API_KEY_HEADER).getValue(), is(apiKey));
} else {
assertThat(httpPost.getLastHeader(HttpHeaders.AUTHORIZATION).getValue(), is(apiKey));
}
} else {
assertThat(httpPost.getLastHeader(HttpHeaders.AUTHORIZATION).getValue(), is("Bearer " + apiKey));
}
}
private Map<String, Object> getParameterMap(
@Nullable Double temperature,
@Nullable Double topP,
@Nullable Boolean doSample,
@Nullable Integer maxNewTokens
) {
var map = new HashMap<String, Object>();
if (temperature != null) {
map.put("temperature", temperature);
}
if (topP != null) {
map.put("top_p", topP);
}
if (doSample != null) {
map.put("do_sample", doSample);
}
if (maxNewTokens != null) {
map.put("max_new_tokens", maxNewTokens);
}
return map;
}
public static AzureAiStudioChatCompletionRequest createRequest(
String target,
AzureAiStudioProvider provider,
AzureAiStudioEndpointType endpointType,
String apiKey,
String input
) {
return createRequest(target, provider, endpointType, apiKey, null, null, null, null, input);
}
public static AzureAiStudioChatCompletionRequest createRequest(
String target,
AzureAiStudioProvider provider,
AzureAiStudioEndpointType endpointType,
String apiKey,
@Nullable Double temperature,
@Nullable Double topP,
@Nullable Boolean doSample,
@Nullable Integer maxNewTokens,
String input
) {
var model = AzureAiStudioChatCompletionModelTests.createModel(
"id",
target,
provider,
endpointType,
apiKey,
temperature,
topP,
doSample,
maxNewTokens,
null
);
return new AzureAiStudioChatCompletionRequest(model, List.of(input), false);
}
}
| AzureAiStudioChatCompletionRequestTests |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DisruptorEndpointBuilderFactory.java | {
"start": 28226,
"end": 28558
} | class ____ extends AbstractEndpointBuilder implements DisruptorEndpointBuilder, AdvancedDisruptorEndpointBuilder {
public DisruptorEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new DisruptorEndpointBuilderImpl(path);
}
} | DisruptorEndpointBuilderImpl |
java | netty__netty | handler/src/test/java/io/netty/handler/ssl/SSLEngineTest.java | {
"start": 6202,
"end": 7281
} | class ____ {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SSLEngineTest.class);
private static final String PRINCIPAL_NAME = "CN=e8ac02fa0d65a84219016045db8b05c485b4ecdf.netty.test";
private static final Runnable NOOP = new Runnable() {
@Override
public void run() { }
};
private final boolean tlsv13Supported;
protected MessageReceiver serverReceiver;
protected MessageReceiver clientReceiver;
protected volatile Throwable serverException;
protected volatile Throwable clientException;
protected SslContext serverSslCtx;
protected SslContext clientSslCtx;
protected ServerBootstrap sb;
protected Bootstrap cb;
protected Channel serverChannel;
protected Channel serverConnectedChannel;
protected Channel clientChannel;
protected CountDownLatch serverLatch;
protected CountDownLatch clientLatch;
protected volatile Future<Channel> serverSslHandshakeFuture;
protected volatile Future<Channel> clientSslHandshakeFuture;
static final | SSLEngineTest |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/xmlonly/Tire.java | {
"start": 148,
"end": 313
} | class ____ {
public Long getId() {
return 1L;
}
public void setId(Long id) {
}
public Car getCar() {
return null;
}
public void setCar(Car car) {
}
}
| Tire |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/StateBackendFactory.java | {
"start": 1415,
"end": 1667
} | interface ____<T extends StateBackend> {
/**
* Creates the state backend, optionally using the given configuration.
*
* @param config The Flink configuration (loaded by the TaskManager).
* @param classLoader The | StateBackendFactory |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/java8stream/streamtononiterable/StreamToNonIterableMappingTest.java | {
"start": 561,
"end": 1373
} | class ____ {
@ProcessorTest
public void shouldMapStringStreamToStringUsingCustomMapper() {
Source source = new Source();
source.setNames( Stream.of( "Alice", "Bob", "Jim" ) );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
assertThat( target.getNames() ).isEqualTo( "Alice-Bob-Jim" );
}
@ProcessorTest
public void shouldReverseMapStringStreamToStringUsingCustomMapper() {
Target target = new Target();
target.setNames( "Alice-Bob-Jim" );
Source source = SourceTargetMapper.INSTANCE.targetToSource( target );
assertThat( source ).isNotNull();
assertThat( source.getNames() ).containsExactly( "Alice", "Bob", "Jim" );
}
}
| StreamToNonIterableMappingTest |
java | google__gson | test-graal-native-image/src/test/java/com/google/gson/native_test/ReflectionTest.java | {
"start": 4979,
"end": 5778
} | class ____ extends TypeAdapter<ClassWithCustomClassAdapter> {
@Override
public ClassWithCustomClassAdapter read(JsonReader in) throws IOException {
return new ClassWithCustomClassAdapter(in.nextInt() + 5);
}
@Override
public void write(JsonWriter out, ClassWithCustomClassAdapter value) throws IOException {
out.value(value.i + 6);
}
}
private int i;
private ClassWithCustomClassAdapter(int i) {
this.i = i;
}
}
@Test
void testCustomClassAdapter() {
Gson gson = new Gson();
ClassWithCustomClassAdapter c = gson.fromJson("1", ClassWithCustomClassAdapter.class);
assertThat(c.i).isEqualTo(6);
assertThat(gson.toJson(new ClassWithCustomClassAdapter(1))).isEqualTo("7");
}
private static | CustomAdapter |
java | elastic__elasticsearch | x-pack/plugin/mapper-exponential-histogram/src/test/java/org/elasticsearch/xpack/exponentialhistogram/aggregations/metrics/ExponentialHistogramSumAggregatorTests.java | {
"start": 1780,
"end": 5469
} | class ____ extends ExponentialHistogramAggregatorTestCase {
private static final String FIELD_NAME = "my_histogram";
public void testMatchesNumericDocValues() throws IOException {
List<ExponentialHistogram> histograms = createRandomHistograms(randomIntBetween(1, 1000));
boolean anyNonEmpty = histograms.stream().anyMatch(histo -> histo.sum() != 0);
double expectedSum = histograms.stream().mapToDouble(ExponentialHistogram::sum).sum();
testCase(new MatchAllDocsQuery(), iw -> histograms.forEach(histo -> addHistogramDoc(iw, FIELD_NAME, histo)), sum -> {
assertThat(sum.value(), closeTo(expectedSum, 0.0001d));
assertThat(AggregationInspectionHelper.hasValue(sum), equalTo(anyNonEmpty));
});
}
public void testNoDocs() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
// Intentionally not writing any docs
}, sum -> {
assertThat(sum.value(), equalTo(0.0d));
assertThat(AggregationInspectionHelper.hasValue(sum), equalTo(false));
});
}
public void testNoMatchingField() throws IOException {
List<ExponentialHistogram> histograms = createRandomHistograms(10);
testCase(new MatchAllDocsQuery(), iw -> histograms.forEach(histo -> addHistogramDoc(iw, "wrong_field", histo)), sum -> {
assertThat(sum.value(), equalTo(0.0d));
assertThat(AggregationInspectionHelper.hasValue(sum), equalTo(false));
});
}
public void testQueryFiltering() throws IOException {
List<Map.Entry<ExponentialHistogram, Boolean>> histogramsWithFilter = createRandomHistograms(10).stream()
.map(histo -> Map.entry(histo, randomBoolean()))
.toList();
boolean anyMatch = histogramsWithFilter.stream().filter(entry -> entry.getKey().sum() != 0).anyMatch(Map.Entry::getValue);
double filteredSum = histogramsWithFilter.stream().filter(Map.Entry::getValue).mapToDouble(entry -> entry.getKey().sum()).sum();
testCase(
new TermQuery(new Term("match", "yes")),
iw -> histogramsWithFilter.forEach(
entry -> addHistogramDoc(
iw,
FIELD_NAME,
entry.getKey(),
new StringField("match", entry.getValue() ? "yes" : "no", Field.Store.NO)
)
),
sum -> {
assertThat(sum.value(), closeTo(filteredSum, 0.0001d));
assertThat(AggregationInspectionHelper.hasValue(sum), equalTo(anyMatch));
}
);
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<Sum> verify)
throws IOException {
var fieldType = new ExponentialHistogramFieldMapper.ExponentialHistogramFieldType(FIELD_NAME, Collections.emptyMap(), null);
AggregationBuilder aggregationBuilder = createAggBuilderForTypeTest(fieldType, FIELD_NAME);
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new SumAggregationBuilder("sum_agg").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(
CoreValuesSourceType.NUMERIC,
CoreValuesSourceType.DATE,
CoreValuesSourceType.BOOLEAN,
ExponentialHistogramValuesSourceType.EXPONENTIAL_HISTOGRAM
);
}
}
| ExponentialHistogramSumAggregatorTests |
java | apache__camel | components/camel-azure/camel-azure-cosmosdb/src/test/java/org/apache/camel/component/azure/cosmosdb/integration/BaseCamelCosmosDbTestSupport.java | {
"start": 1155,
"end": 1724
} | class ____ extends CamelTestSupport {
protected CosmosAsyncClient client;
@Override
protected CamelContext createCamelContext() throws Exception {
client = CosmosDbTestUtils.createAsyncClient();
final CamelContext context = super.createCamelContext();
final CosmosDbComponent component = new CosmosDbComponent(context);
component.init();
component.getConfiguration().setCosmosAsyncClient(client);
context.addComponent("azure-cosmosdb", component);
return context;
}
}
| BaseCamelCosmosDbTestSupport |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/bind/EscapedErrors.java | {
"start": 1594,
"end": 6375
} | class ____ implements Errors {
private final Errors source;
/**
* Create a new EscapedErrors instance for the given source instance.
*/
public EscapedErrors(Errors source) {
Assert.notNull(source, "Errors source must not be null");
this.source = source;
}
public Errors getSource() {
return this.source;
}
@Override
public String getObjectName() {
return this.source.getObjectName();
}
@Override
public void setNestedPath(String nestedPath) {
this.source.setNestedPath(nestedPath);
}
@Override
public String getNestedPath() {
return this.source.getNestedPath();
}
@Override
public void pushNestedPath(String subPath) {
this.source.pushNestedPath(subPath);
}
@Override
public void popNestedPath() throws IllegalStateException {
this.source.popNestedPath();
}
@Override
public void reject(String errorCode) {
this.source.reject(errorCode);
}
@Override
public void reject(String errorCode, String defaultMessage) {
this.source.reject(errorCode, defaultMessage);
}
@Override
public void reject(String errorCode, Object @Nullable [] errorArgs, @Nullable String defaultMessage) {
this.source.reject(errorCode, errorArgs, defaultMessage);
}
@Override
public void rejectValue(@Nullable String field, String errorCode) {
this.source.rejectValue(field, errorCode);
}
@Override
public void rejectValue(@Nullable String field, String errorCode, String defaultMessage) {
this.source.rejectValue(field, errorCode, defaultMessage);
}
@Override
public void rejectValue(@Nullable String field, String errorCode,
Object @Nullable [] errorArgs, @Nullable String defaultMessage) {
this.source.rejectValue(field, errorCode, errorArgs, defaultMessage);
}
@Override
public void addAllErrors(Errors errors) {
this.source.addAllErrors(errors);
}
@Override
public boolean hasErrors() {
return this.source.hasErrors();
}
@Override
public int getErrorCount() {
return this.source.getErrorCount();
}
@Override
public List<ObjectError> getAllErrors() {
return escapeObjectErrors(this.source.getAllErrors());
}
@Override
public boolean hasGlobalErrors() {
return this.source.hasGlobalErrors();
}
@Override
public int getGlobalErrorCount() {
return this.source.getGlobalErrorCount();
}
@Override
public List<ObjectError> getGlobalErrors() {
return escapeObjectErrors(this.source.getGlobalErrors());
}
@Override
public @Nullable ObjectError getGlobalError() {
return escapeObjectError(this.source.getGlobalError());
}
@Override
public boolean hasFieldErrors() {
return this.source.hasFieldErrors();
}
@Override
public int getFieldErrorCount() {
return this.source.getFieldErrorCount();
}
@Override
public List<FieldError> getFieldErrors() {
return this.source.getFieldErrors();
}
@Override
public @Nullable FieldError getFieldError() {
return this.source.getFieldError();
}
@Override
public boolean hasFieldErrors(String field) {
return this.source.hasFieldErrors(field);
}
@Override
public int getFieldErrorCount(String field) {
return this.source.getFieldErrorCount(field);
}
@Override
public List<FieldError> getFieldErrors(String field) {
return escapeObjectErrors(this.source.getFieldErrors(field));
}
@Override
public @Nullable FieldError getFieldError(String field) {
return escapeObjectError(this.source.getFieldError(field));
}
@Override
public @Nullable Object getFieldValue(String field) {
Object value = this.source.getFieldValue(field);
return (value instanceof String text ? HtmlUtils.htmlEscape(text) : value);
}
@Override
public @Nullable Class<?> getFieldType(String field) {
return this.source.getFieldType(field);
}
@SuppressWarnings("unchecked")
private <T extends ObjectError> @Nullable T escapeObjectError(@Nullable T source) {
if (source == null) {
return null;
}
String defaultMessage = source.getDefaultMessage();
if (defaultMessage != null) {
defaultMessage = HtmlUtils.htmlEscape(defaultMessage);
}
if (source instanceof FieldError fieldError) {
Object value = fieldError.getRejectedValue();
if (value instanceof String text) {
value = HtmlUtils.htmlEscape(text);
}
return (T) new FieldError(
fieldError.getObjectName(), fieldError.getField(), value, fieldError.isBindingFailure(),
fieldError.getCodes(), fieldError.getArguments(), defaultMessage);
}
else {
return (T) new ObjectError(
source.getObjectName(), source.getCodes(), source.getArguments(), defaultMessage);
}
}
private <T extends ObjectError> List<T> escapeObjectErrors(List<T> source) {
List<T> escaped = new ArrayList<>(source.size());
for (T objectError : source) {
escaped.add(escapeObjectError(objectError));
}
return escaped;
}
}
| EscapedErrors |
java | spring-projects__spring-boot | module/spring-boot-http-client/src/test/java/org/springframework/boot/http/client/autoconfigure/reactive/ReactiveHttpClientAutoConfigurationTests.java | {
"start": 2672,
"end": 10032
} | class ____ {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ReactiveHttpClientAutoConfiguration.class,
HttpClientAutoConfiguration.class, SslAutoConfiguration.class));
@Test
void whenReactorIsAvailableThenReactorBeansAreDefined() {
this.contextRunner.run((context) -> {
BeanDefinition connectorDefinition = context.getBeanFactory().getBeanDefinition("clientHttpConnector");
assertThat(connectorDefinition.isLazyInit()).isTrue();
assertThat(context).hasSingleBean(ReactorResourceFactory.class);
assertThat(context.getBean(ClientHttpConnectorBuilder.class))
.isExactlyInstanceOf(ReactorClientHttpConnectorBuilder.class);
});
}
@Test
void whenReactorIsUnavailableThenJettyClientBeansAreDefined() {
this.contextRunner.withClassLoader(new FilteredClassLoader(HttpClient.class)).run((context) -> {
BeanDefinition connectorDefinition = context.getBeanFactory().getBeanDefinition("clientHttpConnector");
assertThat(connectorDefinition.isLazyInit()).isTrue();
assertThat(context.getBean(ClientHttpConnectorBuilder.class))
.isExactlyInstanceOf(JettyClientHttpConnectorBuilder.class);
});
}
@Test
void whenReactorAndHttpClientAreUnavailableThenJettyClientBeansAreDefined() {
this.contextRunner.withClassLoader(new FilteredClassLoader(HttpClient.class, HttpAsyncClients.class))
.run((context) -> {
BeanDefinition connectorDefinition = context.getBeanFactory().getBeanDefinition("clientHttpConnector");
assertThat(connectorDefinition.isLazyInit()).isTrue();
assertThat(context.getBean(ClientHttpConnectorBuilder.class))
.isExactlyInstanceOf(JettyClientHttpConnectorBuilder.class);
});
}
@Test
void whenReactorAndHttpClientAndJettyAreUnavailableThenJdkClientBeansAreDefined() {
this.contextRunner
.withClassLoader(new FilteredClassLoader(HttpClient.class, HttpAsyncClients.class,
org.eclipse.jetty.client.HttpClient.class))
.run((context) -> {
BeanDefinition connectorDefinition = context.getBeanFactory().getBeanDefinition("clientHttpConnector");
assertThat(connectorDefinition.isLazyInit()).isTrue();
assertThat(context.getBean(ClientHttpConnectorBuilder.class))
.isExactlyInstanceOf(JdkClientHttpConnectorBuilder.class);
});
}
@Test
void shouldNotOverrideCustomClientConnector() {
this.contextRunner.withUserConfiguration(CustomClientHttpConnectorConfig.class).run((context) -> {
assertThat(context).hasSingleBean(ClientHttpConnector.class);
assertThat(context).hasBean("customConnector");
});
}
@Test
void shouldUseCustomReactorResourceFactory() {
this.contextRunner.withUserConfiguration(CustomReactorResourceConfig.class).run((context) -> {
assertThat(context).hasSingleBean(ClientHttpConnector.class);
assertThat(context).hasSingleBean(ReactorResourceFactory.class);
assertThat(context).hasBean("customReactorResourceFactory");
ClientHttpConnector connector = context.getBean(ClientHttpConnector.class);
assertThat(connector).extracting("httpClient.config.loopResources")
.isEqualTo(context.getBean("customReactorResourceFactory", ReactorResourceFactory.class)
.getLoopResources());
});
}
@Test
void shouldUseReactorResourceFactory() {
this.contextRunner.run((context) -> {
assertThat(context).hasSingleBean(ClientHttpConnector.class);
assertThat(context).hasSingleBean(ReactorResourceFactory.class);
ClientHttpConnector connector = context.getBean(ClientHttpConnector.class);
assertThat(connector).extracting("httpClient.config.loopResources")
.isEqualTo(context.getBean(ReactorResourceFactory.class).getLoopResources());
});
}
@Test
void configuresDetectedClientHttpConnectorBuilderBuilder() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ClientHttpConnectorBuilder.class));
}
@Test
void configuresDefinedClientHttpConnectorBuilder() {
this.contextRunner.withPropertyValues("spring.http.clients.reactive.connector=jetty")
.run((context) -> assertThat(context.getBean(ClientHttpConnectorBuilder.class))
.isInstanceOf(JettyClientHttpConnectorBuilder.class));
}
@Test
void configuresClientHttpConnectorSettings() {
this.contextRunner.withPropertyValues(sslPropertyValues().toArray(String[]::new))
.withPropertyValues("spring.http.clients.redirects=dont-follow", "spring.http.clients.connect-timeout=10s",
"spring.http.clients.read-timeout=20s", "spring.http.clients.ssl.bundle=test")
.run((context) -> {
HttpClientSettings settings = context.getBean(HttpClientSettings.class);
assertThat(settings.redirects()).isEqualTo(HttpRedirects.DONT_FOLLOW);
assertThat(settings.connectTimeout()).isEqualTo(Duration.ofSeconds(10));
assertThat(settings.readTimeout()).isEqualTo(Duration.ofSeconds(20));
SslBundle sslBundle = settings.sslBundle();
assertThat(sslBundle).isNotNull();
assertThat(sslBundle.getKey().getAlias()).isEqualTo("alias1");
});
}
@Test
void shouldBeConditionalOnAtLeastOneHttpConnectorClass() {
FilteredClassLoader classLoader = new FilteredClassLoader(reactor.netty.http.client.HttpClient.class,
org.eclipse.jetty.client.HttpClient.class, org.apache.hc.client5.http.impl.async.HttpAsyncClients.class,
java.net.http.HttpClient.class);
assertThatIllegalStateException().as("enough filtering")
.isThrownBy(() -> ClientHttpConnectorBuilder.detect(classLoader));
this.contextRunner.withClassLoader(classLoader)
.run((context) -> assertThat(context).doesNotHaveBean(ClientHttpConnector.class)
.hasSingleBean(HttpClientSettings.class));
}
@Test
@EnabledForJreRange(min = JRE.JAVA_21)
void whenVirtualThreadsEnabledAndUsingJdkHttpClientUsesVirtualThreadExecutor() {
this.contextRunner
.withPropertyValues("spring.http.clients.reactive.connector=jdk", "spring.threads.virtual.enabled=true")
.run((context) -> {
ClientHttpConnector connector = context.getBean(ClientHttpConnectorBuilder.class).build();
java.net.http.HttpClient httpClient = (java.net.http.HttpClient) ReflectionTestUtils.getField(connector,
"httpClient");
assertThat(httpClient).isNotNull();
assertThat(httpClient.executor()).containsInstanceOf(VirtualThreadTaskExecutor.class);
});
}
private List<String> sslPropertyValues() {
List<String> propertyValues = new ArrayList<>();
String location = "classpath:org/springframework/boot/autoconfigure/ssl/";
propertyValues.add("spring.ssl.bundle.pem.test.key.alias=alias1");
propertyValues.add("spring.ssl.bundle.pem.test.truststore.type=PKCS12");
propertyValues.add("spring.ssl.bundle.pem.test.truststore.certificate=" + location + "rsa-cert.pem");
propertyValues.add("spring.ssl.bundle.pem.test.truststore.private-key=" + location + "rsa-key.pem");
return propertyValues;
}
@Test
void clientHttpConnectorBuilderCustomizersAreApplied() {
this.contextRunner.withPropertyValues("spring.http.clients.reactive.connector=jdk")
.withUserConfiguration(ClientHttpConnectorBuilderCustomizersConfiguration.class)
.run((context) -> {
ClientHttpConnector connector = context.getBean(ClientHttpConnectorBuilder.class).build();
assertThat(connector).extracting("readTimeout").isEqualTo(Duration.ofSeconds(5));
});
}
@Configuration(proxyBeanMethods = false)
static | ReactiveHttpClientAutoConfigurationTests |
java | apache__camel | components/camel-keycloak/src/test/java/org/apache/camel/component/keycloak/security/cache/ConcurrentMapTokenCacheTest.java | {
"start": 1120,
"end": 5097
} | class ____ {
private ConcurrentMapTokenCache cache;
private KeycloakTokenIntrospector.IntrospectionResult testResult;
@BeforeEach
void setUp() {
cache = new ConcurrentMapTokenCache(60); // 60 seconds TTL
Map<String, Object> claims = new HashMap<>();
claims.put("active", true);
claims.put("sub", "test-user");
claims.put("scope", "openid profile");
testResult = new KeycloakTokenIntrospector.IntrospectionResult(claims);
}
@Test
void testPutAndGet() {
String token = "test-token-123";
cache.put(token, testResult);
KeycloakTokenIntrospector.IntrospectionResult retrieved = cache.get(token);
assertNotNull(retrieved);
assertTrue(retrieved.isActive());
assertEquals("test-user", retrieved.getSubject());
}
@Test
void testGetNonExistent() {
KeycloakTokenIntrospector.IntrospectionResult retrieved = cache.get("non-existent");
assertNull(retrieved);
}
@Test
void testRemove() {
String token = "test-token-456";
cache.put(token, testResult);
assertNotNull(cache.get(token));
cache.remove(token);
assertNull(cache.get(token));
}
@Test
void testClear() {
cache.put("token1", testResult);
cache.put("token2", testResult);
assertEquals(2, cache.size());
cache.clear();
assertEquals(0, cache.size());
assertNull(cache.get("token1"));
assertNull(cache.get("token2"));
}
@Test
void testExpiration() throws InterruptedException {
ConcurrentMapTokenCache shortCache = new ConcurrentMapTokenCache(1); // 1 second TTL
String token = "expiring-token";
shortCache.put(token, testResult);
assertNotNull(shortCache.get(token));
// Wait for expiration
Thread.sleep(1100);
assertNull(shortCache.get(token));
}
@Test
void testSize() {
assertEquals(0, cache.size());
cache.put("token1", testResult);
assertEquals(1, cache.size());
cache.put("token2", testResult);
assertEquals(2, cache.size());
cache.remove("token1");
assertEquals(1, cache.size());
}
@Test
void testStats() {
TokenCache.CacheStats stats = cache.getStats();
assertNotNull(stats);
assertEquals(0, stats.getHitCount());
assertEquals(0, stats.getMissCount());
// Put and get (hit)
cache.put("token1", testResult);
cache.get("token1");
stats = cache.getStats();
assertEquals(1, stats.getHitCount());
assertEquals(0, stats.getMissCount());
// Get non-existent (miss)
cache.get("non-existent");
stats = cache.getStats();
assertEquals(1, stats.getHitCount());
assertEquals(1, stats.getMissCount());
assertEquals(0.5, stats.getHitRate(), 0.01);
}
@Test
void testStatsAfterClear() {
cache.put("token1", testResult);
cache.get("token1");
TokenCache.CacheStats stats = cache.getStats();
assertTrue(stats.getHitCount() > 0);
cache.clear();
stats = cache.getStats();
assertEquals(0, stats.getHitCount());
assertEquals(0, stats.getMissCount());
}
@Test
void testConcurrentAccess() throws InterruptedException {
int threadCount = 10;
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++) {
final int index = i;
threads[i] = new Thread(() -> {
String token = "token-" + index;
cache.put(token, testResult);
assertNotNull(cache.get(token));
});
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
assertEquals(threadCount, cache.size());
}
}
| ConcurrentMapTokenCacheTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/support/CountDownActionListener.java | {
"start": 1109,
"end": 2632
} | class ____ extends DelegatingActionListener<Void, Void> {
private final AtomicInteger countDown;
private final AtomicReference<Exception> failure = new AtomicReference<>();
/**
* Creates a new listener
* @param groupSize the group size
* @param delegate the delegate listener
*/
public CountDownActionListener(int groupSize, ActionListener<Void> delegate) {
super(Objects.requireNonNull(delegate));
if (groupSize <= 0) {
assert false : "illegal group size [" + groupSize + "]";
throw new IllegalArgumentException("groupSize must be greater than 0 but was " + groupSize);
}
countDown = new AtomicInteger(groupSize);
}
private boolean countDown() {
final var result = countDown.getAndUpdate(current -> Math.max(0, current - 1));
assert result > 0;
return result == 1;
}
@Override
public void onResponse(Void element) {
if (countDown()) {
if (failure.get() != null) {
super.onFailure(failure.get());
} else {
delegate.onResponse(element);
}
}
}
@Override
public void onFailure(Exception e) {
final var firstException = failure.compareAndExchange(null, e);
if (firstException != null && firstException != e) {
firstException.addSuppressed(e);
}
if (countDown()) {
super.onFailure(failure.get());
}
}
}
| CountDownActionListener |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/predicate/operator/arithmetic/SubUnsignedLongsEvaluator.java | {
"start": 5173,
"end": 5942
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory lhs;
private final EvalOperator.ExpressionEvaluator.Factory rhs;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory lhs,
EvalOperator.ExpressionEvaluator.Factory rhs) {
this.source = source;
this.lhs = lhs;
this.rhs = rhs;
}
@Override
public SubUnsignedLongsEvaluator get(DriverContext context) {
return new SubUnsignedLongsEvaluator(source, lhs.get(context), rhs.get(context), context);
}
@Override
public String toString() {
return "SubUnsignedLongsEvaluator[" + "lhs=" + lhs + ", rhs=" + rhs + "]";
}
}
}
| Factory |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/ser/std/StdContainerSerializer.java | {
"start": 522,
"end": 646
} | class ____ named {@code ContainerSerializer}
* (in package {@code com.fasterxml.jackson.databind.ser}).
*/
public abstract | was |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/constraint/api/SchedulingRequestWithPlacementAttempt.java | {
"start": 1055,
"end": 1781
} | class ____ {
private final int placementAttempt;
private final SchedulingRequest schedulingRequest;
public SchedulingRequestWithPlacementAttempt(int placementAttempt,
SchedulingRequest schedulingRequest) {
this.placementAttempt = placementAttempt;
this.schedulingRequest = schedulingRequest;
}
public int getPlacementAttempt() {
return placementAttempt;
}
public SchedulingRequest getSchedulingRequest() {
return schedulingRequest;
}
@Override
public String toString() {
return "SchedulingRequestWithPlacementAttempt{" +
"placementAttempt=" + placementAttempt +
", schedulingRequest=" + schedulingRequest +
'}';
}
}
| SchedulingRequestWithPlacementAttempt |
java | resilience4j__resilience4j | resilience4j-spring6/src/test/java/io/github/resilience4j/spring6/TestDummyService.java | {
"start": 835,
"end": 5958
} | interface ____ {
String BACKEND = "backendA";
String BACKEND_B = "backendB";
String sync();
String syncSuccess();
CompletionStage<String> asyncThreadPool();
CompletionStage<String> asyncThreadPoolSuccess();
CompletionStage<String> async();
Flux<String> flux();
Mono<String> mono(String parameter);
Observable<String> observable();
Single<String> single();
Completable completable();
Maybe<String> maybe();
Flowable<String> flowable();
io.reactivex.rxjava3.core.Observable<String> rx3Observable();
io.reactivex.rxjava3.core.Single<String> rx3Single();
io.reactivex.rxjava3.core.Completable rx3Completable();
io.reactivex.rxjava3.core.Maybe<String> rx3Maybe();
io.reactivex.rxjava3.core.Flowable<String> rx3Flowable();
default String spelSync(String backend) {
return syncError();
}
default String spelSyncNoCfg(String backend) {
return syncError();
}
default String spelSyncWithCfg(String backend) {
return syncError();
}
default Mono<String> spelMono(String backend) {
return monoError(backend);
}
default Mono<String> spelMonoWithCfg(String backend) {
return monoError(backend);
}
default String syncError() {
throw new RuntimeException("Test");
}
default CompletionStage<String> asyncError() {
CompletableFuture<String> future = new CompletableFuture<>();
future.completeExceptionally(new RuntimeException("Test"));
return future;
}
default Flux<String> fluxError() {
return Flux.error(new RuntimeException("Test"));
}
default Mono<String> monoError(String parameter) {
return Mono.error(new RuntimeException("Test"));
}
default Observable<String> observableError() {
return Observable.error(new RuntimeException("Test"));
}
default Single<String> singleError() {
return Single.error(new RuntimeException("Test"));
}
default Completable completableError() {
return Completable.error(new RuntimeException("Test"));
}
default Maybe<String> maybeError() {
return Maybe.error(new RuntimeException("Test"));
}
default Flowable<String> flowableError() {
return Flowable.error(new RuntimeException("Test"));
}
default io.reactivex.rxjava3.core.Observable<String> rx3ObservableError() {
return io.reactivex.rxjava3.core.Observable.error(new RuntimeException("Test"));
}
default io.reactivex.rxjava3.core.Single<String> rx3SingleError() {
return io.reactivex.rxjava3.core.Single.error(new RuntimeException("Test"));
}
default io.reactivex.rxjava3.core.Completable rx3CompletableError() {
return io.reactivex.rxjava3.core.Completable.error(new RuntimeException("Test"));
}
default io.reactivex.rxjava3.core.Maybe<String> rx3MaybeError() {
return io.reactivex.rxjava3.core.Maybe.error(new RuntimeException("Test"));
}
default io.reactivex.rxjava3.core.Flowable<String> rx3FlowableError() {
return io.reactivex.rxjava3.core.Flowable.error(new RuntimeException("Test"));
}
default String recovery(RuntimeException throwable) {
return "recovered";
}
default CompletionStage<String> completionStageRecovery(Throwable throwable) {
return CompletableFuture.supplyAsync(() -> "recovered");
}
default Flux<String> fluxRecovery(Throwable throwable) {
return Flux.just("recovered");
}
default Mono<String> monoRecovery(String parameter, Throwable throwable) {
return Mono.just(parameter);
}
default Observable<String> observableRecovery(Throwable throwable) {
return Observable.just("recovered");
}
default Single<String> singleRecovery(Throwable throwable) {
return Single.just("recovered");
}
default Completable completableRecovery(Throwable throwable) {
return Completable.complete();
}
default Maybe<String> maybeRecovery(Throwable throwable) {
return Maybe.just("recovered");
}
default Flowable<String> flowableRecovery(Throwable throwable) {
return Flowable.just("recovered");
}
default io.reactivex.rxjava3.core.Observable<String> rx3ObservableRecovery(Throwable throwable) {
return io.reactivex.rxjava3.core.Observable.just("recovered");
}
default io.reactivex.rxjava3.core.Single<String> rx3SingleRecovery(Throwable throwable) {
return io.reactivex.rxjava3.core.Single.just("recovered");
}
default io.reactivex.rxjava3.core.Completable rx3CompletableRecovery(Throwable throwable) {
return io.reactivex.rxjava3.core.Completable.complete();
}
default io.reactivex.rxjava3.core.Maybe<String> rx3MaybeRecovery(Throwable throwable) {
return io.reactivex.rxjava3.core.Maybe.just("recovered");
}
default io.reactivex.rxjava3.core.Flowable<String> rx3FlowableRecovery(Throwable throwable) {
return io.reactivex.rxjava3.core.Flowable.just("recovered");
}
}
| TestDummyService |
java | elastic__elasticsearch | modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/ConfigDatabases.java | {
"start": 1602,
"end": 1658
} | class ____ MP again after serverless is enabled"
)
final | for |
java | micronaut-projects__micronaut-core | http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/ErrorHandlerTest.java | {
"start": 10821,
"end": 11850
} | class ____ {
@Get("/global")
String globalHandler() {
throw new MyException("bad things");
}
@Get("/global-ctrl")
String globalControllerHandler() throws GloballyHandledException {
throw new GloballyHandledException("bad things happens globally");
}
@Get("/global-status-ctrl")
@Status(HttpStatus.I_AM_A_TEAPOT)
String globalControllerHandlerForStatus() {
return "original global status";
}
@Get("/local")
String localHandler() {
throw new AnotherException("bad things");
}
@Error
@Produces(io.micronaut.http.MediaType.TEXT_PLAIN)
@Status(HttpStatus.OK)
String localHandler(AnotherException throwable) {
return throwable.getMessage();
}
}
@Controller(value = "/json/errors", produces = io.micronaut.http.MediaType.APPLICATION_JSON)
@Requires(property = "spec.name", value = SPEC_NAME)
static | ErrorController |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/EntityAttributeMutabilityTest.java | {
"start": 1320,
"end": 2529
} | class ____ {
@Test
public void verifyMetamodel(DomainModelScope domainModelScope, SessionFactoryScope sessionFactoryScope) {
final PersistentClass persistentClass = domainModelScope.getEntityBinding( Employee.class );
final EntityPersister entityDescriptor = sessionFactoryScope.getSessionFactory()
.getRuntimeMetamodels()
.getMappingMetamodel()
.getEntityDescriptor( Employee.class );
// `@Immutable`
final Property managerProperty = persistentClass.getProperty( "manager" );
assertThat( managerProperty.isUpdatable() ).isFalse();
final AttributeMapping managerAttribute = entityDescriptor.findAttributeMapping( "manager" );
assertThat( managerAttribute.getExposedMutabilityPlan().isMutable() ).isFalse();
// `@Mutability(Immutability.class)` - no effect
final Property manager2Property = persistentClass.getProperty( "manager2" );
assertThat( manager2Property.isUpdatable() ).isTrue();
final AttributeMapping manager2Attribute = entityDescriptor.findAttributeMapping( "manager2" );
assertThat( manager2Attribute.getExposedMutabilityPlan().isMutable() ).isTrue();
}
@Entity( name = "Employee" )
@Table( name = "Employee" )
public static | EntityAttributeMutabilityTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/LazyOneToOneMultiAssociationTest.java | {
"start": 2548,
"end": 3952
} | class ____ {
@Id
private Integer id;
@OneToOne
private EntityA selfAssociation;
@OneToOne(mappedBy = "selfAssociation")
private EntityA mappedSelfAssociation;
@OneToOne(mappedBy = "association1", fetch = FetchType.LAZY)
private EntityB mappedAssociation1;
@OneToOne(mappedBy = "association2", fetch = FetchType.LAZY)
private EntityB mappedAssociation2;
protected EntityA() {
}
public EntityA(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public EntityA getSelfAssociation() {
return selfAssociation;
}
public void setSelfAssociation(EntityA selfAssociation) {
this.selfAssociation = selfAssociation;
}
public EntityA getMappedSelfAssociation() {
return mappedSelfAssociation;
}
public void setMappedSelfAssociation(EntityA mappedSelfAssociation) {
this.mappedSelfAssociation = mappedSelfAssociation;
}
public EntityB getMappedAssociation1() {
return mappedAssociation1;
}
public void setMappedAssociation1(EntityB mappedAssociation1) {
this.mappedAssociation1 = mappedAssociation1;
}
public EntityB getMappedAssociation2() {
return mappedAssociation2;
}
public void setMappedAssociation2(EntityB mappedAssociation2) {
this.mappedAssociation2 = mappedAssociation2;
}
}
@Entity(name = "entityb")
public static | EntityA |
java | apache__kafka | examples/src/main/java/kafka/examples/Producer.java | {
"start": 7001,
"end": 8472
} | class ____ implements Callback {
private final int key;
private final String value;
public ProducerCallback(int key, String value) {
this.key = key;
this.value = value;
}
/**
* A callback method the user can implement to provide asynchronous handling of request completion. This method will
* be called when the record sent to the server has been acknowledged. When exception is not null in the callback,
* metadata will contain the special -1 value for all fields except for topicPartition, which will be valid.
*
* @param metadata The metadata for the record that was sent (i.e. the partition and offset). An empty metadata
* with -1 value for all fields except for topicPartition will be returned if an error occurred.
* @param exception The exception thrown during processing of this record. Null if no error occurred.
*/
public void onCompletion(RecordMetadata metadata, Exception exception) {
if (exception != null) {
Utils.printErr(exception.getMessage());
if (!(exception instanceof RetriableException)) {
// we can't recover from these exceptions
shutdown();
}
} else {
Utils.maybePrintRecord(numRecords, key, value, metadata);
}
}
}
}
| ProducerCallback |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/matchers/method/MethodMatchers.java | {
"start": 1091,
"end": 1337
} | interface ____ extends Matcher<ExpressionTree> {}
// Language definition for fluent method matchers.
/**
* @deprecated use {@code Matcher<ExpressionTree>} instead of referring directly to this type.
*/
@Deprecated
public | MethodMatcher |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/rest/action/cat/RestFielddataAction.java | {
"start": 1215,
"end": 1332
} | class ____ display information about the size of fielddata fields per node
*/
@ServerlessScope(Scope.INTERNAL)
public | to |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/accesstype/User.java | {
"start": 300,
"end": 759
} | class ____ {
private Long id;
private String nonPersistent;
private String name;
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Transient
public String getNonPersistent() {
return nonPersistent;
}
public void setNonPersistent(String nonPersistent) {
this.nonPersistent = nonPersistent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| User |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.