language
stringclasses 1
value | repo
stringclasses 60
values | path
stringlengths 22
294
| class_span
dict | source
stringlengths 13
1.16M
| target
stringlengths 1
113
|
|---|---|---|---|---|---|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-router/src/test/java/org/apache/hadoop/yarn/server/router/clientrm/TestRouterClientRMService.java
|
{
"start": 2644,
"end": 2713
}
|
class ____ validate the ClientRM Service inside the Router.
*/
public
|
to
|
java
|
google__dagger
|
dagger-producers/main/java/dagger/producers/monitoring/ProducerToken.java
|
{
"start": 936,
"end": 1259
}
|
class ____ {
@NullableDecl private final Class<?> classToken;
@NullableDecl private final String methodName;
private ProducerToken(@NullableDecl Class<?> classToken, @NullableDecl String methodName) {
this.classToken = classToken;
this.methodName = methodName;
}
/**
* Creates a token for a
|
ProducerToken
|
java
|
quarkusio__quarkus
|
integration-tests/micrometer-opentelemetry/src/main/java/io/quarkus/micrometer/opentelemetry/services/ManualHistogram.java
|
{
"start": 276,
"end": 872
}
|
class ____ {
@Inject
MeterRegistry registry;
public void recordHistogram() {
DistributionSummary summary = DistributionSummary.builder("testSummary")
.description("This is a test distribution summary")
.baseUnit("things")
.tags("tag", "value")
.serviceLevelObjectives(1, 10, 100, 1000)
.distributionStatisticBufferLength(10)
.register(registry);
summary.record(0.5);
summary.record(5);
summary.record(50);
summary.record(500);
}
}
|
ManualHistogram
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/processor/enricher/EnrichExpressionIgnoreInvalidEndpointTest.java
|
{
"start": 982,
"end": 1878
}
|
class ____ extends ContextTestSupport {
@Test
public void testEnrichExpression() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World", "Unknown");
template.sendBodyAndHeader("direct:start", "Camel", "source", "direct:foo");
template.sendBodyAndHeader("direct:start", "Unknown", "source", "unknown");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").enrich().header("source").ignoreInvalidEndpoint().to("mock:result");
from("direct:foo").transform().constant("Hello World");
from("direct:bar").transform().constant("Bye World");
}
};
}
}
|
EnrichExpressionIgnoreInvalidEndpointTest
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/ser/BasicSerializerFactory.java
|
{
"start": 52536,
"end": 53511
}
|
class ____ indicates content ("value") serializer to use.
* If so, will try to instantiate value serializer and return it; otherwise returns null.
*/
protected ValueSerializer<Object> _findContentSerializer(SerializationContext ctxt,
Annotated a)
{
AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
Object serDef = intr.findContentSerializer(ctxt.getConfig(), a);
return ctxt.serializerInstance(a, serDef); // ok to pass null
}
/**
* Method called to find filter that is configured to be used with bean
* serializer being built, if any.
*/
protected Object findFilterId(SerializationConfig config, BeanDescription.Supplier beanDescRef) {
return config.getAnnotationIntrospector().findFilterId(config,
(Annotated)beanDescRef.getClassInfo());
}
/**
* Helper method to check whether global settings and/or class
* annotations for the bean
|
that
|
java
|
spring-projects__spring-security
|
docs/src/test/java/org/springframework/security/docs/servlet/authentication/authorizationmanagerfactory/AuthorizationManagerFactoryTests.java
|
{
"start": 4646,
"end": 4734
}
|
class ____ {
@GetMapping("/**")
String ok() {
return "ok";
}
}
}
|
Http200Controller
|
java
|
spring-projects__spring-boot
|
module/spring-boot-mail/src/test/java/org/springframework/boot/mail/autoconfigure/MailHealthContributorAutoConfigurationTests.java
|
{
"start": 1182,
"end": 1930
}
|
class ____ {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(MailSenderAutoConfiguration.class,
MailHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class))
.withPropertyValues("spring.mail.host:smtp.example.com");
@Test
void runShouldCreateIndicator() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MailHealthIndicator.class));
}
@Test
void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.health.mail.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(MailHealthIndicator.class));
}
}
|
MailHealthContributorAutoConfigurationTests
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/scale/ITestS3AHugeFilesSSECDiskBlocks.java
|
{
"start": 1928,
"end": 3276
}
|
class ____
extends ITestS3AHugeFilesDiskBlocks {
private static final String KEY_1
= "4niV/jPK5VFRHY+KNb6wtqYd4xXyMgdJ9XQJpcQUVbs=";
/**
* Skipping tests when running against mandatory encryption bucket
* which allows only certain encryption method.
* S3 throw AmazonS3Exception with status 403 AccessDenied
* then it is translated into AccessDeniedException by S3AUtils.translateException(...)
*/
@BeforeEach
@Override
public void setup() throws Exception {
try {
super.setup();
} catch (AccessDeniedException | AWSUnsupportedFeatureException e) {
skip("Bucket does not allow " + S3AEncryptionMethods.SSE_C + " encryption method");
}
}
@SuppressWarnings("deprecation")
@Override
protected Configuration createScaleConfiguration() {
Configuration conf = super.createScaleConfiguration();
removeBaseAndBucketOverrides(conf, S3_ENCRYPTION_KEY,
S3_ENCRYPTION_ALGORITHM, SERVER_SIDE_ENCRYPTION_ALGORITHM,
SERVER_SIDE_ENCRYPTION_KEY);
skipIfEncryptionTestsDisabled(conf);
conf.set(Constants.S3_ENCRYPTION_ALGORITHM,
getSSEAlgorithm().getMethod());
conf.set(Constants.S3_ENCRYPTION_KEY, KEY_1);
return conf;
}
private S3AEncryptionMethods getSSEAlgorithm() {
return S3AEncryptionMethods.SSE_C;
}
}
|
ITestS3AHugeFilesSSECDiskBlocks
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/engine/discovery/predicates/TestClassPredicatesTests.java
|
{
"start": 14369,
"end": 14473
}
|
class ____ {
}
@SuppressWarnings("JUnitMalformedDeclaration")
@Nested
private
|
StaticNestedClass
|
java
|
elastic__elasticsearch
|
modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/SortProcessor.java
|
{
"start": 3373,
"end": 4416
}
|
class ____ implements Processor.Factory {
@Override
public SortProcessor create(
Map<String, Processor.Factory> registry,
String processorTag,
String description,
Map<String, Object> config,
ProjectId projectId
) throws Exception {
String field = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, FIELD);
String targetField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "target_field", field);
try {
SortOrder direction = SortOrder.fromString(
ConfigurationUtils.readStringProperty(TYPE, processorTag, config, ORDER, DEFAULT_ORDER)
);
return new SortProcessor(processorTag, description, field, direction, targetField);
} catch (IllegalArgumentException e) {
throw ConfigurationUtils.newConfigurationException(TYPE, processorTag, ORDER, e.getMessage());
}
}
}
}
|
Factory
|
java
|
apache__spark
|
launcher/src/main/java/org/apache/spark/launcher/package-info.java
|
{
"start": 2552,
"end": 2843
}
|
class ____.
* </p>
*
* <p>
* It's also possible to launch a raw child process, without the extra monitoring, using the
* {@link org.apache.spark.launcher.SparkLauncher#launch()} method:
* </p>
*
* <pre>
* {@code
* import org.apache.spark.launcher.SparkLauncher;
*
* public
|
loader
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-client/runtime/src/main/java/io/quarkus/rest/client/reactive/runtime/ResteasyReactiveResponseExceptionMapper.java
|
{
"start": 241,
"end": 560
}
|
interface ____<T extends Throwable> extends ResponseExceptionMapper<T> {
T toThrowable(Response response, RestClientRequestContext context);
@Override
default T toThrowable(Response response) {
throw new IllegalStateException("should never be invoked");
}
}
|
ResteasyReactiveResponseExceptionMapper
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/GenericToOneAssociationTest.java
|
{
"start": 4690,
"end": 4997
}
|
class ____<T> {
@OneToOne(mappedBy = "child")
private T parent;
public AbstractChild() {
}
public abstract Long getId();
public T getParent() {
return this.parent;
}
public void setParent(T parent) {
this.parent = parent;
}
}
@Entity( name = "Child" )
public static
|
AbstractChild
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e3/b2/PolicyId.java
|
{
"start": 286,
"end": 402
}
|
class ____ implements Serializable {
@Column(name = "`type`", length = 32)
String type;
DependentId depPK;
}
|
PolicyId
|
java
|
quarkusio__quarkus
|
independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/catalog/CategoryImpl.java
|
{
"start": 861,
"end": 2097
}
|
class ____ implements Category {
private final String id;
private final String name;
private final String description;
private final Map<String, Object> metadata;
private CategoryImpl(Builder builder) {
this.id = builder.id;
if (id == null) {
throw new IllegalArgumentException("id is missing for category named " + builder.name);
}
this.name = builder.name;
this.description = builder.description;
this.metadata = JsonBuilder.toUnmodifiableMap(builder.metadata);
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return description;
}
@Override
public Map<String, Object> getMetadata() {
return metadata;
}
@Override
public boolean equals(Object o) {
return categoryEquals(this, o);
}
@Override
public int hashCode() {
return Objects.hash(id, name, description, getMetadata());
}
@Override
public String toString() {
return categoryToString(this);
}
/**
* Builder.
*/
public static
|
CategoryImpl
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/ReturnsNullCollectionTest.java
|
{
"start": 866,
"end": 1435
}
|
class ____ {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ReturnsNullCollection.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import com.google.common.collect.Multimap;
import com.google.common.collect.Table;
import java.util.Collection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
|
ReturnsNullCollectionTest
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/language/BeanAnnotationParameterTwoTest.java
|
{
"start": 2694,
"end": 3093
}
|
class ____ {
public String callA(
@Bean(ref = "GreetingService", method = "english") String greeting,
@Bean(ref = "GreetingService", method = "french") String french, String body) {
return greeting + "/" + french + " " + body;
}
public String callB() {
return "Bye World";
}
}
public static final
|
MyBean
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java
|
{
"start": 22187,
"end": 22440
}
|
class ____ {}
@Configuration
@ComponentScan(basePackages = "example.scannable",
useDefaultFilters = false,
includeFilters = {
@Filter(CustomStereotype.class),
@Filter(CustomComponent.class)
}
)
|
ComponentScanWithScopedProxyThroughAspectJPattern
|
java
|
apache__flink
|
flink-tests/src/test/java/org/apache/flink/test/manual/StreamingScalabilityAndLatency.java
|
{
"start": 3936,
"end": 4835
}
|
class ____ implements ParallelSourceFunction<Tuple2<Long, Long>> {
private static final long serialVersionUID = -151782334777482511L;
private volatile boolean running = true;
@Override
public void run(SourceContext<Tuple2<Long, Long>> ctx) throws Exception {
long num = 100;
long counter = (long) (Math.random() * 4096);
while (running) {
if (num < 100) {
num++;
ctx.collect(new Tuple2<Long, Long>(counter++, 0L));
} else {
num = 0;
ctx.collect(new Tuple2<Long, Long>(counter++, System.currentTimeMillis()));
}
Thread.sleep(1);
}
}
@Override
public void cancel() {
running = false;
}
}
private static
|
TimeStampingSource
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/ResourceTypeInfo.java
|
{
"start": 1245,
"end": 5786
}
|
class ____ implements Comparable<ResourceTypeInfo> {
/**
* Get the name for the resource.
*
* @return resource name
*/
public abstract String getName();
/**
* Set the name for the resource.
*
* @param rName
* name for the resource
*/
public abstract void setName(String rName);
/**
* Get units for the resource.
*
* @return units for the resource
*/
public abstract String getDefaultUnit();
/**
* Set the units for the resource.
*
* @param rUnits
* units for the resource
*/
public abstract void setDefaultUnit(String rUnits);
/**
* Get the resource type.
*
* @return the resource type
*/
public abstract ResourceTypes getResourceType();
/**
* Set the resource type.
*
* @param type
* the resource type
*/
public abstract void setResourceType(ResourceTypes type);
/**
* Create a new instance of ResourceTypeInfo from another object.
*
* @param other
* the object from which the new object should be created
* @return the new ResourceTypeInfo object
*/
@InterfaceAudience.Public
@InterfaceStability.Unstable
public static ResourceTypeInfo newInstance(ResourceTypeInfo other) {
ResourceTypeInfo resourceType = Records.newRecord(ResourceTypeInfo.class);
copy(other, resourceType);
return resourceType;
}
/**
* Create a new instance of ResourceTypeInfo from name, units and type.
*
* @param name name of resource type
* @param units units of resource type
* @param type such as countable, etc.
* @return the new ResourceTypeInfo object
*/
@InterfaceAudience.Public
@InterfaceStability.Unstable
public static ResourceTypeInfo newInstance(String name, String units,
ResourceTypes type) {
ResourceTypeInfo resourceType = Records.newRecord(ResourceTypeInfo.class);
resourceType.setName(name);
resourceType.setResourceType(type);
resourceType.setDefaultUnit(units);
return resourceType;
}
/**
* Create a new instance of ResourceTypeInfo from name, units.
*
* @param name name of resource type
* @param units units of resource type
* @return the new ResourceTypeInfo object
*/
@InterfaceAudience.Public
@InterfaceStability.Unstable
public static ResourceTypeInfo newInstance(String name, String units) {
return ResourceTypeInfo.newInstance(name, units, ResourceTypes.COUNTABLE);
}
/**
* Create a new instance of ResourceTypeInfo from name.
*
* @param name name of resource type
* @return the new ResourceTypeInfo object
*/
@InterfaceAudience.Public
@InterfaceStability.Unstable
public static ResourceTypeInfo newInstance(String name) {
return ResourceTypeInfo.newInstance(name, "");
}
/**
* Copies the content of the source ResourceTypeInfo object to the
* destination object, overwriting all properties of the destination object.
*
* @param src
* Source ResourceTypeInfo object
* @param dst
* Destination ResourceTypeInfo object
*/
public static void copy(ResourceTypeInfo src, ResourceTypeInfo dst) {
dst.setName(src.getName());
dst.setResourceType(src.getResourceType());
dst.setDefaultUnit(src.getDefaultUnit());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.getName());
if (!this.getDefaultUnit().isEmpty()) {
sb.append(" (unit=").append(this.getDefaultUnit()).append(")");
}
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof ResourceTypeInfo)) {
return false;
}
ResourceTypeInfo r = (ResourceTypeInfo) obj;
return this.getName().equals(r.getName())
&& this.getResourceType().equals(r.getResourceType())
&& this.getDefaultUnit().equals(r.getDefaultUnit());
}
@Override
public int hashCode() {
final int prime = 47;
int result = prime + getName().hashCode();
result = prime * result + getResourceType().hashCode();
return result;
}
@Override
public int compareTo(ResourceTypeInfo other) {
int diff = this.getName().compareTo(other.getName());
if (diff == 0) {
diff = this.getDefaultUnit().compareTo(other.getDefaultUnit());
if (diff == 0) {
diff = this.getResourceType().compareTo(other.getResourceType());
}
}
return diff;
}
}
|
ResourceTypeInfo
|
java
|
apache__avro
|
lang/java/mapred/src/main/java/org/apache/avro/hadoop/io/AvroSequenceFile.java
|
{
"start": 14475,
"end": 14797
}
|
class ____ the key records.
*
* @return The key class.
*/
public Class<?> getKeyClass() {
if (null == mKeyClass) {
throw new RuntimeException("Must call Options.withKeyClass() or Options.withKeySchema()");
}
return mKeyClass;
}
/**
* Gets the
|
of
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java
|
{
"start": 6503,
"end": 6678
}
|
class ____ implements A {
@DoNotCall
@Override
public final void f() {}
}
""")
.doTest();
}
// The
|
B
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/metrics/scope/JobManagerOperatorScopeFormat.java
|
{
"start": 1149,
"end": 2322
}
|
class ____ extends ScopeFormat {
public JobManagerOperatorScopeFormat(String format, JobManagerJobScopeFormat parentFormat) {
super(
format,
parentFormat,
new String[] {
SCOPE_HOST,
SCOPE_JOB_ID,
SCOPE_JOB_NAME,
SCOPE_TASK_VERTEX_ID,
SCOPE_TASK_NAME,
SCOPE_OPERATOR_ID,
SCOPE_OPERATOR_NAME
});
}
public String[] formatScope(
JobManagerJobMetricGroup parent,
AbstractID vertexId,
String taskName,
OperatorID operatorID,
String operatorName) {
final String[] template = copyTemplate();
final String[] values = {
parent.parent().hostname(),
valueOrNull(parent.jobId()),
valueOrNull(parent.jobName()),
valueOrNull(vertexId),
valueOrNull(taskName),
valueOrNull(operatorID),
valueOrNull(operatorName)
};
return bindVariables(template, values);
}
}
|
JobManagerOperatorScopeFormat
|
java
|
apache__rocketmq
|
store/src/main/java/org/apache/rocketmq/store/queue/ConsumeQueueStore.java
|
{
"start": 35160,
"end": 36696
}
|
class ____ {
protected long lastPhysicalMinOffset = 0;
public void run() {
try {
this.deleteExpiredFiles();
} catch (Throwable e) {
log.warn(this.getServiceName() + " service has exception. ", e);
}
}
protected void deleteExpiredFiles() {
int deleteLogicsFilesInterval = messageStoreConfig.getDeleteConsumeQueueFilesInterval();
long minOffset = messageStore.getCommitLog().getMinOffset();
if (minOffset > this.lastPhysicalMinOffset) {
this.lastPhysicalMinOffset = minOffset;
for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : consumeQueueTable.values()) {
for (ConsumeQueueInterface logic : maps.values()) {
int deleteCount = deleteExpiredFile(logic, minOffset);
if (deleteCount > 0 && deleteLogicsFilesInterval > 0) {
try {
Thread.sleep(deleteLogicsFilesInterval);
} catch (InterruptedException ignored) {
}
}
}
}
messageStore.getIndexService().deleteExpiredFile(minOffset);
}
}
public String getServiceName() {
return messageStore.getBrokerConfig().getIdentifier() + CleanConsumeQueueService.class.getSimpleName();
}
}
}
|
CleanConsumeQueueService
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/math/Pi.java
|
{
"start": 978,
"end": 1959
}
|
class ____ extends DoubleConstantFunction {
public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(Expression.class, "Pi", Pi::new);
@FunctionInfo(
returnType = "double",
description = "Returns {wikipedia}/Pi[Pi], the ratio of a circle’s circumference to its diameter.",
examples = @Example(file = "math", tag = "pi")
)
public Pi(Source source) {
super(source);
}
private Pi(StreamInput in) throws IOException {
this(Source.readFrom((PlanStreamInput) in));
}
@Override
public void writeTo(StreamOutput out) throws IOException {
Source.EMPTY.writeTo(out);
}
@Override
public String getWriteableName() {
return ENTRY.name;
}
@Override
public Object fold(FoldContext ctx) {
return Math.PI;
}
@Override
public Expression replaceChildren(List<Expression> newChildren) {
return new Pi(source());
}
}
|
Pi
|
java
|
apache__kafka
|
trogdor/src/main/java/org/apache/kafka/trogdor/workload/TimeIntervalTransactionsGenerator.java
|
{
"start": 1089,
"end": 2425
}
|
class ____ implements TransactionGenerator {
private static final long NULL_START_MS = -1;
private final Time time;
private final int intervalMs;
private long lastTransactionStartMs = NULL_START_MS;
@JsonCreator
public TimeIntervalTransactionsGenerator(@JsonProperty("transactionIntervalMs") int intervalMs) {
this(intervalMs, Time.SYSTEM);
}
TimeIntervalTransactionsGenerator(@JsonProperty("transactionIntervalMs") int intervalMs,
Time time) {
if (intervalMs < 1) {
throw new IllegalArgumentException("Cannot have a negative interval");
}
this.time = time;
this.intervalMs = intervalMs;
}
@JsonProperty
public int transactionIntervalMs() {
return intervalMs;
}
@Override
public synchronized TransactionAction nextAction() {
if (lastTransactionStartMs == NULL_START_MS) {
lastTransactionStartMs = time.milliseconds();
return TransactionAction.BEGIN_TRANSACTION;
}
if (time.milliseconds() - lastTransactionStartMs >= intervalMs) {
lastTransactionStartMs = NULL_START_MS;
return TransactionAction.COMMIT_TRANSACTION;
}
return TransactionAction.NO_OP;
}
}
|
TimeIntervalTransactionsGenerator
|
java
|
elastic__elasticsearch
|
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionModuleCheckTaskProvider.java
|
{
"start": 4356,
"end": 5816
}
|
class ____ their root. */
private static void assertAllESJarsAreModular(Path libPath) throws IOException {
try (var s = Files.walk(libPath, 1)) {
s.filter(Files::isRegularFile).filter(isESJar).filter(isNotExcluded).sorted().forEach(path -> {
try (JarFile jf = new JarFile(path.toFile())) {
JarEntry entry = jf.getJarEntry(MODULE_INFO);
if (entry == null) {
throw new GradleException(MODULE_INFO + " no found in " + path);
}
} catch (IOException e) {
throw new GradleException("Failed when reading jar file " + path, e);
}
});
}
}
/** Checks that all expected Elasticsearch modules are present. */
private static void assertAllModulesPresent(Path libPath) {
List<String> actualESModules = ModuleFinder.of(libPath).findAll().stream().filter(isESModule).map(toName).sorted().toList();
if (actualESModules.equals(EXPECTED_ES_SERVER_MODULES) == false) {
throw new GradleException(
"expected modules " + listToString(EXPECTED_ES_SERVER_MODULES) + ", \nactual modules " + listToString(actualESModules)
);
}
}
// ####: eventually assert hashes, etc
static String listToString(List<String> list) {
return list.stream().sorted().collect(joining("\n ", "[\n ", "]"));
}
}
|
in
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/TaskID.java
|
{
"start": 8446,
"end": 9646
}
|
class ____ {
private static EnumMap<TaskType, Character> typeToCharMap =
new EnumMap<TaskType,Character>(TaskType.class);
private static Map<Character, TaskType> charToTypeMap =
new HashMap<Character, TaskType>();
static String allTaskTypes = "(m|r|s|c|t)";
static {
setupTaskTypeToCharMapping();
setupCharToTaskTypeMapping();
}
private static void setupTaskTypeToCharMapping() {
typeToCharMap.put(TaskType.MAP, 'm');
typeToCharMap.put(TaskType.REDUCE, 'r');
typeToCharMap.put(TaskType.JOB_SETUP, 's');
typeToCharMap.put(TaskType.JOB_CLEANUP, 'c');
typeToCharMap.put(TaskType.TASK_CLEANUP, 't');
}
private static void setupCharToTaskTypeMapping() {
charToTypeMap.put('m', TaskType.MAP);
charToTypeMap.put('r', TaskType.REDUCE);
charToTypeMap.put('s', TaskType.JOB_SETUP);
charToTypeMap.put('c', TaskType.JOB_CLEANUP);
charToTypeMap.put('t', TaskType.TASK_CLEANUP);
}
static char getRepresentingCharacter(TaskType type) {
return typeToCharMap.get(type);
}
static TaskType getTaskType(char c) {
return charToTypeMap.get(c);
}
}
}
|
CharTaskTypeMaps
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableTakeLast.java
|
{
"start": 1246,
"end": 2874
}
|
class ____<T> extends ArrayDeque<T> implements Observer<T>, Disposable {
private static final long serialVersionUID = 7240042530241604978L;
final Observer<? super T> downstream;
final int count;
Disposable upstream;
volatile boolean cancelled;
TakeLastObserver(Observer<? super T> actual, int count) {
this.downstream = actual;
this.count = count;
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.upstream, d)) {
this.upstream = d;
downstream.onSubscribe(this);
}
}
@Override
public void onNext(T t) {
if (count == size()) {
poll();
}
offer(t);
}
@Override
public void onError(Throwable t) {
downstream.onError(t);
}
@Override
public void onComplete() {
Observer<? super T> a = downstream;
for (;;) {
if (cancelled) {
return;
}
T v = poll();
if (v == null) {
a.onComplete();
return;
}
a.onNext(v);
}
}
@Override
public void dispose() {
if (!cancelled) {
cancelled = true;
upstream.dispose();
}
}
@Override
public boolean isDisposed() {
return cancelled;
}
}
}
|
TakeLastObserver
|
java
|
quarkusio__quarkus
|
core/runtime/src/main/java/io/quarkus/runtime/RuntimeValue.java
|
{
"start": 187,
"end": 596
}
|
class ____<T> {
private final T value;
public RuntimeValue(T value) {
Objects.requireNonNull(value);
this.value = value;
}
public RuntimeValue() {
this.value = null;
}
public T getValue() {
if (value == null) {
throw new IllegalStateException("Cannot call getValue() at deployment time");
}
return value;
}
}
|
RuntimeValue
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/tck/TakeLastTckTest.java
|
{
"start": 772,
"end": 1009
}
|
class ____ extends BaseTck<Integer> {
@Override
public Publisher<Integer> createPublisher(long elements) {
return
Flowable.range(0, (int)elements * 2).takeLast((int)elements)
;
}
}
|
TakeLastTckTest
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/integration/MockitoSpyBeanUsedDuringApplicationContextRefreshIntegrationTests.java
|
{
"start": 2283,
"end": 2620
}
|
class ____ {
@Bean
ContextRefreshedEventProcessor eventProcessor() {
// Cannot be a lambda expression, since Mockito cannot create a spy for a lambda.
return new ContextRefreshedEventProcessor() {
@Override
public void process(ContextRefreshedEvent event) {
contextRefreshedEvent = event;
}
};
}
}
|
Config
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/bugs/_1590/BookMapper.java
|
{
"start": 298,
"end": 454
}
|
interface ____ {
BookMapper INSTANCE = Mappers.getMapper( BookMapper.class );
Book map(Book book);
List<Book> map(List<Book> books);
}
|
BookMapper
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/JSONObjectTest_get.java
|
{
"start": 223,
"end": 463
}
|
class ____ extends TestCase {
public void test_get() throws Exception {
JSONObject obj = JSON.parseObject("{id:123}");
Assert.assertEquals(123, obj.getObject("id", Object.class));
}
public static
|
JSONObjectTest_get
|
java
|
alibaba__nacos
|
config/src/main/java/com/alibaba/nacos/config/server/utils/YamlParserUtil.java
|
{
"start": 2836,
"end": 3388
}
|
class ____ extends Representer {
public CustomRepresenter() {
super(new DumperOptions());
}
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
Tag customTag) {
if (propertyValue == null) {
return null;
} else {
return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
}
}
}
public static
|
CustomRepresenter
|
java
|
google__guava
|
android/guava/src/com/google/common/util/concurrent/ForwardingFluentFuture.java
|
{
"start": 1083,
"end": 1445
}
|
class ____ {@code FluentFuture} but with extra methods, we recommend declaring your
* own subclass of {@link ListenableFuture}, complete with a method like {@link #from} to adapt an
* existing {@code ListenableFuture}, implemented atop a {@link ForwardingListenableFuture} that
* forwards to that future and adds the desired methods.
*/
@GwtCompatible
final
|
like
|
java
|
micronaut-projects__micronaut-core
|
inject/src/main/java/io/micronaut/inject/qualifiers/InterceptorBindingQualifier.java
|
{
"start": 1592,
"end": 9417
}
|
class ____<T> extends FilteringQualifier<T> {
public static final String META_BINDING_VALUES = "$bindingValues";
public static final String META_MEMBER_INTERCEPTOR_TYPE = "interceptorType";
private final Map<String, List<AnnotationValue<?>>> supportedAnnotationNames;
private final Set<String> supportedInterceptorTypes;
InterceptorBindingQualifier(AnnotationMetadata annotationMetadata) {
Collection<AnnotationValue<Annotation>> annotationValues;
AnnotationValue<Annotation> av = annotationMetadata.findAnnotation(AnnotationUtil.ANN_INTERCEPTOR_BINDING_QUALIFIER).orElse(null);
if (av == null) {
annotationValues = Collections.emptyList();
} else {
annotationValues = av.getAnnotations(AnnotationMetadata.VALUE_MEMBER);
}
if (annotationValues.isEmpty()) {
annotationValues = annotationMetadata.getAnnotationValuesByName(AnnotationUtil.ANN_INTERCEPTOR_BINDING);
}
supportedAnnotationNames = findSupportedAnnotations(annotationValues);
Set<String> supportedInterceptorTypes = CollectionUtils.newHashSet(annotationValues.size());
for (AnnotationValue<?> annotationValue : annotationValues) {
annotationValue.annotationClassValue(META_MEMBER_INTERCEPTOR_TYPE).map(AnnotationClassValue::getName).ifPresent(supportedInterceptorTypes::add);
}
this.supportedInterceptorTypes = supportedInterceptorTypes;
}
/**
* Interceptor binding qualifiers.
* @param bindingAnnotations The binding annotations
*/
InterceptorBindingQualifier(Collection<AnnotationValue<Annotation>> bindingAnnotations) {
if (CollectionUtils.isNotEmpty(bindingAnnotations)) {
supportedAnnotationNames = findSupportedAnnotations(bindingAnnotations);
} else {
this.supportedAnnotationNames = Collections.emptyMap();
}
this.supportedInterceptorTypes = Collections.emptySet();
}
private static Map<String, List<AnnotationValue<?>>> findSupportedAnnotations(Collection<AnnotationValue<Annotation>> annotationValues) {
final Map<String, List<AnnotationValue<?>>> supportedAnnotationNames = CollectionUtils.newHashMap(annotationValues.size());
for (AnnotationValue<?> annotationValue : annotationValues) {
final String name = annotationValue.stringValue().orElse(null);
if (name == null) {
continue;
}
final AnnotationValue<?> members = annotationValue.getAnnotation(META_BINDING_VALUES).orElse(null);
if (members != null) {
List<AnnotationValue<?>> existing = supportedAnnotationNames
.computeIfAbsent(name, k -> new ArrayList<>(5));
existing.add(members);
} else {
supportedAnnotationNames.put(name, null);
}
}
return supportedAnnotationNames;
}
@Override
public boolean doesQualify(Class<T> beanType, BeanType<T> candidate) {
if (supportedInterceptorTypes.contains(candidate.getBeanType().getName())) {
return true;
}
if (supportedAnnotationNames.isEmpty()) {
return false;
}
final AnnotationMetadata annotationMetadata = candidate.getAnnotationMetadata();
Collection<AnnotationValue<Annotation>> interceptorValues = resolveInterceptorAnnotationValues(annotationMetadata, null);
if (interceptorValues.isEmpty()) {
return false;
}
if (interceptorValues.size() == 1) {
// single binding case, fast path
final AnnotationValue<?> interceptorBinding = interceptorValues.iterator().next();
final String annotationName = interceptorBinding.stringValue().orElse(null);
if (annotationName == null) {
return false;
}
final List<AnnotationValue<?>> bindingList = supportedAnnotationNames.get(annotationName);
if (bindingList != null) {
final AnnotationValue<Annotation> otherBinding =
interceptorBinding.getAnnotation(META_BINDING_VALUES).orElse(null);
boolean matched = true;
for (AnnotationValue<?> binding : bindingList) {
matched = matched && (!binding.isPresent(META_BINDING_VALUES) || binding.equals(otherBinding));
}
return matched;
}
return supportedAnnotationNames.containsKey(annotationName);
} else {
// multiple binding case
boolean matched = false;
for (AnnotationValue<?> annotation : interceptorValues) {
final String annotationName = annotation.stringValue().orElse(null);
if (annotationName == null) {
continue;
}
final List<AnnotationValue<?>> bindingList = supportedAnnotationNames.get(annotationName);
if (bindingList != null) {
final AnnotationValue<Annotation> otherBinding =
annotation.getAnnotation(META_BINDING_VALUES).orElse(null);
for (AnnotationValue<?> binding : bindingList) {
matched = (!binding.isPresent(META_BINDING_VALUES) || binding.equals(otherBinding));
if (matched) {
break;
}
}
} else {
matched = supportedAnnotationNames.containsKey(annotationName);
}
if (matched) {
break;
}
}
return matched;
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InterceptorBindingQualifier<?> that = (InterceptorBindingQualifier<?>) o;
return supportedAnnotationNames.equals(that.supportedAnnotationNames) && supportedInterceptorTypes.equals(that.supportedInterceptorTypes);
}
@Override
public int hashCode() {
return ObjectUtils.hash(supportedAnnotationNames, supportedInterceptorTypes);
}
@Override
public String toString() {
if (CollectionUtils.isEmpty(supportedAnnotationNames) && CollectionUtils.isEmpty(supportedInterceptorTypes)) {
return "@InterceptorBinding(NONE)";
} else {
return supportedAnnotationNames.keySet().stream().map((name) -> "@InterceptorBinding(" + NameUtils.getShortenedName(name) + ")").collect(Collectors.joining(" ")) +
supportedInterceptorTypes.stream().map((type) -> "@InterceptorBinding(interceptorType = " + NameUtils.getShortenedName(type) + ")").collect(Collectors.joining(" "));
}
}
private static @NonNull Collection<AnnotationValue<Annotation>> resolveInterceptorAnnotationValues(
@NonNull AnnotationMetadata annotationMetadata,
@Nullable String kind) {
List<AnnotationValue<Annotation>> bindings = annotationMetadata.getAnnotationValuesByName(AnnotationUtil.ANN_INTERCEPTOR_BINDING);
if (CollectionUtils.isEmpty(bindings)) {
return Collections.emptyList();
}
List<AnnotationValue<Annotation>> result = new ArrayList<>(bindings.size());
for (AnnotationValue<Annotation> av : bindings) {
if (av.stringValue().isEmpty()) {
continue;
}
if (kind == null || av.stringValue("kind").orElse(kind).equals(kind)) {
result.add(av);
}
}
return result;
}
}
|
InterceptorBindingQualifier
|
java
|
assertj__assertj-core
|
assertj-tests/assertj-integration-tests/assertj-core-spring-boot/src/test/java/org/assertj/tests/core/api/recursive/comparison/Issue_3533_Test.java
|
{
"start": 2576,
"end": 3158
}
|
class ____ {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String postalCode;
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 String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public City() {}
}
|
City
|
java
|
spring-projects__spring-boot
|
buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleTests.java
|
{
"start": 3441,
"end": 27513
}
|
class ____ {
private TestPrintStream out;
private DockerApi docker;
private final Map<String, ContainerConfig> configs = new LinkedHashMap<>();
private final Map<String, ContainerContent> content = new LinkedHashMap<>();
@BeforeEach
void setup() {
this.out = new TestPrintStream();
this.docker = mockDockerApi();
}
@ParameterizedTest
@BooleanValueSource
void executeExecutesPhases(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
createLifecycle(trustBuilder).execute();
if (trustBuilder) {
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator.json"));
}
else {
assertPhaseWasRun("analyzer", withExpectedConfig("lifecycle-analyzer.json"));
assertPhaseWasRun("detector", withExpectedConfig("lifecycle-detector.json"));
assertPhaseWasRun("restorer", withExpectedConfig("lifecycle-restorer.json"));
assertPhaseWasRun("builder", withExpectedConfig("lifecycle-builder.json"));
assertPhaseWasRun("exporter", withExpectedConfig("lifecycle-exporter.json"));
}
assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'");
}
@Test
void executeWithBindingsExecutesPhases() throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
BuildRequest request = getTestRequest(true).withBindings(Binding.of("/host/src/path:/container/dest/path:ro"),
Binding.of("volume-name:/container/volume/path:rw"));
createLifecycle(request).execute();
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-bindings.json"));
assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'");
}
@Test
void executeExecutesPhasesWithPlatformApi03() throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
createLifecycle(true, "builder-metadata-platform-api-0.3.json").execute();
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-platform-api-0.3.json"));
assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'");
}
@ParameterizedTest
@BooleanValueSource
void executeOnlyUploadsContentOnce(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
createLifecycle(trustBuilder).execute();
assertThat(this.content).hasSize(1);
}
@ParameterizedTest
@BooleanValueSource
void executeWhenAlreadyRunThrowsException(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
Lifecycle lifecycle = createLifecycle(trustBuilder);
lifecycle.execute();
assertThatIllegalStateException().isThrownBy(lifecycle::execute)
.withMessage("Lifecycle has already been executed");
}
@ParameterizedTest
@BooleanValueSource
void executeWhenBuilderReturnsErrorThrowsException(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(9, null));
assertThatExceptionOfType(BuilderException.class).isThrownBy(() -> createLifecycle(trustBuilder).execute())
.withMessage(
"Builder lifecycle '" + ((trustBuilder) ? "creator" : "analyzer") + "' failed with status code 9");
}
@ParameterizedTest
@BooleanValueSource
void executeWhenCleanCacheClearsCache(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
BuildRequest request = getTestRequest(trustBuilder).withCleanCache(true);
createLifecycle(request).execute();
if (trustBuilder) {
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-clean-cache.json"));
}
else {
assertPhaseWasRun("analyzer", withExpectedConfig("lifecycle-analyzer.json"));
assertPhaseWasRun("detector", withExpectedConfig("lifecycle-detector.json"));
assertPhaseWasRun("builder", withExpectedConfig("lifecycle-builder.json"));
assertPhaseWasRun("exporter", withExpectedConfig("lifecycle-exporter.json"));
assertThat(this.out.toString()).contains("Skipping restorer because 'cleanCache' is enabled");
}
VolumeName name = VolumeName.of("pack-cache-b35197ac41ea.build");
then(this.docker.volume()).should().delete(name, true);
}
@Test
void executeWhenPlatformApiNotSupportedThrowsException() throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
assertThatIllegalStateException()
.isThrownBy(() -> createLifecycle(true, "builder-metadata-unsupported-api.json").execute())
.withMessageContaining("Detected platform API versions '0.2' are not included in supported versions");
}
@Test
void executeWhenMultiplePlatformApisNotSupportedThrowsException() throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
assertThatIllegalStateException()
.isThrownBy(() -> createLifecycle(true, "builder-metadata-unsupported-apis.json").execute())
.withMessageContaining("Detected platform API versions '0.1,0.2' are not included in supported versions");
}
@ParameterizedTest
@BooleanValueSource
void executeWhenMultiplePlatformApisSupportedExecutesPhase(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
createLifecycle(trustBuilder, "builder-metadata-supported-apis.json").execute();
if (trustBuilder) {
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator.json"));
}
else {
assertPhaseWasRun("analyzer", withExpectedConfig("lifecycle-analyzer.json"));
assertPhaseWasRun("detector", withExpectedConfig("lifecycle-detector.json"));
assertPhaseWasRun("restorer", withExpectedConfig("lifecycle-restorer.json"));
assertPhaseWasRun("builder", withExpectedConfig("lifecycle-builder.json"));
assertPhaseWasRun("exporter", withExpectedConfig("lifecycle-exporter.json"));
}
}
@Test
void closeClearsVolumes() throws Exception {
createLifecycle(true).close();
then(this.docker.volume()).should().delete(VolumeName.of("pack-layers-aaaaaaaaaa"), true);
then(this.docker.volume()).should().delete(VolumeName.of("pack-app-aaaaaaaaaa"), true);
}
@Test
void executeWithNetworkExecutesPhases() throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
BuildRequest request = getTestRequest(true).withNetwork("test");
createLifecycle(request).execute();
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-network.json"));
assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'");
}
@ParameterizedTest
@BooleanValueSource
void executeWithCacheVolumeNamesExecutesPhases(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
BuildRequest request = getTestRequest(trustBuilder).withBuildWorkspace(Cache.volume("work-volume"))
.withBuildCache(Cache.volume("build-volume"))
.withLaunchCache(Cache.volume("launch-volume"));
createLifecycle(request).execute();
if (trustBuilder) {
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-cache-volumes.json"));
}
else {
assertPhaseWasRun("analyzer", withExpectedConfig("lifecycle-analyzer-cache-volumes.json"));
assertPhaseWasRun("detector", withExpectedConfig("lifecycle-detector-cache-volumes.json"));
assertPhaseWasRun("restorer", withExpectedConfig("lifecycle-restorer-cache-volumes.json"));
assertPhaseWasRun("builder", withExpectedConfig("lifecycle-builder-cache-volumes.json"));
assertPhaseWasRun("exporter", withExpectedConfig("lifecycle-exporter-cache-volumes.json"));
}
assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'");
}
@ParameterizedTest
@BooleanValueSource
void executeWithCacheBindMountsExecutesPhases(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
BuildRequest request = getTestRequest(trustBuilder).withBuildWorkspace(Cache.bind("/tmp/work"))
.withBuildCache(Cache.bind("/tmp/build-cache"))
.withLaunchCache(Cache.bind("/tmp/launch-cache"));
createLifecycle(request).execute();
if (trustBuilder) {
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-cache-bind-mounts.json"));
}
else {
assertPhaseWasRun("analyzer", withExpectedConfig("lifecycle-analyzer-cache-bind-mounts.json"));
assertPhaseWasRun("detector", withExpectedConfig("lifecycle-detector-cache-bind-mounts.json"));
assertPhaseWasRun("restorer", withExpectedConfig("lifecycle-restorer-cache-bind-mounts.json"));
assertPhaseWasRun("builder", withExpectedConfig("lifecycle-builder-cache-bind-mounts.json"));
assertPhaseWasRun("exporter", withExpectedConfig("lifecycle-exporter-cache-bind-mounts.json"));
}
assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'");
}
@ParameterizedTest
@BooleanValueSource
void executeWithCreatedDateExecutesPhases(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
BuildRequest request = getTestRequest(trustBuilder).withCreatedDate("2020-07-01T12:34:56Z");
createLifecycle(request).execute();
if (trustBuilder) {
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-created-date.json"));
}
else {
assertPhaseWasRun("analyzer", withExpectedConfig("lifecycle-analyzer.json"));
assertPhaseWasRun("detector", withExpectedConfig("lifecycle-detector.json"));
assertPhaseWasRun("restorer", withExpectedConfig("lifecycle-restorer.json"));
assertPhaseWasRun("builder", withExpectedConfig("lifecycle-builder.json"));
assertPhaseWasRun("exporter", withExpectedConfig("lifecycle-exporter-created-date.json"));
}
assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'");
}
@ParameterizedTest
@BooleanValueSource
void executeWithApplicationDirectoryExecutesPhases(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
BuildRequest request = getTestRequest(trustBuilder).withApplicationDirectory("/application");
createLifecycle(request).execute();
if (trustBuilder) {
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-app-dir.json"));
}
else {
assertPhaseWasRun("analyzer", withExpectedConfig("lifecycle-analyzer.json"));
assertPhaseWasRun("detector", withExpectedConfig("lifecycle-detector-app-dir.json"));
assertPhaseWasRun("restorer", withExpectedConfig("lifecycle-restorer.json"));
assertPhaseWasRun("builder", withExpectedConfig("lifecycle-builder-app-dir.json"));
assertPhaseWasRun("exporter", withExpectedConfig("lifecycle-exporter-app-dir.json"));
}
assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'");
}
@ParameterizedTest
@BooleanValueSource
void executeWithSecurityOptionsExecutesPhases(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
BuildRequest request = getTestRequest(trustBuilder)
.withSecurityOptions(List.of("label=user:USER", "label=role:ROLE"));
createLifecycle(request).execute();
if (trustBuilder) {
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-security-opts.json", true));
}
else {
assertPhaseWasRun("analyzer", withExpectedConfig("lifecycle-analyzer-security-opts.json", true));
assertPhaseWasRun("detector", withExpectedConfig("lifecycle-detector.json"));
assertPhaseWasRun("restorer", withExpectedConfig("lifecycle-restorer-security-opts.json", true));
assertPhaseWasRun("builder", withExpectedConfig("lifecycle-builder.json"));
assertPhaseWasRun("exporter", withExpectedConfig("lifecycle-exporter-security-opts.json", true));
}
assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'");
}
@ParameterizedTest
@BooleanValueSource
void executeWithDockerHostAndRemoteAddressExecutesPhases(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
BuildRequest request = getTestRequest(trustBuilder);
createLifecycle(request,
ResolvedDockerHost.from(new DockerConnectionConfiguration.Host("tcp://192.168.1.2:2376")))
.execute();
if (trustBuilder) {
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-inherit-remote.json"));
}
else {
assertPhaseWasRun("analyzer", withExpectedConfig("lifecycle-analyzer-inherit-remote.json"));
assertPhaseWasRun("detector", withExpectedConfig("lifecycle-detector.json"));
assertPhaseWasRun("restorer", withExpectedConfig("lifecycle-restorer-inherit-remote.json"));
assertPhaseWasRun("builder", withExpectedConfig("lifecycle-builder.json"));
assertPhaseWasRun("exporter", withExpectedConfig("lifecycle-exporter-inherit-remote.json"));
}
assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'");
}
@ParameterizedTest
@BooleanValueSource
void executeWithDockerHostAndLocalAddressExecutesPhases(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), isNull())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), isNull(), any())).willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
BuildRequest request = getTestRequest(trustBuilder);
createLifecycle(request, ResolvedDockerHost.from(new DockerConnectionConfiguration.Host("/var/alt.sock")))
.execute();
if (trustBuilder) {
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-inherit-local.json"));
}
else {
assertPhaseWasRun("analyzer", withExpectedConfig("lifecycle-analyzer-inherit-local.json"));
assertPhaseWasRun("detector", withExpectedConfig("lifecycle-detector.json"));
assertPhaseWasRun("restorer", withExpectedConfig("lifecycle-restorer-inherit-local.json"));
assertPhaseWasRun("builder", withExpectedConfig("lifecycle-builder.json"));
assertPhaseWasRun("exporter", withExpectedConfig("lifecycle-exporter-inherit-local.json"));
}
assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'");
}
@ParameterizedTest
@BooleanValueSource
void executeWithImagePlatformExecutesPhases(boolean trustBuilder) throws Exception {
given(this.docker.container().create(any(), eq(ImagePlatform.of("linux/arm64"))))
.willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().create(any(), eq(ImagePlatform.of("linux/arm64")), any()))
.willAnswer(answerWithGeneratedContainerId());
given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null));
BuildRequest request = getTestRequest(trustBuilder).withImagePlatform("linux/arm64");
createLifecycle(request).execute();
if (trustBuilder) {
assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator.json"));
}
else {
assertPhaseWasRun("analyzer", withExpectedConfig("lifecycle-analyzer.json"));
assertPhaseWasRun("detector", withExpectedConfig("lifecycle-detector.json"));
assertPhaseWasRun("restorer", withExpectedConfig("lifecycle-restorer.json"));
assertPhaseWasRun("builder", withExpectedConfig("lifecycle-builder.json"));
assertPhaseWasRun("exporter", withExpectedConfig("lifecycle-exporter.json"));
}
assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'");
}
private DockerApi mockDockerApi() {
DockerApi docker = mock(DockerApi.class);
ImageApi imageApi = mock(ImageApi.class);
ContainerApi containerApi = mock(ContainerApi.class);
VolumeApi volumeApi = mock(VolumeApi.class);
given(docker.image()).willReturn(imageApi);
given(docker.container()).willReturn(containerApi);
given(docker.volume()).willReturn(volumeApi);
return docker;
}
private BuildRequest getTestRequest(boolean trustBuilder) {
TarArchive content = mock(TarArchive.class);
ImageReference name = ImageReference.of("my-application");
return BuildRequest.of(name, (owner) -> content)
.withRunImage(ImageReference.of("cloudfoundry/run"))
.withTrustBuilder(trustBuilder);
}
private Lifecycle createLifecycle(boolean trustBuilder) throws IOException {
return createLifecycle(getTestRequest(trustBuilder));
}
private Lifecycle createLifecycle(BuildRequest request) throws IOException {
EphemeralBuilder builder = mockEphemeralBuilder();
return createLifecycle(request, builder);
}
private Lifecycle createLifecycle(boolean trustBuilder, String builderMetadata) throws IOException {
EphemeralBuilder builder = mockEphemeralBuilder(builderMetadata);
return createLifecycle(getTestRequest(trustBuilder), builder);
}
private Lifecycle createLifecycle(BuildRequest request, ResolvedDockerHost dockerHost) throws IOException {
EphemeralBuilder builder = mockEphemeralBuilder();
return new TestLifecycle(BuildLog.to(this.out), this.docker, dockerHost, request, builder);
}
private Lifecycle createLifecycle(BuildRequest request, EphemeralBuilder ephemeralBuilder) {
return new TestLifecycle(BuildLog.to(this.out), this.docker, null, request, ephemeralBuilder);
}
private EphemeralBuilder mockEphemeralBuilder() throws IOException {
return mockEphemeralBuilder("builder-metadata.json");
}
private EphemeralBuilder mockEphemeralBuilder(String builderMetadata) throws IOException {
EphemeralBuilder builder = mock(EphemeralBuilder.class);
byte[] metadataContent = FileCopyUtils.copyToByteArray(getClass().getResourceAsStream(builderMetadata));
BuilderMetadata metadata = BuilderMetadata.fromJson(new String(metadataContent, StandardCharsets.UTF_8));
given(builder.getName()).willReturn(ImageReference.of("pack.local/ephemeral-builder"));
given(builder.getBuilderMetadata()).willReturn(metadata);
return builder;
}
private Answer<ContainerReference> answerWithGeneratedContainerId() {
return (invocation) -> {
ContainerConfig config = invocation.getArgument(0, ContainerConfig.class);
ArrayNode command = getCommand(config);
String name = command.get(0).asString().substring(1).replaceAll("/", "-");
this.configs.put(name, config);
if (invocation.getArguments().length > 2) {
this.content.put(name, invocation.getArgument(2, ContainerContent.class));
}
return ContainerReference.of(name);
};
}
private ArrayNode getCommand(ContainerConfig config) {
JsonNode node = SharedJsonMapper.get().readTree(config.toString());
return (ArrayNode) node.at("/Cmd");
}
private void assertPhaseWasRun(String name, IOConsumer<ContainerConfig> configConsumer) throws IOException {
ContainerReference containerReference = ContainerReference.of("cnb-lifecycle-" + name);
then(this.docker.container()).should().start(containerReference);
then(this.docker.container()).should().logs(eq(containerReference), any());
then(this.docker.container()).should().remove(containerReference, true);
ContainerConfig containerConfig = this.configs.get(containerReference.toString());
assertThat(containerConfig).isNotNull();
configConsumer.accept(containerConfig);
}
private IOConsumer<ContainerConfig> withExpectedConfig(String name) {
return withExpectedConfig(name, false);
}
private IOConsumer<ContainerConfig> withExpectedConfig(String name, boolean expectSecurityOptAlways) {
return (config) -> {
try {
InputStream in = getClass().getResourceAsStream(name);
String jsonString = FileCopyUtils.copyToString(new InputStreamReader(in, StandardCharsets.UTF_8));
JSONObject json = new JSONObject(jsonString);
if (!expectSecurityOptAlways && Platform.isWindows()) {
JSONObject hostConfig = json.getJSONObject("HostConfig");
hostConfig.remove("SecurityOpt");
}
JSONAssert.assertEquals(config.toString(), json, true);
}
catch (JSONException ex) {
throw new IOException(ex);
}
};
}
static
|
LifecycleTests
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/main/java/org/springframework/web/servlet/resource/LiteWebJarsResourceResolver.java
|
{
"start": 1876,
"end": 4082
}
|
class ____ extends AbstractResourceResolver {
private static final int WEBJARS_LOCATION_LENGTH = WebJarVersionLocator.WEBJARS_PATH_PREFIX.length() + 1;
private final WebJarVersionLocator webJarVersionLocator;
/**
* Create a {@code LiteWebJarsResourceResolver} with a default {@code WebJarVersionLocator} instance.
*/
public LiteWebJarsResourceResolver() {
this.webJarVersionLocator = new WebJarVersionLocator();
}
/**
* Create a {@code LiteWebJarsResourceResolver} with a custom {@code WebJarVersionLocator} instance,
* for example, with a custom cache implementation.
*/
public LiteWebJarsResourceResolver(WebJarVersionLocator webJarVersionLocator) {
this.webJarVersionLocator = webJarVersionLocator;
}
@Override
protected @Nullable Resource resolveResourceInternal(@Nullable HttpServletRequest request, String requestPath,
List<? extends Resource> locations, ResourceResolverChain chain) {
Resource resolved = chain.resolveResource(request, requestPath, locations);
if (resolved == null) {
String webJarResourcePath = findWebJarResourcePath(requestPath);
if (webJarResourcePath != null) {
return chain.resolveResource(request, webJarResourcePath, locations);
}
}
return resolved;
}
@Override
protected @Nullable String resolveUrlPathInternal(String resourceUrlPath,
List<? extends Resource> locations, ResourceResolverChain chain) {
String path = chain.resolveUrlPath(resourceUrlPath, locations);
if (path == null) {
String webJarResourcePath = findWebJarResourcePath(resourceUrlPath);
if (webJarResourcePath != null) {
return chain.resolveUrlPath(webJarResourcePath, locations);
}
}
return path;
}
protected @Nullable String findWebJarResourcePath(String path) {
int endOffset = path.indexOf('/', 1);
if (endOffset != -1) {
int startOffset = (path.startsWith("/") ? 1 : 0);
String webjar = path.substring(startOffset, endOffset);
String partialPath = path.substring(endOffset + 1);
String webJarPath = this.webJarVersionLocator.fullPath(webjar, partialPath);
if (webJarPath != null) {
return webJarPath.substring(WEBJARS_LOCATION_LENGTH);
}
}
return null;
}
}
|
LiteWebJarsResourceResolver
|
java
|
assertj__assertj-core
|
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/objectarrays/ObjectArrays_assertAre_Test.java
|
{
"start": 1178,
"end": 1947
}
|
class ____ extends ObjectArraysWithConditionBaseTest {
@Test
void should_pass_if_each_element_satisfies_condition() {
arrays.assertAre(INFO, array("Yoda", "Luke"), jedi);
}
@Test
void should_throw_error_if_condition_is_null() {
assertThatNullPointerException().isThrownBy(() -> arrays.assertAre(INFO, actual, null))
.withMessage("The condition to evaluate should not be null");
}
@Test
void should_fail_if_Condition_is_not_met() {
// GIVEN
var actual = array("Yoda", "Luke", "Leia");
// WHEN
expectAssertionError(() -> arrays.assertAre(INFO, actual, jedi));
// THEN
verify(failures).failure(INFO, elementsShouldBe(actual, newArrayList("Leia"), jedi));
}
}
|
ObjectArrays_assertAre_Test
|
java
|
google__guava
|
android/guava/src/com/google/common/util/concurrent/SimpleTimeLimiter.java
|
{
"start": 3276,
"end": 9787
}
|
interface ____");
Set<Method> interruptibleMethods = findInterruptibleMethods(interfaceType);
InvocationHandler handler =
(obj, method, args) -> {
Callable<@Nullable Object> callable =
() -> {
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
throw throwCause(e, /* combineStackTraces= */ false);
}
};
return callWithTimeout(
callable, timeoutDuration, timeoutUnit, interruptibleMethods.contains(method));
};
return newProxy(interfaceType, handler);
}
// TODO: replace with version in common.reflect if and when it's open-sourced
private static <T> T newProxy(Class<T> interfaceType, InvocationHandler handler) {
Object object =
Proxy.newProxyInstance(
interfaceType.getClassLoader(), new Class<?>[] {interfaceType}, handler);
return interfaceType.cast(object);
}
@ParametricNullness
private <T extends @Nullable Object> T callWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible)
throws Exception {
checkNotNull(callable);
checkNotNull(timeoutUnit);
checkPositiveTimeout(timeoutDuration);
Future<T> future = executor.submit(callable);
try {
return amInterruptible
? future.get(timeoutDuration, timeoutUnit)
: getUninterruptibly(future, timeoutDuration, timeoutUnit);
} catch (InterruptedException e) {
future.cancel(true);
throw e;
} catch (ExecutionException e) {
throw throwCause(e, true /* combineStackTraces */);
} catch (TimeoutException e) {
future.cancel(true);
throw new UncheckedTimeoutException(e);
}
}
@CanIgnoreReturnValue
@Override
@ParametricNullness
public <T extends @Nullable Object> T callWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, InterruptedException, ExecutionException {
checkNotNull(callable);
checkNotNull(timeoutUnit);
checkPositiveTimeout(timeoutDuration);
Future<T> future = executor.submit(callable);
try {
return future.get(timeoutDuration, timeoutUnit);
} catch (InterruptedException | TimeoutException e) {
future.cancel(true /* mayInterruptIfRunning */);
throw e;
} catch (ExecutionException e) {
wrapAndThrowExecutionExceptionOrError(e.getCause());
throw new AssertionError();
}
}
@CanIgnoreReturnValue
@Override
@ParametricNullness
public <T extends @Nullable Object> T callUninterruptiblyWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, ExecutionException {
checkNotNull(callable);
checkNotNull(timeoutUnit);
checkPositiveTimeout(timeoutDuration);
Future<T> future = executor.submit(callable);
try {
return getUninterruptibly(future, timeoutDuration, timeoutUnit);
} catch (TimeoutException e) {
future.cancel(true /* mayInterruptIfRunning */);
throw e;
} catch (ExecutionException e) {
wrapAndThrowExecutionExceptionOrError(e.getCause());
throw new AssertionError();
}
}
@Override
public void runWithTimeout(Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, InterruptedException {
checkNotNull(runnable);
checkNotNull(timeoutUnit);
checkPositiveTimeout(timeoutDuration);
Future<?> future = executor.submit(runnable);
try {
future.get(timeoutDuration, timeoutUnit);
} catch (InterruptedException | TimeoutException e) {
future.cancel(true /* mayInterruptIfRunning */);
throw e;
} catch (ExecutionException e) {
wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause());
throw new AssertionError();
}
}
@Override
public void runUninterruptiblyWithTimeout(
Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit) throws TimeoutException {
checkNotNull(runnable);
checkNotNull(timeoutUnit);
checkPositiveTimeout(timeoutDuration);
Future<?> future = executor.submit(runnable);
try {
getUninterruptibly(future, timeoutDuration, timeoutUnit);
} catch (TimeoutException e) {
future.cancel(true /* mayInterruptIfRunning */);
throw e;
} catch (ExecutionException e) {
wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause());
throw new AssertionError();
}
}
private static Exception throwCause(Exception e, boolean combineStackTraces) throws Exception {
Throwable cause = e.getCause();
if (cause == null) {
throw e;
}
if (combineStackTraces) {
StackTraceElement[] combined =
ObjectArrays.concat(cause.getStackTrace(), e.getStackTrace(), StackTraceElement.class);
cause.setStackTrace(combined);
}
if (cause instanceof Exception) {
throw (Exception) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
// The cause is a weird kind of Throwable, so throw the outer exception.
throw e;
}
private static Set<Method> findInterruptibleMethods(Class<?> interfaceType) {
Set<Method> set = new HashSet<>();
for (Method m : interfaceType.getMethods()) {
if (declaresInterruptedEx(m)) {
set.add(m);
}
}
return set;
}
private static boolean declaresInterruptedEx(Method method) {
for (Class<?> exType : method.getExceptionTypes()) {
// debate: == or isAssignableFrom?
if (exType == InterruptedException.class) {
return true;
}
}
return false;
}
private static void wrapAndThrowExecutionExceptionOrError(Throwable cause)
throws ExecutionException {
if (cause instanceof Error) {
throw new ExecutionError((Error) cause);
} else if (cause instanceof RuntimeException) {
throw new UncheckedExecutionException(cause);
} else {
throw new ExecutionException(cause);
}
}
private static void wrapAndThrowRuntimeExecutionExceptionOrError(Throwable cause) {
if (cause instanceof Error) {
throw new ExecutionError((Error) cause);
} else {
throw new UncheckedExecutionException(cause);
}
}
private static void checkPositiveTimeout(long timeoutDuration) {
checkArgument(timeoutDuration > 0, "timeout must be positive: %s", timeoutDuration);
}
}
|
type
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/TransactionTimeoutTests.java
|
{
"start": 907,
"end": 1900
}
|
class ____ {
@Test
void testJdbcTxn(SessionFactoryScope sessions) {
sessions.inSession( (session) -> {
final Transaction transaction = session.getTransaction();
// timeout in 2 seconds
transaction.setTimeout( 2 );
// start the transaction and sleep for 3 seconds to exceed the transaction timeout
transaction.begin();
try {
Thread.sleep( 3 * 1000 );
}
catch (InterruptedException e) {
throw new RuntimeException( "Thread#sleep error", e );
}
try {
// perform an operation against the db and try to commit the transaction
session.createSelectionQuery( "from Person", Person.class ).list();
transaction.commit();
fail( "Transaction should have timed out" );
}
catch (PersistenceException e) {
assertThat( e ).isInstanceOf( TransactionException.class );
assertThat( e ).hasMessageContaining( "Transaction timeout expired" );
}
} );
}
@Entity(name="Person")
@Table(name="persons")
public static
|
TransactionTimeoutTests
|
java
|
google__guava
|
android/guava/src/com/google/common/graph/DirectedGraphConnections.java
|
{
"start": 1890,
"end": 1984
}
|
class ____<N, V> implements GraphConnections<N, V> {
/**
* A wrapper
|
DirectedGraphConnections
|
java
|
google__guava
|
android/guava-tests/test/com/google/common/eventbus/DispatcherTest.java
|
{
"start": 1126,
"end": 4973
}
|
class ____ extends TestCase {
private final EventBus bus = new EventBus();
private final IntegerSubscriber i1 = new IntegerSubscriber("i1");
private final IntegerSubscriber i2 = new IntegerSubscriber("i2");
private final IntegerSubscriber i3 = new IntegerSubscriber("i3");
private final ImmutableList<Subscriber> integerSubscribers =
ImmutableList.of(
subscriber(bus, i1, "handleInteger", Integer.class),
subscriber(bus, i2, "handleInteger", Integer.class),
subscriber(bus, i3, "handleInteger", Integer.class));
private final StringSubscriber s1 = new StringSubscriber("s1");
private final StringSubscriber s2 = new StringSubscriber("s2");
private final ImmutableList<Subscriber> stringSubscribers =
ImmutableList.of(
subscriber(bus, s1, "handleString", String.class),
subscriber(bus, s2, "handleString", String.class));
private final ConcurrentLinkedQueue<Object> dispatchedSubscribers = new ConcurrentLinkedQueue<>();
private Dispatcher dispatcher;
public void testPerThreadQueuedDispatcher() {
dispatcher = Dispatcher.perThreadDispatchQueue();
dispatcher.dispatch(1, integerSubscribers.iterator());
assertThat(dispatchedSubscribers)
.containsExactly(
i1,
i2,
i3, // Integer subscribers are dispatched to first.
s1,
s2, // Though each integer subscriber dispatches to all string subscribers,
s1,
s2, // those string subscribers aren't actually dispatched to until all integer
s1,
s2 // subscribers have finished.
)
.inOrder();
}
public void testLegacyAsyncDispatcher() {
dispatcher = Dispatcher.legacyAsync();
CyclicBarrier barrier = new CyclicBarrier(2);
CountDownLatch latch = new CountDownLatch(2);
new Thread(
new Runnable() {
@Override
public void run() {
try {
barrier.await();
} catch (Exception e) {
throw new AssertionError(e);
}
dispatcher.dispatch(2, integerSubscribers.iterator());
latch.countDown();
}
})
.start();
new Thread(
new Runnable() {
@Override
public void run() {
try {
barrier.await();
} catch (Exception e) {
throw new AssertionError(e);
}
dispatcher.dispatch("foo", stringSubscribers.iterator());
latch.countDown();
}
})
.start();
Uninterruptibles.awaitUninterruptibly(latch);
// See Dispatcher.LegacyAsyncDispatcher for an explanation of why there aren't really any
// useful testable guarantees about the behavior of that dispatcher in a multithreaded
// environment. Here we simply test that all the expected dispatches happened in some order.
assertThat(dispatchedSubscribers).containsExactly(i1, i2, i3, s1, s1, s1, s1, s2, s2, s2, s2);
}
public void testImmediateDispatcher() {
dispatcher = Dispatcher.immediate();
dispatcher.dispatch(1, integerSubscribers.iterator());
assertThat(dispatchedSubscribers)
.containsExactly(
i1, s1, s2, // Each integer subscriber immediately dispatches to 2 string subscribers.
i2, s1, s2, i3, s1, s2)
.inOrder();
}
private static Subscriber subscriber(
EventBus bus, Object target, String methodName, Class<?> eventType) {
try {
return Subscriber.create(bus, target, target.getClass().getMethod(methodName, eventType));
} catch (NoSuchMethodException e) {
throw new AssertionError(e);
}
}
public final
|
DispatcherTest
|
java
|
assertj__assertj-core
|
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/presentation/StandardRepresentation_unambiguousToStringOf_Test.java
|
{
"start": 22976,
"end": 23504
}
|
class ____ {
int x;
int y;
Ambiguous(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Ambiguous that = (Ambiguous) o;
return this.x == that.x && this.y == that.y;
}
@Override
public int hashCode() {
return x;
}
@Override
public String toString() {
return "Ambiguous(%d)".formatted(x);
}
}
}
|
Ambiguous
|
java
|
FasterXML__jackson-core
|
src/main/java/tools/jackson/core/util/Instantiatable.java
|
{
"start": 487,
"end": 781
}
|
interface ____<T>
{
/**
* Method called to ensure that we have a non-blueprint object to use;
* it is either this object (if stateless), or a newly created object
* with separate state.
*
* @return Actual instance to use
*/
T createInstance();
}
|
Instantiatable
|
java
|
apache__dubbo
|
dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java
|
{
"start": 990,
"end": 1143
}
|
interface ____ {
void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception;
boolean isSupport();
}
|
Validator
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/AutoValueRules.java
|
{
"start": 2651,
"end": 3128
}
|
class ____ extends AbstractAutoRule {
BuilderRule(String annotation) {
super(annotation);
}
@Override
protected ResultUsePolicy autoMethodPolicy(
MethodSymbol abstractMethod, ClassSymbol autoClass, VisitorState state) {
return abstractMethod.getParameters().size() == 1
&& isSameType(abstractMethod.getReturnType(), autoClass.type, state)
? OPTIONAL
: EXPECTED;
}
}
private abstract static
|
BuilderRule
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/boot/PersistenceConfigurationTests.java
|
{
"start": 1187,
"end": 5360
}
|
class ____ {
@Test
@RequiresDialect( H2Dialect.class )
void testBaseJpa() {
try (EntityManagerFactory emf = new PersistenceConfiguration( "emf" ).createEntityManagerFactory()) {
assert emf.isOpen();
}
try (EntityManagerFactory emf = new HibernatePersistenceConfiguration( "emf" ).createEntityManagerFactory()) {
assert emf.isOpen();
}
}
@Test
@RequiresDialect( H2Dialect.class )
void testCallPersistence() {
final PersistenceConfiguration cfg1 = new PersistenceConfiguration( "emf" );
try (EntityManagerFactory emf = Persistence.createEntityManagerFactory( cfg1 )) {
assert emf.isOpen();
}
final HibernatePersistenceConfiguration cfg2 = new HibernatePersistenceConfiguration( "emf" );
try (EntityManagerFactory emf = Persistence.createEntityManagerFactory( cfg2 )) {
assert emf.isOpen();
}
}
@Test
@RequiresDialect( H2Dialect.class )
void testJdbcData() {
final PersistenceConfiguration cfg = new PersistenceConfiguration( "emf" );
TestingDatabaseInfo.forEachSetting( cfg::property );
try (EntityManagerFactory emf = cfg.createEntityManagerFactory()) {
assert emf.isOpen();
}
final PersistenceConfiguration cfg2 = new PersistenceConfiguration( "emf" );
TestingDatabaseInfo.forEachSetting( cfg2::property );
try (EntityManagerFactory emf = cfg2.createEntityManagerFactory()) {
assert emf.isOpen();
}
final PersistenceConfiguration cfg3 = new HibernatePersistenceConfiguration( "emf" );
TestingDatabaseInfo.forEachSetting( cfg3::property );
try (EntityManagerFactory emf = cfg3.createEntityManagerFactory()) {
assert emf.isOpen();
}
final PersistenceConfiguration cfg4 = new HibernatePersistenceConfiguration( "emf" )
.jdbcDriver( TestingDatabaseInfo.DRIVER )
.jdbcUrl( TestingDatabaseInfo.URL )
.jdbcUsername( TestingDatabaseInfo.USER )
.jdbcPassword( TestingDatabaseInfo.PASS );
try (EntityManagerFactory emf = cfg4.createEntityManagerFactory()) {
assert emf.isOpen();
}
}
@Test
@RequiresDialect( H2Dialect.class )
public void testForUserGuide() {
{
//tag::example-bootstrap-standard-PersistenceConfiguration[]
final PersistenceConfiguration cfg = new PersistenceConfiguration( "emf" )
.property( JDBC_URL, "jdbc:h2:mem:db1" )
.property( JDBC_USER, "sa" )
.property( JDBC_PASSWORD, "" );
try (EntityManagerFactory emf = cfg.createEntityManagerFactory()) {
assert emf.isOpen();
}
//end::example-bootstrap-standard-PersistenceConfiguration[]
}
{
//tag::example-bootstrap-standard-HibernatePersistenceConfiguration[]
final PersistenceConfiguration cfg = new HibernatePersistenceConfiguration( "emf" )
.jdbcUrl( "jdbc:h2:mem:db1" )
.jdbcUsername( "sa" )
.jdbcPassword( "" );
try (EntityManagerFactory emf = cfg.createEntityManagerFactory()) {
assert emf.isOpen();
}
//end::example-bootstrap-standard-HibernatePersistenceConfiguration[]
}
}
@Test
@RequiresDialect( H2Dialect.class )
public void testVarargs() {
final PersistenceConfiguration cfg = new HibernatePersistenceConfiguration( "emf" )
.jdbcUrl( "jdbc:h2:mem:db1" )
.jdbcUsername( "sa" )
.jdbcPassword( "" )
.schemaToolingAction( Action.CREATE_DROP )
.managedClasses( Book.class, Person.class );
try (EntityManagerFactory emf = cfg.createEntityManagerFactory()) {
assert emf.isOpen();
TransactionUtil2.inTransaction( emf.unwrap( SessionFactoryImplementor.class ), (em) -> {
em.createSelectionQuery( "from Book", Book.class ).list();
} );
}
}
@Test
@RequiresDialect( H2Dialect.class )
public void testVarargs2() {
final PersistenceConfiguration cfg = new HibernatePersistenceConfiguration( "emf" )
.jdbcUrl( "jdbc:h2:mem:db1" )
.jdbcUsername( "sa" )
.jdbcPassword( "" )
.schemaToolingAction( Action.CREATE_DROP )
.managedClasses( List.of( Book.class, Person.class ) );
try (EntityManagerFactory emf = cfg.createEntityManagerFactory()) {
assert emf.isOpen();
TransactionUtil2.inTransaction( emf.unwrap( SessionFactoryImplementor.class ), (em) -> {
em.createSelectionQuery( "from Book", Book.class ).list();
} );
}
}
}
|
PersistenceConfigurationTests
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/PoolTestCase.java
|
{
"start": 202,
"end": 1151
}
|
class ____ extends TestCase {
protected void setUp() throws Exception {
DruidDataSourceStatManager.clear();
}
protected void tearDown() throws Exception {
int size = DruidDataSourceStatManager.getInstance().getDataSourceList().size();
String errorInfo = null;
if (size > 0) {
CompositeData compositeData = (CompositeData) DruidDataSourceStatManager
.getInstance()
.getDataSourceList()
.values()
.iterator()
.next();
String name = (String) compositeData.get("Name");
String url = (String) compositeData.get("URL");
String initStackTrace = (String) compositeData.get("InitStackTrace");
errorInfo = "Name " + name + ", URL " + url + ", initStackTrace=" + initStackTrace;
}
Assert.assertEquals(errorInfo, 0, size);
}
}
|
PoolTestCase
|
java
|
grpc__grpc-java
|
cronet/src/main/java/io/grpc/cronet/CronetWritableBuffer.java
|
{
"start": 740,
"end": 1396
}
|
class ____ implements WritableBuffer {
private final ByteBuffer buffer;
public CronetWritableBuffer(ByteBuffer buffer, int capacity) {
this.buffer = Preconditions.checkNotNull(buffer, "buffer");
}
@Override
public void write(byte[] src, int srcIndex, int length) {
buffer.put(src, srcIndex, length);
}
@Override
public void write(byte b) {
buffer.put(b);
}
@Override
public int writableBytes() {
return buffer.remaining();
}
@Override
public int readableBytes() {
return buffer.position();
}
@Override
public void release() {
}
ByteBuffer buffer() {
return buffer;
}
}
|
CronetWritableBuffer
|
java
|
quarkusio__quarkus
|
extensions/jdbc/jdbc-h2/runtime/src/main/java/io/quarkus/jdbc/h2/runtime/graalvm/DisableSourceCompiler.java
|
{
"start": 331,
"end": 1332
}
|
class ____ {
private static final String ERR = "It's not possible to compile H2 triggers when embedding the engine in GraalVM native images";
//Delete it all
@Substitute
public static boolean isJavaxScriptSource(String source) {
throw new UnsupportedOperationException(ERR);
}
@Substitute
public CompiledScript getCompiledScript(String packageAndClassName) throws ScriptException {
throw new UnsupportedOperationException(ERR);
}
@Substitute
public Class<?> getClass(String packageAndClassName)
throws ClassNotFoundException {
throw new UnsupportedOperationException(ERR);
}
@Substitute
public void setSource(String className, String source) {
//no-op
}
@Substitute
public void setJavaSystemCompiler(boolean enabled) {
//no-op
}
@Substitute
public Method getMethod(String className) {
throw new UnsupportedOperationException(ERR);
}
}
|
DisableSourceCompiler
|
java
|
apache__dubbo
|
dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/RegistryFactory.java
|
{
"start": 938,
"end": 1251
}
|
interface ____ extends org.apache.dubbo.registry.RegistryFactory {
com.alibaba.dubbo.registry.Registry getRegistry(com.alibaba.dubbo.common.URL url);
@Override
default Registry getRegistry(URL url) {
return this.getRegistry(new com.alibaba.dubbo.common.DelegateURL(url));
}
}
|
RegistryFactory
|
java
|
junit-team__junit5
|
junit-jupiter-api/src/main/java/org/junit/jupiter/api/condition/DisabledIfSystemProperty.java
|
{
"start": 3616,
"end": 4476
}
|
interface ____ {
/**
* The name of the JVM system property to retrieve.
*
* @return the system property name; never <em>blank</em>
* @see System#getProperty(String)
*/
String named();
/**
* A regular expression that will be used to match against the retrieved
* value of the {@link #named} JVM system property.
*
* @return the regular expression; never <em>blank</em>
* @see String#matches(String)
* @see java.util.regex.Pattern
*/
String matches();
/**
* Custom reason to provide if the test or container is disabled.
*
* <p>If a custom reason is supplied, it will be combined with the default
* reason for this annotation. If a custom reason is not supplied, the default
* reason will be used.
*
* @since 5.7
*/
@API(status = STABLE, since = "5.7")
String disabledReason() default "";
}
|
DisabledIfSystemProperty
|
java
|
apache__maven
|
impl/maven-executor/src/main/java/org/apache/maven/cling/executor/internal/HelperImpl.java
|
{
"start": 1334,
"end": 3885
}
|
class ____ implements ExecutorHelper {
private final Mode defaultMode;
private final Path installationDirectory;
private final Path userHomeDirectory;
private final HashMap<Mode, Executor> executors;
private final ConcurrentHashMap<String, String> cache;
public HelperImpl(
Mode defaultMode,
@Nullable Path installationDirectory,
@Nullable Path userHomeDirectory,
Executor embedded,
Executor forked) {
this.defaultMode = requireNonNull(defaultMode);
this.installationDirectory = installationDirectory != null
? ExecutorRequest.getCanonicalPath(installationDirectory)
: ExecutorRequest.discoverInstallationDirectory();
this.userHomeDirectory = userHomeDirectory != null
? ExecutorRequest.getCanonicalPath(userHomeDirectory)
: ExecutorRequest.discoverUserHomeDirectory();
this.executors = new HashMap<>();
this.executors.put(Mode.EMBEDDED, requireNonNull(embedded, "embedded"));
this.executors.put(Mode.FORKED, requireNonNull(forked, "forked"));
this.cache = new ConcurrentHashMap<>();
}
@Override
public Mode getDefaultMode() {
return defaultMode;
}
@Override
public ExecutorRequest.Builder executorRequest() {
return ExecutorRequest.mavenBuilder(installationDirectory).userHomeDirectory(userHomeDirectory);
}
@Override
public int execute(Mode mode, ExecutorRequest executorRequest) throws ExecutorException {
return getExecutor(mode, executorRequest).execute(executorRequest);
}
@Override
public String mavenVersion() {
return cache.computeIfAbsent("maven.version", k -> {
ExecutorRequest request = executorRequest().build();
return getExecutor(Mode.AUTO, request).mavenVersion(request);
});
}
protected Executor getExecutor(Mode mode, ExecutorRequest request) throws ExecutorException {
return switch (mode) {
case AUTO -> getExecutorByRequest(request);
case EMBEDDED -> executors.get(Mode.EMBEDDED);
case FORKED -> executors.get(Mode.FORKED);
};
}
private Executor getExecutorByRequest(ExecutorRequest request) {
if (request.environmentVariables().isEmpty() && request.jvmArguments().isEmpty()) {
return getExecutor(Mode.EMBEDDED, request);
} else {
return getExecutor(Mode.FORKED, request);
}
}
}
|
HelperImpl
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/webmonitor/history/OnlyExecutionGraphJsonArchivist.java
|
{
"start": 1237,
"end": 2310
}
|
interface ____ extends JsonArchivist {
/**
* Returns a {@link Collection} of {@link ArchivedJson}s containing JSON responses and their
* respective REST URL for a given job.
*
* <p>The collection should contain one entry for every response that could be generated for the
* given job, for example one entry for each task. The REST URLs should be unique and must not
* contain placeholders.
*
* @param graph AccessExecutionGraph for which the responses should be generated
* @return Collection containing an ArchivedJson for every response that could be generated for
* the given job
* @throws IOException thrown if the JSON generation fails
*/
Collection<ArchivedJson> archiveJsonWithPath(AccessExecutionGraph graph) throws IOException;
@Override
default Collection<ArchivedJson> archiveJsonWithPath(ExecutionGraphInfo executionGraphInfo)
throws IOException {
return archiveJsonWithPath(executionGraphInfo.getArchivedExecutionGraph());
}
}
|
OnlyExecutionGraphJsonArchivist
|
java
|
google__guice
|
extensions/assistedinject/test/com/google/inject/assistedinject/FactoryModuleBuilderTest.java
|
{
"start": 1738,
"end": 14493
}
|
enum ____ {
BLUE,
GREEN,
RED,
GRAY,
BLACK
}
public void testImplicitForwardingAssistedBindingFailsWithInterface() {
try {
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(Car.class).to(Golf.class);
install(new FactoryModuleBuilder().build(ColoredCarFactory.class));
}
});
fail();
} catch (CreationException ce) {
assertContains(
ce.getMessage(),
"FactoryModuleBuilderTest$Car is an interface, not a concrete class.",
"Unable to create AssistedInject factory.",
"while locating FactoryModuleBuilderTest$Car",
"at FactoryModuleBuilderTest$ColoredCarFactory.create(");
assertEquals(1, ce.getErrorMessages().size());
}
}
public void testImplicitForwardingAssistedBindingFailsWithAbstractClass() {
try {
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(AbstractCar.class).to(ArtCar.class);
install(new FactoryModuleBuilder().build(ColoredAbstractCarFactory.class));
}
});
fail();
} catch (CreationException ce) {
assertContains(
ce.getMessage(),
"FactoryModuleBuilderTest$AbstractCar is abstract, not a concrete class.",
"Unable to create AssistedInject factory.",
"while locating FactoryModuleBuilderTest$AbstractCar",
"at FactoryModuleBuilderTest$ColoredAbstractCarFactory.create(");
assertEquals(1, ce.getErrorMessages().size());
}
}
public void testImplicitForwardingAssistedBindingCreatesNewObjects() {
final Mustang providedMustang = new Mustang(Color.BLUE);
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
install(new FactoryModuleBuilder().build(MustangFactory.class));
}
@Provides
Mustang provide() {
return providedMustang;
}
});
assertSame(providedMustang, injector.getInstance(Mustang.class));
MustangFactory factory = injector.getInstance(MustangFactory.class);
Mustang created = factory.create(Color.GREEN);
assertNotSame(providedMustang, created);
assertEquals(Color.BLUE, providedMustang.color);
assertEquals(Color.GREEN, created.color);
}
public void testExplicitForwardingAssistedBindingFailsWithInterface() {
try {
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(Volkswagen.class).to(Golf.class);
install(
new FactoryModuleBuilder()
.implement(Car.class, Volkswagen.class)
.build(ColoredCarFactory.class));
}
});
fail();
} catch (CreationException ce) {
assertContains(
ce.getMessage(),
"FactoryModuleBuilderTest$Volkswagen is an interface, not a concrete class.",
"Unable to create AssistedInject factory.",
"while locating FactoryModuleBuilderTest$Volkswagen",
"while locating FactoryModuleBuilderTest$Car",
"at FactoryModuleBuilderTest$ColoredCarFactory.create(");
assertEquals(1, ce.getErrorMessages().size());
}
}
public void testExplicitForwardingAssistedBindingFailsWithAbstractClass() {
try {
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(AbstractCar.class).to(ArtCar.class);
install(
new FactoryModuleBuilder()
.implement(Car.class, AbstractCar.class)
.build(ColoredCarFactory.class));
}
});
fail();
} catch (CreationException ce) {
assertContains(
ce.getMessage(),
"FactoryModuleBuilderTest$AbstractCar is abstract, not a concrete class.",
"Unable to create AssistedInject factory.",
"while locating FactoryModuleBuilderTest$AbstractCar",
"while locating FactoryModuleBuilderTest$Car",
"at FactoryModuleBuilderTest$ColoredCarFactory.create(");
assertEquals(1, ce.getErrorMessages().size());
}
}
public void testExplicitForwardingAssistedBindingCreatesNewObjects() {
final Mustang providedMustang = new Mustang(Color.BLUE);
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
install(
new FactoryModuleBuilder()
.implement(Car.class, Mustang.class)
.build(ColoredCarFactory.class));
}
@Provides
Mustang provide() {
return providedMustang;
}
});
assertSame(providedMustang, injector.getInstance(Mustang.class));
ColoredCarFactory factory = injector.getInstance(ColoredCarFactory.class);
Mustang created = (Mustang) factory.create(Color.GREEN);
assertNotSame(providedMustang, created);
assertEquals(Color.BLUE, providedMustang.color);
assertEquals(Color.GREEN, created.color);
}
public void testAnnotatedAndParentBoundReturnValue() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(Car.class).to(Golf.class);
bind(Integer.class).toInstance(911);
bind(Double.class).toInstance(5.0d);
install(
new FactoryModuleBuilder()
.implement(Car.class, Names.named("german"), Beetle.class)
.implement(Car.class, Names.named("american"), Mustang.class)
.build(AnnotatedVersatileCarFactory.class));
}
});
AnnotatedVersatileCarFactory factory = injector.getInstance(AnnotatedVersatileCarFactory.class);
assertTrue(factory.getGermanCar(Color.BLACK) instanceof Beetle);
assertTrue(injector.getInstance(Car.class) instanceof Golf);
}
public void testParentBoundReturnValue() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(Car.class).to(Golf.class);
bind(Double.class).toInstance(5.0d);
install(
new FactoryModuleBuilder()
.implement(Car.class, Mustang.class)
.build(ColoredCarFactory.class));
}
});
ColoredCarFactory factory = injector.getInstance(ColoredCarFactory.class);
assertTrue(factory.create(Color.RED) instanceof Mustang);
assertTrue(injector.getInstance(Car.class) instanceof Golf);
}
public void testConfigureAnnotatedReturnValue() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
install(
new FactoryModuleBuilder()
.implement(Car.class, Names.named("german"), Beetle.class)
.implement(Car.class, Names.named("american"), Mustang.class)
.build(AnnotatedVersatileCarFactory.class));
}
});
AnnotatedVersatileCarFactory factory = injector.getInstance(AnnotatedVersatileCarFactory.class);
assertTrue(factory.getGermanCar(Color.GRAY) instanceof Beetle);
assertTrue(factory.getAmericanCar(Color.BLACK) instanceof Mustang);
}
public void testNoBindingAssistedInject() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
install(new FactoryModuleBuilder().build(MustangFactory.class));
}
});
MustangFactory factory = injector.getInstance(MustangFactory.class);
Mustang mustang = factory.create(Color.BLUE);
assertEquals(Color.BLUE, mustang.color);
}
public void testBindingAssistedInject() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
install(
new FactoryModuleBuilder()
.implement(Car.class, Mustang.class)
.build(ColoredCarFactory.class));
}
});
ColoredCarFactory factory = injector.getInstance(ColoredCarFactory.class);
Mustang mustang = (Mustang) factory.create(Color.BLUE);
assertEquals(Color.BLUE, mustang.color);
}
public void testDuplicateBindings() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
install(
new FactoryModuleBuilder()
.implement(Car.class, Mustang.class)
.build(ColoredCarFactory.class));
install(
new FactoryModuleBuilder()
.implement(Car.class, Mustang.class)
.build(ColoredCarFactory.class));
}
});
ColoredCarFactory factory = injector.getInstance(ColoredCarFactory.class);
Mustang mustang = (Mustang) factory.create(Color.BLUE);
assertEquals(Color.BLUE, mustang.color);
}
public void testSimilarBindingsWithConflictingImplementations() {
try {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
install(
new FactoryModuleBuilder()
.implement(Car.class, Mustang.class)
.build(ColoredCarFactory.class));
install(
new FactoryModuleBuilder()
.implement(Car.class, Golf.class)
.build(ColoredCarFactory.class));
}
});
injector.getInstance(ColoredCarFactory.class);
fail();
} catch (CreationException ce) {
assertContains(
ce.getMessage(), "FactoryModuleBuilderTest$ColoredCarFactory was bound multiple times");
assertEquals(1, ce.getErrorMessages().size());
}
}
public void testMultipleReturnTypes() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(Double.class).toInstance(5.0d);
install(new FactoryModuleBuilder().build(VersatileCarFactory.class));
}
});
VersatileCarFactory factory = injector.getInstance(VersatileCarFactory.class);
Mustang mustang = factory.getMustang(Color.RED);
assertEquals(Color.RED, mustang.color);
Beetle beetle = factory.getBeetle(Color.GREEN);
assertEquals(Color.GREEN, beetle.color);
}
public void testParameterizedClassesWithNoImplements() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
install(
new FactoryModuleBuilder().build(new TypeLiteral<Foo.Factory<String>>() {}));
}
});
Foo.Factory<String> factory =
injector.getInstance(Key.get(new TypeLiteral<Foo.Factory<String>>() {}));
@SuppressWarnings("unused")
Foo<String> foo = factory.create(new Bar());
}
public void testGenericErrorMessageMakesSense() {
try {
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
install(new FactoryModuleBuilder().build(Key.get(Foo.Factory.class)));
}
});
fail();
} catch (CreationException ce) {
// Assert not only that it's the correct message, but also that it's the *only* message.
Collection<Message> messages = ce.getErrorMessages();
assertEquals(
Foo.Factory.class.getName() + " cannot be used as a key; It is not fully specified.",
Iterables.getOnlyElement(messages).getMessage());
}
}
|
Color
|
java
|
quarkusio__quarkus
|
integration-tests/mongodb-client/src/test/java/io/quarkus/it/mongodb/BookResourceTest.java
|
{
"start": 671,
"end": 1783
}
|
class ____ {
private static Jsonb jsonb;
@BeforeAll
public static void giveMeAMapper() {
jsonb = Utils.initialiseJsonb();
}
@AfterAll
public static void releaseMapper() throws Exception {
jsonb.close();
}
@Test
public void testBlockingClient() {
Utils.callTheEndpoint("/books");
}
@Test
public void testReactiveClients() {
Utils.callTheEndpoint("/reactive-books");
}
@Test
public void health() throws Exception {
// trigger (lazy) creation of the client, otherwise the health check would fail
get("/books");
RestAssured.when().get("/q/health/ready").then()
.body("status", is("UP"),
"checks.data", containsInAnyOrder(hasKey(MongoHealthCheck.CLIENT_DEFAULT)),
"checks.data", containsInAnyOrder(hasKey(MongoHealthCheck.CLIENT_DEFAULT_REACTIVE)),
"checks.status", containsInAnyOrder("UP"),
"checks.name", containsInAnyOrder("MongoDB connection health check"));
}
}
|
BookResourceTest
|
java
|
apache__camel
|
components/camel-web3j/src/test/java/org/apache/camel/component/web3j/Web3jProducerTest.java
|
{
"start": 5052,
"end": 44918
}
|
class ____ extends Web3jMockTestSupport {
@Produce("direct:start")
protected ProducerTemplate template;
@Mock
private Request request;
@Override
public boolean isUseAdviceWith() {
return false;
}
@Test
public void clientVersionTest() throws Exception {
Web3ClientVersion response = Mockito.mock(Web3ClientVersion.class);
Mockito.when(mockWeb3j.web3ClientVersion()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getWeb3ClientVersion()).thenReturn("Geth-123");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.WEB3_CLIENT_VERSION);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertTrue(body.startsWith("Geth"));
}
@Test
public void netVersionTest() throws Exception {
NetVersion response = Mockito.mock(NetVersion.class);
Mockito.when(mockWeb3j.netVersion()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getNetVersion()).thenReturn("Net-123");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.NET_VERSION);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertTrue(body.startsWith("Net"));
}
@Test
public void web3Sha3Test() throws Exception {
Web3Sha3 response = Mockito.mock(Web3Sha3.class);
Mockito.when(mockWeb3j.web3Sha3(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getResult()).thenReturn("0x471");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.WEB3_SHA3);
exchange.getIn().setBody("0x68");
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("0x471", body);
}
@Test
public void netListeningTest() throws Exception {
NetListening response = Mockito.mock(NetListening.class);
Mockito.when(mockWeb3j.netListening()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.isListening()).thenReturn(true);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.NET_LISTENING);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
@Test
public void netPeerCountTest() throws Exception {
BigInteger peerCount = BigInteger.ONE;
NetPeerCount response = Mockito.mock(NetPeerCount.class);
Mockito.when(mockWeb3j.netPeerCount()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getQuantity()).thenReturn(peerCount);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.NET_PEER_COUNT);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(peerCount, body);
}
@Test
public void ethProtocolVersionTest() throws Exception {
EthProtocolVersion response = Mockito.mock(EthProtocolVersion.class);
Mockito.when(mockWeb3j.ethProtocolVersion()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getProtocolVersion()).thenReturn("123");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_PROTOCOL_VERSION);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("123", body);
}
@Test
public void ethCoinbaseTest() throws Exception {
EthCoinbase response = Mockito.mock(EthCoinbase.class);
Mockito.when(mockWeb3j.ethCoinbase()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getAddress()).thenReturn("123");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_COINBASE);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("123", body);
}
@Test
public void ethSyncingTest() throws Exception {
EthSyncing response = Mockito.mock(EthSyncing.class);
Mockito.when(mockWeb3j.ethSyncing()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.isSyncing()).thenReturn(Boolean.TRUE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_SYNCING);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
@Test
public void ethMiningTest() throws Exception {
EthMining response = Mockito.mock(EthMining.class);
Mockito.when(mockWeb3j.ethMining()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.isMining()).thenReturn(Boolean.TRUE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_MINING);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
@Test
public void ethHashrateTest() throws Exception {
EthHashrate response = Mockito.mock(EthHashrate.class);
Mockito.when(mockWeb3j.ethHashrate()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getHashrate()).thenReturn(BigInteger.ONE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_HASHRATE);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethGasPriceTest() throws Exception {
EthGasPrice response = Mockito.mock(EthGasPrice.class);
Mockito.when(mockWeb3j.ethGasPrice()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getGasPrice()).thenReturn(BigInteger.ONE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GAS_PRICE);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethAccountsTest() throws Exception {
EthAccounts response = Mockito.mock(EthAccounts.class);
Mockito.when(mockWeb3j.ethAccounts()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getAccounts()).thenReturn(Collections.emptyList());
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_ACCOUNTS);
template.send(exchange);
List body = exchange.getIn().getBody(List.class);
assertTrue(body.isEmpty());
}
@Test
public void ethBlockNumberTest() throws Exception {
EthBlockNumber response = Mockito.mock(EthBlockNumber.class);
Mockito.when(mockWeb3j.ethBlockNumber()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getBlockNumber()).thenReturn(BigInteger.ONE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_BLOCK_NUMBER);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethGetBalanceTest() throws Exception {
EthGetBalance response = Mockito.mock(EthGetBalance.class);
Mockito.when(mockWeb3j.ethGetBalance(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getBalance()).thenReturn(BigInteger.ONE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_BALANCE);
exchange.getIn().setHeader(Web3jConstants.AT_BLOCK, DefaultBlockParameterName.EARLIEST);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethGetStorageAtTest() throws Exception {
EthGetStorageAt response = Mockito.mock(EthGetStorageAt.class);
Mockito.when(mockWeb3j.ethGetStorageAt(any(), any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getData()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_STORAGE_AT);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void ethGetTransactionCountTest() throws Exception {
EthGetTransactionCount response = Mockito.mock(EthGetTransactionCount.class);
Mockito.when(mockWeb3j.ethGetTransactionCount(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getTransactionCount()).thenReturn(BigInteger.ONE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_TRANSACTION_COUNT);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethGetBlockTransactionCountByHashTest() throws Exception {
EthGetBlockTransactionCountByHash response = Mockito.mock(EthGetBlockTransactionCountByHash.class);
Mockito.when(mockWeb3j.ethGetBlockTransactionCountByHash(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getTransactionCount()).thenReturn(BigInteger.ONE);
Exchange exchange
= createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_BLOCK_TRANSACTION_COUNT_BY_HASH);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethGetBlockTransactionCountByNumberTest() throws Exception {
EthGetBlockTransactionCountByNumber response = Mockito.mock(EthGetBlockTransactionCountByNumber.class);
Mockito.when(mockWeb3j.ethGetBlockTransactionCountByNumber(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getTransactionCount()).thenReturn(BigInteger.ONE);
Exchange exchange
= createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_BLOCK_TRANSACTION_COUNT_BY_NUMBER);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethGetUncleCountByBlockHashTest() throws Exception {
EthGetUncleCountByBlockHash response = Mockito.mock(EthGetUncleCountByBlockHash.class);
Mockito.when(mockWeb3j.ethGetUncleCountByBlockHash(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getUncleCount()).thenReturn(BigInteger.ONE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_UNCLE_COUNT_BY_BLOCK_HASH);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethGetUncleCountByBlockNumberTest() throws Exception {
EthGetUncleCountByBlockNumber response = Mockito.mock(EthGetUncleCountByBlockNumber.class);
Mockito.when(mockWeb3j.ethGetUncleCountByBlockNumber(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getUncleCount()).thenReturn(BigInteger.ONE);
Exchange exchange
= createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_UNCLE_COUNT_BY_BLOCK_NUMBER);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethGetCodeTest() throws Exception {
EthGetCode response = Mockito.mock(EthGetCode.class);
Mockito.when(mockWeb3j.ethGetCode(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getCode()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_CODE);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void ethSignTest() throws Exception {
EthSign response = Mockito.mock(EthSign.class);
Mockito.when(mockWeb3j.ethSign(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getSignature()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_SIGN);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void ethSendTransactionTest() throws Exception {
EthSendTransaction response = Mockito.mock(EthSendTransaction.class);
Mockito.when(mockWeb3j.ethSendTransaction(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getTransactionHash()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_SEND_TRANSACTION);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void ethSendRawTransactionTest() throws Exception {
EthSendTransaction response = Mockito.mock(EthSendTransaction.class);
Mockito.when(mockWeb3j.ethSendRawTransaction(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getTransactionHash()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_SEND_RAW_TRANSACTION);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void ethCallTest() throws Exception {
EthCall response = Mockito.mock(EthCall.class);
Mockito.when(mockWeb3j.ethCall(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getValue()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_CALL);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void ethEstimateGasTest() throws Exception {
EthEstimateGas response = Mockito.mock(EthEstimateGas.class);
Mockito.when(mockWeb3j.ethEstimateGas(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getAmountUsed()).thenReturn(BigInteger.ONE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_ESTIMATE_GAS);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethGetBlockByHashTest() throws Exception {
EthBlock response = Mockito.mock(EthBlock.class);
Mockito.when(mockWeb3j.ethGetBlockByHash(any(), anyBoolean())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getBlock()).thenReturn(Mockito.mock(EthBlock.Block.class));
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_BLOCK_BY_HASH);
template.send(exchange);
EthBlock.Block body = exchange.getIn().getBody(EthBlock.Block.class);
assertNotNull(body);
}
@Test
public void ethGetBlockByNumberTest() throws Exception {
EthBlock response = Mockito.mock(EthBlock.class);
Mockito.when(mockWeb3j.ethGetBlockByNumber(any(), anyBoolean())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getBlock()).thenReturn(Mockito.mock(EthBlock.Block.class));
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_BLOCK_BY_NUMBER);
exchange.getIn().setHeader(Web3jConstants.AT_BLOCK, DefaultBlockParameterName.EARLIEST);
exchange.getIn().setHeader(Web3jConstants.FULL_TRANSACTION_OBJECTS, true);
template.send(exchange);
EthBlock.Block body = exchange.getIn().getBody(EthBlock.Block.class);
assertNotNull(body);
}
@Test
public void ethGetTransactionByHashTest() throws Exception {
EthTransaction response = Mockito.mock(EthTransaction.class);
Mockito.when(mockWeb3j.ethGetTransactionByHash(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Transaction transaction = Mockito.mock(Transaction.class);
Optional<Transaction> optional = Optional.ofNullable(transaction);
Mockito.when(response.getTransaction()).thenReturn(optional);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_TRANSACTION_BY_HASH);
template.send(exchange);
Transaction body = exchange.getIn().getBody(Transaction.class);
assertNotNull(body);
}
@Test
public void ethGetTransactionByBlockHashAndIndexTest() throws Exception {
EthTransaction response = Mockito.mock(EthTransaction.class);
Mockito.when(mockWeb3j.ethGetTransactionByBlockHashAndIndex(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Transaction transaction = Mockito.mock(Transaction.class);
Optional<Transaction> optional = Optional.ofNullable(transaction);
Mockito.when(response.getTransaction()).thenReturn(optional);
Exchange exchange
= createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_TRANSACTION_BY_BLOCK_HASH_AND_INDEX);
template.send(exchange);
Transaction body = exchange.getIn().getBody(Transaction.class);
assertNotNull(body);
}
@Test
public void ethGetTransactionByBlockNumberAndIndexTest() throws Exception {
EthTransaction response = Mockito.mock(EthTransaction.class);
Mockito.when(mockWeb3j.ethGetTransactionByBlockNumberAndIndex(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Transaction transaction = Mockito.mock(Transaction.class);
Optional<Transaction> optional = Optional.ofNullable(transaction);
Mockito.when(response.getTransaction()).thenReturn(optional);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION,
Web3jConstants.ETH_GET_TRANSACTION_BY_BLOCK_NUMBER_AND_INDEX);
template.send(exchange);
Transaction body = exchange.getIn().getBody(Transaction.class);
assertNotNull(body);
}
@Test
public void ethGetTransactionReceiptTest() throws Exception {
EthGetTransactionReceipt response = Mockito.mock(EthGetTransactionReceipt.class);
Mockito.when(mockWeb3j.ethGetTransactionReceipt(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getTransactionReceipt()).thenReturn(Mockito.mock(Optional.class));
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_TRANSACTION_RECEIPT);
template.send(exchange);
Optional<Transaction> body = exchange.getIn().getBody(Optional.class);
assertNotNull(body);
}
@Test
public void ethGetUncleByBlockHashAndIndexTest() throws Exception {
EthBlock response = Mockito.mock(EthBlock.class);
Mockito.when(mockWeb3j.ethGetUncleByBlockHashAndIndex(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getBlock()).thenReturn(Mockito.mock(EthBlock.Block.class));
Exchange exchange
= createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_UNCLE_BY_BLOCK_HASH_AND_INDEX);
template.send(exchange);
EthBlock.Block body = exchange.getIn().getBody(EthBlock.Block.class);
assertNotNull(body);
}
@Test
public void ethGetCompilersTest() throws Exception {
EthGetCompilers response = Mockito.mock(EthGetCompilers.class);
Mockito.when(mockWeb3j.ethGetCompilers()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getCompilers()).thenReturn(Collections.EMPTY_LIST);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_COMPILERS);
template.send(exchange);
List body = exchange.getIn().getBody(List.class);
assertTrue(body.isEmpty());
}
@Test
public void ethCompileLLLTest() throws Exception {
EthCompileLLL response = Mockito.mock(EthCompileLLL.class);
Mockito.when(mockWeb3j.ethCompileLLL(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getCompiledSourceCode()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_COMPILE_LLL);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void ethCompileSolidityTest() throws Exception {
EthCompileSolidity response = Mockito.mock(EthCompileSolidity.class);
Mockito.when(mockWeb3j.ethCompileSolidity(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getCompiledSolidity()).thenReturn(Collections.EMPTY_MAP);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_COMPILE_SOLIDITY);
template.send(exchange);
Map body = exchange.getIn().getBody(Map.class);
assertTrue(body.isEmpty());
}
@Test
public void ethCompileSerpentTest() throws Exception {
EthCompileSerpent response = Mockito.mock(EthCompileSerpent.class);
Mockito.when(mockWeb3j.ethCompileSerpent(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getCompiledSourceCode()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_COMPILE_SERPENT);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void ethNewFilterTest() throws Exception {
EthFilter response = Mockito.mock(EthFilter.class);
Mockito.when(mockWeb3j.ethNewFilter(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getFilterId()).thenReturn(BigInteger.ONE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_NEW_FILTER);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethNewBlockFilterTest() throws Exception {
EthFilter response = Mockito.mock(EthFilter.class);
Mockito.when(mockWeb3j.ethNewBlockFilter()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getFilterId()).thenReturn(BigInteger.ONE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_NEW_BLOCK_FILTER);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethNewPendingTransactionFilterTest() throws Exception {
EthFilter response = Mockito.mock(EthFilter.class);
Mockito.when(mockWeb3j.ethNewPendingTransactionFilter()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getFilterId()).thenReturn(BigInteger.ONE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_NEW_PENDING_TRANSACTION_FILTER);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void ethUninstallFilterTest() throws Exception {
EthUninstallFilter response = Mockito.mock(EthUninstallFilter.class);
Mockito.when(mockWeb3j.ethUninstallFilter(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.isUninstalled()).thenReturn(Boolean.TRUE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_UNINSTALL_FILTER);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
@Test
public void ethGetFilterChangesTest() throws Exception {
EthLog response = Mockito.mock(EthLog.class);
Mockito.when(mockWeb3j.ethGetFilterChanges(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getLogs()).thenReturn(Collections.EMPTY_LIST);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_FILTER_CHANGES);
template.send(exchange);
List body = exchange.getIn().getBody(List.class);
assertTrue(body.isEmpty());
}
@Test
public void ethGetFilterLogsTest() throws Exception {
EthLog response = Mockito.mock(EthLog.class);
Mockito.when(mockWeb3j.ethGetFilterLogs(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getLogs()).thenReturn(Collections.EMPTY_LIST);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_FILTER_LOGS);
template.send(exchange);
List body = exchange.getIn().getBody(List.class);
assertTrue(body.isEmpty());
}
@Test
public void ethGetLogsTest() throws Exception {
EthLog response = Mockito.mock(EthLog.class);
Mockito.when(mockWeb3j.ethGetLogs(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getLogs()).thenReturn(Collections.EMPTY_LIST);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_LOGS);
template.send(exchange);
List body = exchange.getIn().getBody(List.class);
assertTrue(body.isEmpty());
}
@Test
public void ethGetWorkTest() throws Exception {
EthGetWork response = Mockito.mock(EthGetWork.class);
Mockito.when(mockWeb3j.ethGetWork()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getResult()).thenReturn(Collections.EMPTY_LIST);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_WORK);
template.send(exchange);
List body = exchange.getIn().getBody(List.class);
assertEquals(Collections.EMPTY_LIST, body);
}
@Test
public void ethSubmitWorkTest() throws Exception {
EthSubmitWork response = Mockito.mock(EthSubmitWork.class);
Mockito.when(mockWeb3j.ethSubmitWork(any(), any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.solutionValid()).thenReturn(Boolean.TRUE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_SUBMIT_WORK);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
@Test
public void ethSubmitHashrateTest() throws Exception {
EthSubmitHashrate response = Mockito.mock(EthSubmitHashrate.class);
Mockito.when(mockWeb3j.ethSubmitHashrate(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.submissionSuccessful()).thenReturn(Boolean.TRUE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_SUBMIT_HASHRATE);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
@Test
public void dbPutStringTest() throws Exception {
DbPutString response = Mockito.mock(DbPutString.class);
Mockito.when(mockWeb3j.dbPutString(any(), any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.valueStored()).thenReturn(Boolean.TRUE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.DB_PUT_STRING);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
@Test
public void dbGetStringTest() throws Exception {
DbGetString response = Mockito.mock(DbGetString.class);
Mockito.when(mockWeb3j.dbGetString(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getStoredValue()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.DB_GET_STRING);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void dbPutHexTest() throws Exception {
DbPutHex response = Mockito.mock(DbPutHex.class);
Mockito.when(mockWeb3j.dbPutHex(any(), any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.valueStored()).thenReturn(Boolean.TRUE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.DB_PUT_HEX);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
@Test
public void dbGetHexTest() throws Exception {
DbGetHex response = Mockito.mock(DbGetHex.class);
Mockito.when(mockWeb3j.dbGetHex(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getStoredValue()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.DB_GET_HEX);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void shhPostTest() throws Exception {
ShhPost response = Mockito.mock(ShhPost.class);
Mockito.when(mockWeb3j.shhPost(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.messageSent()).thenReturn(Boolean.TRUE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_POST);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
@Test
public void shhVersionTest() throws Exception {
ShhVersion response = Mockito.mock(ShhVersion.class);
Mockito.when(mockWeb3j.shhVersion()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getVersion()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_VERSION);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void shhNewIdentityTest() throws Exception {
ShhNewIdentity response = Mockito.mock(ShhNewIdentity.class);
Mockito.when(mockWeb3j.shhNewIdentity()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getAddress()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_NEW_IDENTITY);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void shhHasIdentityTest() throws Exception {
ShhHasIdentity response = Mockito.mock(ShhHasIdentity.class);
Mockito.when(mockWeb3j.shhHasIdentity(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.hasPrivateKeyForIdentity()).thenReturn(Boolean.TRUE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_HAS_IDENTITY);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
@Test
public void shhNewGroupTest() throws Exception {
ShhNewGroup response = Mockito.mock(ShhNewGroup.class);
Mockito.when(mockWeb3j.shhNewGroup()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getAddress()).thenReturn("test");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_NEW_GROUP);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
}
@Test
public void shhAddToGroupTest() throws Exception {
ShhAddToGroup response = Mockito.mock(ShhAddToGroup.class);
Mockito.when(mockWeb3j.shhAddToGroup(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.addedToGroup()).thenReturn(Boolean.TRUE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_ADD_TO_GROUP);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
@Test
public void shhNewFilterTest() throws Exception {
ShhNewFilter response = Mockito.mock(ShhNewFilter.class);
Mockito.when(mockWeb3j.shhNewFilter(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getFilterId()).thenReturn(BigInteger.ONE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_NEW_FILTER);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
}
@Test
public void shhUninstallFilterTest() throws Exception {
ShhUninstallFilter response = Mockito.mock(ShhUninstallFilter.class);
Mockito.when(mockWeb3j.shhUninstallFilter(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.isUninstalled()).thenReturn(Boolean.TRUE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_UNINSTALL_FILTER);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
@Test
public void shhGetFilterChangesTest() throws Exception {
ShhMessages response = Mockito.mock(ShhMessages.class);
Mockito.when(mockWeb3j.shhGetFilterChanges(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getMessages()).thenReturn(Collections.EMPTY_LIST);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_GET_FILTER_CHANGES);
template.send(exchange);
List body = exchange.getIn().getBody(List.class);
assertTrue(body.isEmpty());
}
@Test
public void shhGetMessagesTest() throws Exception {
ShhMessages response = Mockito.mock(ShhMessages.class);
Mockito.when(mockWeb3j.shhGetMessages(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getMessages()).thenReturn(Collections.EMPTY_LIST);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_GET_MESSAGES);
template.send(exchange);
List body = exchange.getIn().getBody(List.class);
assertTrue(body.isEmpty());
}
@Test
public void setRequestIdTest() throws Exception {
Web3ClientVersion response = Mockito.mock(Web3ClientVersion.class);
Mockito.when(mockWeb3j.web3ClientVersion()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Exchange exchange = createExchangeWithBodyAndHeader(null, Web3jConstants.ID, Long.valueOf(1));
template.send(exchange);
Mockito.verify(request).setId(1L);
}
@Test
public void checkForErrorTest() throws Exception {
Web3ClientVersion response = Mockito.mock(Web3ClientVersion.class);
Mockito.when(mockWeb3j.web3ClientVersion()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.hasError()).thenReturn(true);
Response.Error error = Mockito.mock(Response.Error.class);
Mockito.when(response.getError()).thenReturn(error);
Mockito.when(error.getCode()).thenReturn(1);
Mockito.when(error.getMessage()).thenReturn("error message");
Mockito.when(error.getData()).thenReturn("error data");
Exchange exchange = createExchangeWithBodyAndHeader(null, Web3jConstants.ID, Long.valueOf(2));
template.send(exchange);
assertEquals(Integer.valueOf(1), exchange.getIn().getHeader(Web3jConstants.ERROR_CODE, Integer.class));
assertEquals("error message", exchange.getIn().getHeader(Web3jConstants.ERROR_MESSAGE, String.class));
assertEquals("error data", exchange.getIn().getHeader(Web3jConstants.ERROR_DATA, String.class));
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start")
.to(getUrl() + OPERATION.toLowerCase() + "=" + Web3jConstants.WEB3_CLIENT_VERSION);
}
};
}
}
|
Web3jProducerTest
|
java
|
quarkusio__quarkus
|
extensions/hibernate-validator/runtime/src/main/java/io/quarkus/hibernate/validator/runtime/jaxrs/JaxrsEndPointValidationInterceptor.java
|
{
"start": 808,
"end": 2813
}
|
class ____ extends AbstractMethodValidationInterceptor {
private static final List<MediaType> JSON_MEDIA_TYPE_LIST = Collections.singletonList(MediaType.APPLICATION_JSON_TYPE);
private final ConcurrentHashMap<Method, List<MediaType>> producedMediaTypesCache = new ConcurrentHashMap<>();
@Inject
ResteasyConfigSupport resteasyConfigSupport;
@AroundInvoke
@Override
public Object validateMethodInvocation(InvocationContext ctx) throws Exception {
try {
return super.validateMethodInvocation(ctx);
} catch (ConstraintViolationException e) {
List<MediaType> producedMediaTypes = getProduces(ctx.getMethod());
if (producedMediaTypes.isEmpty() && resteasyConfigSupport.isJsonDefault()) {
producedMediaTypes = JSON_MEDIA_TYPE_LIST;
}
throw new ResteasyViolationExceptionImpl(e.getConstraintViolations(), producedMediaTypes);
}
}
@AroundConstruct
@Override
public void validateConstructorInvocation(InvocationContext ctx) throws Exception {
super.validateConstructorInvocation(ctx);
}
private List<MediaType> getProduces(Method originalMethod) {
List<MediaType> cachedMediaTypes = producedMediaTypesCache.get(originalMethod);
if (cachedMediaTypes != null) {
return cachedMediaTypes;
}
return producedMediaTypesCache.computeIfAbsent(originalMethod, new Function<Method, List<MediaType>>() {
@Override
public List<MediaType> apply(Method method) {
return doGetProduces(originalMethod);
}
});
}
/**
* Ideally, we would be able to get the information from RESTEasy so that we can follow strictly the inheritance rules.
* But, given RESTEasy Reactive is our new default REST layer, I think we can live with this limitation.
* <p>
* Superclass method annotations have precedence, then
|
JaxrsEndPointValidationInterceptor
|
java
|
quarkusio__quarkus
|
independent-projects/qute/core/src/test/java/io/quarkus/qute/TemplateInstanceTest.java
|
{
"start": 418,
"end": 5152
}
|
class ____ {
@Test
public void testInitializer() {
Engine engine = Engine.builder()
.addDefaults()
.addTemplateInstanceInitializer(instance -> instance.data("foo", "bar").setAttribute("alpha", Boolean.TRUE))
.build();
Template hello = engine.parse("Hello {foo}!");
TemplateInstance instance = hello.instance();
assertEquals(Boolean.TRUE, instance.getAttribute("alpha"));
assertEquals("Hello bar!", instance.render());
instance.data("foo", "baz");
assertEquals("Hello baz!", instance.render());
}
@Test
public void testRendered() {
Engine engine = Engine.builder().addDefaults().build();
Template hello = engine.parse("Hello {foo}!");
AtomicBoolean rendered = new AtomicBoolean();
TemplateInstance instance = hello.instance().data("foo", "baz").onRendered(() -> rendered.set(true));
assertEquals("Hello baz!", instance.render());
assertTrue(rendered.get());
}
@Test
public void testGetTemplate() {
Engine engine = Engine.builder().addDefaults().build();
Template hello = engine.parse("Hello {foo}!");
String generatedId = hello.getGeneratedId();
assertEquals(generatedId, hello.instance().getTemplate().getGeneratedId());
}
@Test
public void testComputeData() {
Engine engine = Engine.builder().addDefaults().build();
TemplateInstance instance = engine.parse("Hello {foo} and {bar}!").instance();
AtomicBoolean barUsed = new AtomicBoolean();
AtomicBoolean fooUsed = new AtomicBoolean();
instance
.computedData("bar", key -> {
barUsed.set(true);
return key.length();
})
.data("bar", 30)
.computedData("foo", key -> {
fooUsed.set(true);
return key.toUpperCase();
});
assertFalse(fooUsed.get());
assertEquals("Hello FOO and 30!", instance.render());
assertTrue(fooUsed.get());
assertFalse(barUsed.get());
}
@Test
public void testLocale() throws Exception {
Engine engine = Engine.builder().addDefaults()
.addValueResolver(ValueResolver.builder()
.applyToName("locale")
.resolveSync(ctx -> ctx.getAttribute(TemplateInstance.LOCALE))
.build())
.build();
Template hello = engine.parse("Hello {locale}!");
assertEquals("Hello fr!", hello.instance().setLocale(Locale.FRENCH).render());
}
@Test
public void testVariant() {
Engine engine = Engine.builder().addDefaults()
.addValueResolver(ValueResolver.builder()
.applyToName("variant")
.resolveSync(ctx -> ctx.getAttribute(TemplateInstance.SELECTED_VARIANT))
.build())
.addValueResolver(ValueResolver.builder()
.appliesTo(ctx -> ctx.getBase() instanceof Variant && ctx.getName().equals("contentType"))
.resolveSync(ctx -> ((Variant) ctx.getBase()).getContentType())
.build())
.build();
Template hello = engine.parse("Hello {variant.contentType}!");
String render = hello.instance().setVariant(Variant.forContentType(Variant.TEXT_HTML)).render();
assertEquals("Hello text/html!", render);
}
@Test
public void testCapacity() {
Engine engine = Engine.builder().addDefaults().build();
assertCapacity(engine, "foo", 3, 3, Map.of());
assertCapacity(engine, "{! comment is ignored !}foo", 3, 3, Map.of());
assertCapacity(engine, "{foo} and bar", 10 + 8, 28, Map.of("foo", "bazzz".repeat(4)));
assertCapacity(engine, "{#each foo}bar{/}", 10 * 3, 3, Map.of("foo", List.of(1)));
assertCapacity(engine, "{#include bar /} and bar", 500 + 8, -1, Map.of());
// limit reached
assertCapacity(engine, "{#each}{foo}{/}".repeat(1000), Capacity.LIMIT, -1, Map.of());
assertCapacity(engine, "{foo}", 10, Capacity.LIMIT, Map.of("foo", "b".repeat(70_000)));
}
private void assertCapacity(Engine engine, String val, int expectedComputed, int expectedMax, Map<String, Object> data) {
TemplateImpl template = (TemplateImpl) engine.parse(val);
assertEquals(expectedComputed, template.capacity.computed);
if (expectedMax != -1) {
template.render(data);
assertEquals(expectedMax, template.capacity.max);
}
}
}
|
TemplateInstanceTest
|
java
|
apache__kafka
|
metadata/src/main/java/org/apache/kafka/metadata/properties/MetaProperties.java
|
{
"start": 1139,
"end": 2360
}
|
class ____ {
/**
* The property that sets the version number.
*/
static final String VERSION_PROP = "version";
/**
* The property that specifies the cluster id.
*/
static final String CLUSTER_ID_PROP = "cluster.id";
/**
* The property that specifies the broker id. Only in V0.
*/
static final String BROKER_ID_PROP = "broker.id";
/**
* The property that specifies the node id. Replaces broker.id in V1.
*/
static final String NODE_ID_PROP = "node.id";
/**
* The property that specifies the directory id.
*/
static final String DIRECTORY_ID_PROP = "directory.id";
/**
* The version of the MetaProperties file.
*/
private final MetaPropertiesVersion version;
/**
* The cluster ID, which may be Optional.empty in V0.
*/
private final Optional<String> clusterId;
/**
* The node ID, which may be OptionalInt.empty in V0.
*/
private final OptionalInt nodeId;
/**
* The directory ID, or Optional.empty if none is specified.
*/
private final Optional<Uuid> directoryId;
/**
* Creates a new MetaProperties object.
*/
public static
|
MetaProperties
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/MyParameterConverter.java
|
{
"start": 107,
"end": 397
}
|
class ____ implements ParamConverter<MyParameter> {
@Override
public MyParameter fromString(String value) {
return new MyParameter(value, value);
}
@Override
public String toString(MyParameter value) {
return value.toString();
}
}
|
MyParameterConverter
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/collection/nonInsertable/NonInsertableColumnTest.java
|
{
"start": 1904,
"end": 2078
}
|
class ____ {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long id;
@ElementCollection
public List<Child> children;
}
@Embeddable
public static
|
Parent
|
java
|
alibaba__nacos
|
common/src/test/java/com/alibaba/nacos/common/notify/NotifyCenterTest.java
|
{
"start": 12032,
"end": 12284
}
|
class ____ extends Event {
private static final long serialVersionUID = -7787588724415976798L;
@Override
public boolean isPluginEvent() {
return true;
}
}
private static
|
PluginEvent
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTest.java
|
{
"start": 75114,
"end": 76753
}
|
class ____ {",
" // BUG: Diagnostic contains: (Null)",
" Object o1 = triggerNullnessChecker(null);", // instance field initializer
" // BUG: Diagnostic contains: (Null)",
" static Object o2 = triggerNullnessChecker(null);", // static field initializer
" {", // instance initializer block
" // BUG: Diagnostic contains: (Null)",
" triggerNullnessChecker(null);",
" }",
" static {", // static initializer block
" // BUG: Diagnostic contains: (Null)",
" triggerNullnessChecker(null);",
" // The following is a regression test for b/80179088",
" int i = 0; i = i++;",
" }",
"}")
.doTest();
}
/**
* Tests nullness propagation for references to constants defined in other compilation units. Enum
* constants and compile-time constants are still known to be non-null; other constants are
* assumed nullable. It doesn't matter whether the referenced compilation unit is part of the same
* compilation or not. Note we often do better when constants are defined in the same compilation
* unit. Circular initialization dependencies between compilation units are also not recognized
* while we do recognize them inside a compilation unit.
*/
@Test
public void constantsDefinedInOtherCompilationUnits() {
compilationHelper
.addSourceLines(
"AnotherEnum.java",
"""
package com.google.errorprone.dataflow.nullnesspropagation;
public
|
InitializerBlockTest
|
java
|
mockito__mockito
|
mockito-extensions/mockito-errorprone/src/test/java/org/mockito/errorprone/bugpatterns/MockitoAnyClassWithPrimitiveTypeTest.java
|
{
"start": 5028,
"end": 5787
}
|
class ____ {",
" int run(int arg) {",
" return 42;",
" }",
" int runWithBoth(String arg1, int arg2) {",
" return 42;",
" }",
" }",
"}")
.doTest();
}
@Test
public void testRefactoring() {
refactoringHelper
.addInputLines(
"Test.java",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.when;",
"import static org.mockito.ArgumentMatchers.any;",
"
|
Foo
|
java
|
apache__maven
|
its/core-it-suite/src/test/java/org/apache/maven/it/MavenIT0063SystemScopeDependencyTest.java
|
{
"start": 988,
"end": 2073
}
|
class ____ extends AbstractMavenIntegrationTestCase {
/**
* Test the use of a system scoped dependency to a (fake) tools.jar.
*
* @throws Exception in case of failure
*/
@Test
public void testit0063() throws Exception {
File testDir = extractResources("/it0063");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.getSystemProperties().setProperty("jre.home", new File(testDir, "jdk/jre").getPath());
verifier.addCliArgument(
"org.apache.maven.its.plugins:maven-it-plugin-dependency-resolution:2.1-SNAPSHOT:compile");
verifier.execute();
verifier.verifyErrorFreeLog();
List<String> lines = verifier.loadLines("target/compile.txt");
assertEquals(2, lines.size());
assertEquals(
new File(testDir, "jdk/lib/tools.jar").getCanonicalFile(),
new File((String) lines.get(1)).getCanonicalFile());
}
}
|
MavenIT0063SystemScopeDependencyTest
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/fs/IOMapperBase.java
|
{
"start": 1414,
"end": 4739
}
|
class ____<T> extends Configured
implements Mapper<Text, LongWritable, Text, Text> {
protected byte[] buffer;
protected int bufferSize;
protected FileSystem fs;
protected String hostName;
protected Closeable stream;
public IOMapperBase() {
}
public void configure(JobConf conf) {
setConf(conf);
try {
fs = FileSystem.get(conf);
} catch (Exception e) {
throw new RuntimeException("Cannot create file system.", e);
}
bufferSize = conf.getInt("test.io.file.buffer.size", 4096);
buffer = new byte[bufferSize];
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch(Exception e) {
hostName = "localhost";
}
}
public void close() throws IOException {
}
/**
* Perform io operation, usually read or write.
*
* @param reporter
* @param name file name
* @param value offset within the file
* @return object that is passed as a parameter to
* {@link #collectStats(OutputCollector,String,long,Object)}
* @throws IOException
*/
abstract T doIO(Reporter reporter,
String name,
long value) throws IOException;
/**
* Create an input or output stream based on the specified file.
* Subclasses should override this method to provide an actual stream.
*
* @param name file name
* @return the stream
* @throws IOException
*/
public Closeable getIOStream(String name) throws IOException {
return null;
}
/**
* Collect stat data to be combined by a subsequent reducer.
*
* @param output
* @param name file name
* @param execTime IO execution time
* @param doIOReturnValue value returned by {@link #doIO(Reporter,String,long)}
* @throws IOException
*/
abstract void collectStats(OutputCollector<Text, Text> output,
String name,
long execTime,
T doIOReturnValue) throws IOException;
/**
* Map file name and offset into statistical data.
* <p>
* The map task is to get the
* <code>key</code>, which contains the file name, and the
* <code>value</code>, which is the offset within the file.
*
* The parameters are passed to the abstract method
* {@link #doIO(Reporter,String,long)}, which performs the io operation,
* usually read or write data, and then
* {@link #collectStats(OutputCollector,String,long,Object)}
* is called to prepare stat data for a subsequent reducer.
*/
public void map(Text key,
LongWritable value,
OutputCollector<Text, Text> output,
Reporter reporter) throws IOException {
String name = key.toString();
long longValue = value.get();
reporter.setStatus("starting " + name + " ::host = " + hostName);
this.stream = getIOStream(name);
T statValue = null;
long tStart = System.currentTimeMillis();
try {
statValue = doIO(reporter, name, longValue);
} finally {
if(stream != null) stream.close();
}
long tEnd = System.currentTimeMillis();
long execTime = tEnd - tStart;
collectStats(output, name, execTime, statValue);
reporter.setStatus("finished " + name + " ::host = " + hostName);
}
}
|
IOMapperBase
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/EsqlBaseParser.java
|
{
"start": 299774,
"end": 302119
}
|
class ____ extends ParserRuleContext {
public TerminalNode PROMQL_UNQUOTED_IDENTIFIER() { return getToken(EsqlBaseParser.PROMQL_UNQUOTED_IDENTIFIER, 0); }
public TerminalNode QUOTED_IDENTIFIER() { return getToken(EsqlBaseParser.QUOTED_IDENTIFIER, 0); }
public TerminalNode QUOTED_STRING() { return getToken(EsqlBaseParser.QUOTED_STRING, 0); }
public TerminalNode NAMED_OR_POSITIONAL_PARAM() { return getToken(EsqlBaseParser.NAMED_OR_POSITIONAL_PARAM, 0); }
@SuppressWarnings("this-escape")
public PromqlParamContentContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_promqlParamContent; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).enterPromqlParamContent(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).exitPromqlParamContent(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof EsqlBaseParserVisitor ) return ((EsqlBaseParserVisitor<? extends T>)visitor).visitPromqlParamContent(this);
else return visitor.visitChildren(this);
}
}
public final PromqlParamContentContext promqlParamContent() throws RecognitionException {
PromqlParamContentContext _localctx = new PromqlParamContentContext(_ctx, getState());
enterRule(_localctx, 192, RULE_promqlParamContent);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(974);
_la = _input.LA(1);
if ( !(_la==QUOTED_STRING || ((((_la - 95)) & ~0x3f) == 0 && ((1L << (_la - 95)) & 140737488355457L) != 0)) ) {
_errHandler.recoverInline(this);
}
else {
if ( _input.LA(1)==Token.EOF ) matchedEOF = true;
_errHandler.reportMatch(this);
consume();
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
@SuppressWarnings("CheckReturnValue")
public static
|
PromqlParamContentContext
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/TrackingArgs.java
|
{
"start": 1051,
"end": 6458
}
|
class ____ {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link TrackingArgs} with {@literal CLIENT TRACKING ON}.
*
* @return new {@link TrackingArgs}.
* @see TrackingArgs#enabled(boolean)
*/
public static TrackingArgs enabled() {
return enabled(true);
}
/**
* Creates new {@link TrackingArgs} with {@literal CLIENT TRACKING ON} if {@code enabled} is {@code true}.
*
* @param enabled whether to enable key tracking for the currently connected client.
* @return new {@link TrackingArgs}.
* @see TrackingArgs#enabled(boolean)
*/
public static TrackingArgs enabled(boolean enabled) {
return new TrackingArgs().enabled(enabled);
}
}
/**
* Controls whether to enable key tracking for the currently connected client.
*
* @param enabled whether to enable key tracking for the currently connected client.
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs enabled(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Send redirection messages to the connection with the specified ID. The connection must exist, you can get the ID of such
* connection using {@code CLIENT ID}. If the connection we are redirecting to is terminated, when in RESP3 mode the
* connection with tracking enabled will receive tracking-redir-broken push messages in order to signal the condition.
*
* @param clientId process Id of the client for notification redirection.
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs redirect(long clientId) {
this.redirect = clientId;
return this;
}
/**
* Enable tracking in broadcasting mode. In this mode invalidation messages are reported for all the prefixes specified,
* regardless of the keys requested by the connection. Instead when the broadcasting mode is not enabled, Redis will track
* which keys are fetched using read-only commands, and will report invalidation messages only for such keys.
*
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs bcast() {
this.bcast = true;
return this;
}
/**
* For broadcasting, register a given key prefix, so that notifications will be provided only for keys starting with this
* string. This option can be given multiple times to register multiple prefixes. If broadcasting is enabled without this
* option, Redis will send notifications for every key.
*
* @param prefixes the key prefixes for broadcasting of change notifications. Encoded using
* {@link java.nio.charset.StandardCharsets#UTF_8}.
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs prefixes(String... prefixes) {
return prefixes(StandardCharsets.UTF_8, prefixes);
}
/**
* For broadcasting, register a given key prefix, so that notifications will be provided only for keys starting with this
* string. This option can be given multiple times to register multiple prefixes. If broadcasting is enabled without this
* option, Redis will send notifications for every key.
*
* @param charset the charset to use for {@code prefixes} encoding.
* @param prefixes the key prefixes for broadcasting of change notifications.
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs prefixes(Charset charset, String... prefixes) {
LettuceAssert.notNull(charset, "Charset must not be null");
this.prefixCharset = charset;
this.prefixes = prefixes;
return this;
}
/**
* When broadcasting is NOT active, normally don't track keys in read only commands, unless they are called immediately
* after a CLIENT CACHING yes command.
*
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs optin() {
this.optin = true;
return this;
}
/**
* When broadcasting is NOT active, normally track keys in read only commands, unless they are called immediately after a
* CLIENT CACHING no command.
*
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs optout() {
this.optout = true;
return this;
}
/**
* Don't send notifications about keys modified by this connection itself.
*
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs noloop() {
this.noloop = true;
return this;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {
args.add(enabled ? CommandKeyword.ON : CommandKeyword.OFF);
if (redirect != null) {
args.add("REDIRECT").add(redirect);
}
if (prefixes != null) {
for (String prefix : prefixes) {
args.add("PREFIX").add(prefix.getBytes(prefixCharset));
}
}
if (bcast) {
args.add("BCAST");
}
if (optin) {
args.add("OPTIN");
}
if (optout) {
args.add("OPTOUT");
}
if (noloop) {
args.add("NOLOOP");
}
}
}
|
Builder
|
java
|
apache__camel
|
catalog/camel-report-maven-plugin/src/test/java/org/apache/camel/maven/htmlxlsx/process/XmlToCamelRouteCoverageTest.java
|
{
"start": 1427,
"end": 2808
}
|
class ____ {
@Test
public void testXmlToCamelRouteCoverageConverter() {
// keep jacoco happy
XmlToCamelRouteCoverageConverter result = new XmlToCamelRouteCoverageConverter();
assertNotNull(result);
}
@Test
public void testConvert() throws IOException {
XmlToCamelRouteCoverageConverter converter = new XmlToCamelRouteCoverageConverter();
TestResult result = converter.convert(loadXml());
assertAll(
() -> assertNotNull(result),
() -> assertNotNull(
result.getCamelContextRouteCoverage().getRoutes().getRouteList().get(0).getComponentsMap()));
}
@Test
public void testConvertException() throws JsonProcessingException {
XmlToCamelRouteCoverageConverter spy = spy(new XmlToCamelRouteCoverageConverter());
Mockito
.doAnswer(invocation -> {
throw new TestJsonProcessingException();
})
.when(spy).readValue(anyString());
assertThrows(RuntimeException.class, () -> {
spy.convert(loadXml());
});
}
private String loadXml() throws IOException {
Path path = Paths.get("src/test/resources/XmlToCamelRouteCoverageConverter.xml");
return new String(Files.readAllBytes(path));
}
}
|
XmlToCamelRouteCoverageTest
|
java
|
apache__dubbo
|
dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoadbalanceRules.java
|
{
"start": 951,
"end": 1814
}
|
class ____ one provider from multiple providers randomly.
**/
String RANDOM = "random";
/**
* Round-robin load balance.
**/
String ROUND_ROBIN = "roundrobin";
/**
* Filter the number of invokers with the least number of active calls and count the weights and quantities of these invokers.
**/
String LEAST_ACTIVE = "leastactive";
/**
* Consistent Hash, requests with the same parameters are always sent to the same provider.
**/
String CONSISTENT_HASH = "consistenthash";
/**
* Filter the number of invokers with the shortest response time of success calls and count the weights and quantities of these invokers.
**/
String SHORTEST_RESPONSE = "shortestresponse";
/**
* adaptive load balance.
**/
String ADAPTIVE = "adaptive";
String EMPTY = "";
}
|
select
|
java
|
assertj__assertj-core
|
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/assertion/RecursiveAssertionAssert_withIntrospectionStrategy_Test.java
|
{
"start": 5288,
"end": 5487
}
|
class ____ {
String title;
Date publicationDate = null;
Author[] authors;
Book(String title, Author[] authors) {
this.title = title;
this.authors = authors;
}
}
}
|
Book
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/jaxb/mapping/spi/db/JaxbColumnJoined.java
|
{
"start": 341,
"end": 469
}
|
interface ____ extends JaxbColumnCommon {
String getReferencedColumnName();
JaxbForeignKeyImpl getForeignKey();
}
|
JaxbColumnJoined
|
java
|
google__guava
|
android/guava/src/com/google/common/hash/Murmur3_128HashFunction.java
|
{
"start": 2522,
"end": 5906
}
|
class ____ extends AbstractStreamingHasher {
private static final int CHUNK_SIZE = 16;
private static final long C1 = 0x87c37b91114253d5L;
private static final long C2 = 0x4cf5ad432745937fL;
private long h1;
private long h2;
private int length;
Murmur3_128Hasher(int seed) {
super(CHUNK_SIZE);
this.h1 = seed;
this.h2 = seed;
this.length = 0;
}
@Override
protected void process(ByteBuffer bb) {
long k1 = bb.getLong();
long k2 = bb.getLong();
bmix64(k1, k2);
length += CHUNK_SIZE;
}
private void bmix64(long k1, long k2) {
h1 ^= mixK1(k1);
h1 = Long.rotateLeft(h1, 27);
h1 += h2;
h1 = h1 * 5 + 0x52dce729;
h2 ^= mixK2(k2);
h2 = Long.rotateLeft(h2, 31);
h2 += h1;
h2 = h2 * 5 + 0x38495ab5;
}
@Override
protected void processRemaining(ByteBuffer bb) {
long k1 = 0;
long k2 = 0;
length += bb.remaining();
switch (bb.remaining()) {
case 15:
k2 ^= (long) toUnsignedInt(bb.get(14)) << 48; // fall through
case 14:
k2 ^= (long) toUnsignedInt(bb.get(13)) << 40; // fall through
case 13:
k2 ^= (long) toUnsignedInt(bb.get(12)) << 32; // fall through
case 12:
k2 ^= (long) toUnsignedInt(bb.get(11)) << 24; // fall through
case 11:
k2 ^= (long) toUnsignedInt(bb.get(10)) << 16; // fall through
case 10:
k2 ^= (long) toUnsignedInt(bb.get(9)) << 8; // fall through
case 9:
k2 ^= (long) toUnsignedInt(bb.get(8)); // fall through
case 8:
k1 ^= bb.getLong();
break;
case 7:
k1 ^= (long) toUnsignedInt(bb.get(6)) << 48; // fall through
case 6:
k1 ^= (long) toUnsignedInt(bb.get(5)) << 40; // fall through
case 5:
k1 ^= (long) toUnsignedInt(bb.get(4)) << 32; // fall through
case 4:
k1 ^= (long) toUnsignedInt(bb.get(3)) << 24; // fall through
case 3:
k1 ^= (long) toUnsignedInt(bb.get(2)) << 16; // fall through
case 2:
k1 ^= (long) toUnsignedInt(bb.get(1)) << 8; // fall through
case 1:
k1 ^= (long) toUnsignedInt(bb.get(0));
break;
default:
throw new AssertionError("Should never get here.");
}
h1 ^= mixK1(k1);
h2 ^= mixK2(k2);
}
@Override
protected HashCode makeHash() {
h1 ^= length;
h2 ^= length;
h1 += h2;
h2 += h1;
h1 = fmix64(h1);
h2 = fmix64(h2);
h1 += h2;
h2 += h1;
return HashCode.fromBytesNoCopy(
ByteBuffer.wrap(new byte[CHUNK_SIZE])
.order(ByteOrder.LITTLE_ENDIAN)
.putLong(h1)
.putLong(h2)
.array());
}
private static long fmix64(long k) {
k ^= k >>> 33;
k *= 0xff51afd7ed558ccdL;
k ^= k >>> 33;
k *= 0xc4ceb9fe1a85ec53L;
k ^= k >>> 33;
return k;
}
private static long mixK1(long k1) {
k1 *= C1;
k1 = Long.rotateLeft(k1, 31);
k1 *= C2;
return k1;
}
private static long mixK2(long k2) {
k2 *= C2;
k2 = Long.rotateLeft(k2, 33);
k2 *= C1;
return k2;
}
}
private static final long serialVersionUID = 0L;
}
|
Murmur3_128Hasher
|
java
|
spring-projects__spring-framework
|
spring-websocket/src/test/java/org/springframework/web/socket/config/WebSocketMessageBrokerStatsTests.java
|
{
"start": 1267,
"end": 3279
}
|
class ____ {
private final WebSocketMessageBrokerStats stats = new WebSocketMessageBrokerStats();
@Test
void nullValues() {
String expected = "WebSocketSession[null], stompSubProtocol[null], stompBrokerRelay[null], " +
"inboundChannel[null], outboundChannel[null], sockJsScheduler[null]";
assertThat(stats).hasToString(expected);
}
@Test
void inboundAndOutboundChannelsWithThreadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.afterPropertiesSet();
stats.setInboundChannelExecutor(executor);
stats.setOutboundChannelExecutor(executor);
assertThat(stats.getClientInboundExecutorStatsInfo()).as("inbound channel stats")
.isEqualTo("pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0");
assertThat(stats.getClientOutboundExecutorStatsInfo()).as("outbound channel stats")
.isEqualTo("pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0");
}
@Test
void inboundAndOutboundChannelsWithMockedTaskExecutor() {
TaskExecutor executor = mock();
stats.setInboundChannelExecutor(executor);
stats.setOutboundChannelExecutor(executor);
assertThat(stats.getClientInboundExecutorStatsInfo()).as("inbound channel stats").isEqualTo("thread-per-task");
assertThat(stats.getClientOutboundExecutorStatsInfo()).as("outbound channel stats").isEqualTo("thread-per-task");
}
@Test
void sockJsTaskSchedulerWithThreadPoolTaskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.afterPropertiesSet();
stats.setSockJsTaskScheduler(scheduler);
assertThat(stats.getSockJsTaskSchedulerStatsInfo())
.isEqualTo("pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0");
}
@Test
void sockJsTaskSchedulerWithMockedTaskScheduler() {
TaskScheduler scheduler = mock();
stats.setSockJsTaskScheduler(scheduler);
assertThat(stats.getSockJsTaskSchedulerStatsInfo()).isEqualTo("thread-per-task");
}
}
|
WebSocketMessageBrokerStatsTests
|
java
|
apache__kafka
|
coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorRecordSerde.java
|
{
"start": 4716,
"end": 5015
}
|
class ____ provide implementation which returns appropriate
* type of {@link ApiMessage} objects representing the value.
*
* @param recordType - short representing type
* @return ApiMessage object
*/
protected abstract ApiMessage apiMessageValueFor(short recordType);
}
|
must
|
java
|
spring-projects__spring-security
|
core/src/main/java/org/springframework/security/authentication/AccountExpiredException.java
|
{
"start": 898,
"end": 1493
}
|
class ____ extends AccountStatusException {
@Serial
private static final long serialVersionUID = 3732869526329993353L;
/**
* Constructs a <code>AccountExpiredException</code> with the specified message.
* @param msg the detail message
*/
public AccountExpiredException(String msg) {
super(msg);
}
/**
* Constructs a <code>AccountExpiredException</code> with the specified message and
* root cause.
* @param msg the detail message
* @param cause root cause
*/
public AccountExpiredException(String msg, Throwable cause) {
super(msg, cause);
}
}
|
AccountExpiredException
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/api/common/typeutils/CompositeTypeSerializerSnapshot.java
|
{
"start": 2987,
"end": 5133
}
|
class ____ its own versioning for the format in which it writes the outer snapshot
* and the nested serializer snapshots. The version of the serialization format of this based class
* is defined by {@link #getCurrentVersion()}. This is independent of the version in which
* subclasses writes their outer snapshot, defined by {@link #getCurrentOuterSnapshotVersion()}.
* This means that the outer snapshot's version can be maintained only taking into account changes
* in how the outer snapshot is written. Any changes in the base format does not require upticks in
* the outer snapshot's version.
*
* <h2>Serialization Format</h2>
*
* <p>The current version of the serialization format of a {@link CompositeTypeSerializerSnapshot}
* is as follows:
*
* <pre>{@code
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | CompositeTypeSerializerSnapshot | CompositeTypeSerializerSnapshot | Outer snapshot |
* | version | MAGIC_NUMBER | version |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Outer snapshot |
* | #writeOuterSnapshot(DataOutputView out) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Delegate MAGIC_NUMBER | Delegate version | Num. nested serializers |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Nested serializer snapshots |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* }</pre>
*
* @param <T> The data type that the originating serializer of this snapshot serializes.
* @param <S> The type of the originating serializer.
*/
@PublicEvolving
public abstract
|
has
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/api/common/operators/MailboxExecutor.java
|
{
"start": 3745,
"end": 3960
}
|
interface ____ {
/** A constant for empty args to save on object allocation. */
Object[] EMPTY_ARGS = new Object[0];
/** Extra options to configure enqueued mails. */
@PublicEvolving
|
MailboxExecutor
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/qa/server/single-node/src/javaRestTest/java/org/elasticsearch/xpack/esql/qa/single_node/RestSampleIT.java
|
{
"start": 659,
"end": 905
}
|
class ____ extends RestSampleTestCase {
@ClassRule
public static ElasticsearchCluster cluster = Clusters.testCluster();
@Override
protected String getTestRestCluster() {
return cluster.getHttpAddresses();
}
}
|
RestSampleIT
|
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/capacity/queuemanagement/DeactivatedLeafQueuesByLabel.java
|
{
"start": 1220,
"end": 4270
}
|
class ____ {
private String parentQueuePath;
private String nodeLabel;
private Map<String, QueueCapacities> deactivatedLeafQueues;
private float sumOfChildQueueActivatedCapacity;
private float parentAbsoluteCapacity;
private float leafQueueTemplateAbsoluteCapacity;
private float availableCapacity;
private float totalDeactivatedCapacity;
@VisibleForTesting
public DeactivatedLeafQueuesByLabel() {}
public DeactivatedLeafQueuesByLabel(
Map<String, QueueCapacities> deactivatedLeafQueues,
String parentQueuePath,
String nodeLabel,
float sumOfChildQueueActivatedCapacity,
float parentAbsoluteCapacity,
float leafQueueTemplateAbsoluteCapacity) {
this.parentQueuePath = parentQueuePath;
this.nodeLabel = nodeLabel;
this.deactivatedLeafQueues = deactivatedLeafQueues;
this.sumOfChildQueueActivatedCapacity = sumOfChildQueueActivatedCapacity;
this.parentAbsoluteCapacity = parentAbsoluteCapacity;
this.leafQueueTemplateAbsoluteCapacity = leafQueueTemplateAbsoluteCapacity;
this.totalDeactivatedCapacity = getTotalDeactivatedCapacity();
this.availableCapacity = parentAbsoluteCapacity - sumOfChildQueueActivatedCapacity +
this.totalDeactivatedCapacity + EPSILON;
}
float getTotalDeactivatedCapacity() {
float deactivatedCapacity = 0;
for (Map.Entry<String, QueueCapacities> deactivatedQueueCapacity :
deactivatedLeafQueues.entrySet()) {
deactivatedCapacity += deactivatedQueueCapacity.getValue().getAbsoluteCapacity(nodeLabel);
}
return deactivatedCapacity;
}
public Set<String> getQueues() {
return deactivatedLeafQueues.keySet();
}
public void printToDebug(Logger logger) {
if (logger.isDebugEnabled()) {
logger.debug("Parent queue = {}, nodeLabel = {}, absCapacity = {}, " +
"leafQueueAbsoluteCapacity = {}, deactivatedCapacity = {}, " +
"absChildActivatedCapacity = {}, availableCapacity = {}",
parentQueuePath, nodeLabel, parentAbsoluteCapacity,
leafQueueTemplateAbsoluteCapacity, getTotalDeactivatedCapacity(),
sumOfChildQueueActivatedCapacity, availableCapacity);
}
}
@VisibleForTesting
public int getMaxLeavesToBeActivated(int numPendingApps) {
float childQueueAbsoluteCapacity = leafQueueTemplateAbsoluteCapacity;
if (childQueueAbsoluteCapacity > 0) {
int numLeafQueuesNeeded = (int) Math.floor(availableCapacity / childQueueAbsoluteCapacity);
return Math.min(numLeafQueuesNeeded, numPendingApps);
}
return 0;
}
public boolean canActivateLeafQueues() {
return availableCapacity >= leafQueueTemplateAbsoluteCapacity;
}
@VisibleForTesting
public void setAvailableCapacity(float availableCapacity) {
this.availableCapacity = availableCapacity;
}
@VisibleForTesting
public void setLeafQueueTemplateAbsoluteCapacity(float leafQueueTemplateAbsoluteCapacity) {
this.leafQueueTemplateAbsoluteCapacity = leafQueueTemplateAbsoluteCapacity;
}
}
|
DeactivatedLeafQueuesByLabel
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_3.java
|
{
"start": 316,
"end": 3018
}
|
class ____ extends TestCase {
public void test_0() throws Exception {
DefaultJSONParser parser = new DefaultJSONParser("{v1:3}");
parser.config(Feature.AllowUnQuotedFieldNames, true);
A a = parser.parseObject(A.class);
Assert.assertEquals(3, a.getV1());
}
public void test_1() throws Exception {
DefaultJSONParser parser = new DefaultJSONParser("{v1:'3'}");
parser.config(Feature.AllowUnQuotedFieldNames, true);
parser.config(Feature.AllowSingleQuotes, true);
A a = parser.parseObject(A.class);
Assert.assertEquals(3, a.getV1());
}
public void test_2() throws Exception {
DefaultJSONParser parser = new DefaultJSONParser("{v1:\"3\"}");
parser.config(Feature.AllowUnQuotedFieldNames, true);
parser.config(Feature.AllowSingleQuotes, true);
A a = parser.parseObject(A.class);
Assert.assertEquals(3, a.getV1());
}
public void test_3() throws Exception {
DefaultJSONParser parser = new DefaultJSONParser("{o1:{}}");
parser.config(Feature.AllowUnQuotedFieldNames, true);
parser.config(Feature.AllowSingleQuotes, true);
A a = parser.parseObject(A.class);
Assert.assertEquals(true, a.getO1() != null);
}
public void test_4() throws Exception {
DefaultJSONParser parser = new DefaultJSONParser("{v5:'3'}");
parser.config(Feature.AllowUnQuotedFieldNames, true);
parser.config(Feature.AllowSingleQuotes, true);
A a = parser.parseObject(A.class);
Assert.assertEquals(3L, a.getV5().longValue());
}
public void test_5() throws Exception {
DefaultJSONParser parser = new DefaultJSONParser("{v5:\"3\"}");
parser.config(Feature.AllowUnQuotedFieldNames, true);
parser.config(Feature.AllowSingleQuotes, true);
A a = parser.parseObject(A.class);
Assert.assertEquals(3L, a.getV5().longValue());
}
public void test_6() throws Exception {
int features = JSON.DEFAULT_PARSER_FEATURE;
features = Feature.config(features, Feature.AllowSingleQuotes, true);
Assert.assertEquals(true, Feature.isEnabled(features, Feature.AllowSingleQuotes));
DefaultJSONParser parser = new DefaultJSONParser("'abc'", ParserConfig.getGlobalInstance(), features);
Assert.assertEquals("abc", parser.parse());
}
public void test_7() throws Exception {
DefaultJSONParser parser = new DefaultJSONParser("123");
ParserConfig mapping = new ParserConfig();
parser.setConfig(mapping);
Assert.assertEquals(mapping, parser.getConfig());
}
public static
|
DefaultExtJSONParserTest_3
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/streaming/api/functions/sink/legacy/SinkFunction.java
|
{
"start": 1389,
"end": 3897
}
|
interface ____<IN> extends Function, Serializable {
/**
* @deprecated Use {@link #invoke(Object, Context)}.
*/
default void invoke(IN value) throws Exception {}
/**
* Writes the given value to the sink. This function is called for every record.
*
* <p>You have to override this method when implementing a {@code SinkFunction}, this is a
* {@code default} method for backward compatibility with the old-style method only.
*
* @param value The input record.
* @param context Additional context about the input record.
* @throws Exception This method may throw exceptions. Throwing an exception will cause the
* operation to fail and may trigger recovery.
*/
default void invoke(IN value, Context context) throws Exception {
invoke(value);
}
/**
* Writes the given watermark to the sink. This function is called for every watermark.
*
* <p>This method is intended for advanced sinks that propagate watermarks.
*
* @param watermark The watermark.
* @throws Exception This method may throw exceptions. Throwing an exception will cause the
* operation to fail and may trigger recovery.
*/
default void writeWatermark(Watermark watermark) throws Exception {}
/**
* This method is called at the end of data processing.
*
* <p>The method is expected to flush all remaining buffered data. Exceptions will cause the
* pipeline to be recognized as failed, because the last data items are not processed properly.
* You may use this method to flush remaining buffered elements in the state into transactions
* which you can commit in the last checkpoint.
*
* <p><b>NOTE:</b>This method does not need to close any resources. You should release external
* resources in the {@link RichSinkFunction#close()} method.
*
* @throws Exception This method may throw exceptions. Throwing an exception will cause the
* operation to fail and may trigger recovery.
*/
default void finish() throws Exception {}
/**
* Context that {@link SinkFunction SinkFunctions } can use for getting additional data about an
* input record.
*
* <p>The context is only valid for the duration of a {@link SinkFunction#invoke(Object,
* Context)} call. Do not store the context and use afterwards!
*/
@Public // Interface might be extended in the future with additional methods.
|
SinkFunction
|
java
|
spring-projects__spring-boot
|
smoke-test/spring-boot-smoke-test-structured-logging/src/main/java/smoketest/structuredlogging/SampleStructuredLoggingApplication.java
|
{
"start": 815,
"end": 980
}
|
class ____ {
public static void main(String[] args) {
SpringApplication.run(SampleStructuredLoggingApplication.class, args);
}
}
|
SampleStructuredLoggingApplication
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/api/CompiledPlanITCase.java
|
{
"start": 2057,
"end": 18642
}
|
class ____ extends JsonPlanTestBase {
private static final List<String> DATA =
Arrays.asList("1,1,hi", "2,1,hello", "3,2,hello world");
private static final String[] COLUMNS_DEFINITION =
new String[] {"a bigint", "b int", "c varchar"};
@BeforeEach
@Override
protected void setup() throws Exception {
super.setup();
String srcTableDdl =
"CREATE TABLE MyTable (\n"
+ String.join(",", COLUMNS_DEFINITION)
+ ") with (\n"
+ " 'connector' = 'values',\n"
+ " 'bounded' = 'false')";
tableEnv.executeSql(srcTableDdl);
String sinkTableDdl =
"CREATE TABLE MySink (\n"
+ String.join(",", COLUMNS_DEFINITION)
+ ") with (\n"
+ " 'connector' = 'values',\n"
+ " 'table-sink-class' = 'DEFAULT')";
tableEnv.executeSql(sinkTableDdl);
}
@Test
void testCompilePlanSql() throws IOException {
CompiledPlan compiledPlan =
tableEnv.compilePlanSql("INSERT INTO MySink SELECT * FROM MyTable");
String expected = TableTestUtil.readFromResource("/jsonplan/testGetJsonPlan.out");
assertThat(getPreparedToCompareCompiledPlan(compiledPlan.asJsonString()))
.isEqualTo(getPreparedToCompareCompiledPlan(expected));
}
@Test
void testSourceTableWithHints() {
CompiledPlan compiledPlan =
tableEnv.compilePlanSql(
"INSERT INTO MySink SELECT * FROM MyTable"
// OPTIONS hints here do not play any significant role
// we just have to be sure that these options are present in
// compiled plan
+ " /*+ OPTIONS('bounded'='true', 'scan.parallelism'='2') */");
String expected = TableTestUtil.readFromResource("/jsonplan/testSourceTableWithHints.out");
assertThat(getPreparedToCompareCompiledPlan(compiledPlan.asJsonString()))
.isEqualTo(expected);
}
@Test
void testSinkTableWithHints() {
CompiledPlan compiledPlan =
tableEnv.compilePlanSql(
"INSERT INTO MySink "
+ "/*+ OPTIONS('sink.parallelism'='2', 'sink-insert-only'='false') */ "
+ "SELECT * FROM MyTable");
String expected = TableTestUtil.readFromResource("/jsonplan/testSinkTableWithHints.out");
assertThat(getPreparedToCompareCompiledPlan(compiledPlan.asJsonString()))
.isEqualTo(expected);
}
@Test
void testExecutePlanSql() throws Exception {
File sinkPath = createSourceSinkTables();
tableEnv.compilePlanSql("INSERT INTO sink SELECT * FROM src").execute().await();
assertResult(DATA, sinkPath);
}
@Test
void testExecuteCtasPlanSql() throws Exception {
createTestCsvSourceTable("src", DATA, COLUMNS_DEFINITION);
File sinkPath = TempDirUtils.newFolder(tempFolder);
assertThatThrownBy(
() ->
tableEnv.compilePlanSql(
String.format(
"CREATE TABLE sink\n"
+ "WITH (\n"
+ " 'connector' = 'filesystem',\n"
+ " 'format' = 'testcsv',\n"
+ " 'path' = '%s'\n"
+ ") AS SELECT * FROM src",
sinkPath.getAbsolutePath()))
.execute())
.satisfies(
anyCauseMatches(
TableException.class,
"Unsupported SQL query! compilePlanSql() only accepts a single SQL statement"
+ " of type INSERT"));
}
@Test
void testExecutePlanTable() throws Exception {
File sinkPath = createSourceSinkTables();
tableEnv.from("src").select($("*")).insertInto("sink").compilePlan().execute().await();
assertResult(DATA, sinkPath);
}
@Test
void testCompileWriteToFileAndThenExecuteSql() throws Exception {
Path planPath =
Paths.get(TempDirUtils.newFolder(tempFolder, "plan").getPath(), "plan.json");
File sinkPath = createSourceSinkTables();
CompiledPlan plan = tableEnv.compilePlanSql("INSERT INTO sink SELECT * FROM src");
plan.writeToFile(planPath);
tableEnv.executeSql(String.format("EXECUTE PLAN '%s'", planPath.toAbsolutePath())).await();
assertResult(DATA, sinkPath);
}
@Test
void testCompileWriteToFilePathWithSchemeAndThenExecuteSql() throws Exception {
Path planPath =
Paths.get(TempDirUtils.newFolder(tempFolder, "plan").getPath(), "plan.json");
File sinkPath = createSourceSinkTables();
tableEnv.executeSql(
String.format(
"COMPILE PLAN 'file://%s' FOR INSERT INTO sink SELECT * FROM src",
planPath.toAbsolutePath()));
tableEnv.executeSql(String.format("EXECUTE PLAN 'file://%s'", planPath.toAbsolutePath()))
.await();
assertResult(DATA, sinkPath);
}
@Test
void testCompilePlan() throws Exception {
Path planPath =
Paths.get(TempDirUtils.newFolder(tempFolder, "plan").getPath(), "plan.json")
.toAbsolutePath();
File sinkPath = createSourceSinkTables();
TableResult tableResult =
tableEnv.executeSql(
String.format(
"COMPILE PLAN '%s' FOR INSERT INTO sink SELECT * FROM src",
planPath));
assertThat(tableResult).isEqualTo(TableResultInternal.TABLE_RESULT_OK);
assertThat(planPath.toFile()).exists();
assertThatThrownBy(
() ->
tableEnv.executeSql(
String.format(
"COMPILE PLAN '%s' FOR INSERT INTO sink SELECT * FROM src",
planPath)))
.satisfies(anyCauseMatches(TableException.class, "Cannot overwrite the plan file"));
tableEnv.executeSql(String.format("EXECUTE PLAN '%s'", planPath)).await();
assertResult(DATA, sinkPath);
}
@Test
void testCompilePlanWithStatementSet() throws Exception {
Path planPath =
Paths.get(TempDirUtils.newFolder(tempFolder, "plan").getPath(), "plan.json")
.toAbsolutePath();
createTestCsvSourceTable("src", DATA, COLUMNS_DEFINITION);
File sinkAPath = createTestCsvSinkTable("sinkA", COLUMNS_DEFINITION);
File sinkBPath = createTestCsvSinkTable("sinkB", COLUMNS_DEFINITION);
TableResult tableResult =
tableEnv.executeSql(
String.format(
"COMPILE PLAN '%s' FOR STATEMENT SET BEGIN "
+ "INSERT INTO sinkA SELECT * FROM src;"
+ "INSERT INTO sinkB SELECT a + 1, b + 1, CONCAT(c, '-something') FROM src;"
+ "END",
planPath));
assertThat(tableResult).isEqualTo(TableResultInternal.TABLE_RESULT_OK);
assertThat(planPath.toFile()).exists();
tableEnv.executeSql(String.format("EXECUTE PLAN '%s'", planPath)).await();
assertResult(DATA, sinkAPath);
assertResult(
Arrays.asList(
"2,2,hi-something", "3,2,hello-something", "4,3,hello world-something"),
sinkBPath);
}
@Test
void testCompilePlanIfNotExists() throws Exception {
Path planPath =
Paths.get(TempDirUtils.newFolder(tempFolder, "plan").getPath(), "plan.json")
.toAbsolutePath();
File sinkPath = createSourceSinkTables();
TableResult tableResult =
tableEnv.executeSql(
String.format(
"COMPILE PLAN '%s' IF NOT EXISTS FOR INSERT INTO sink SELECT * FROM src",
planPath));
assertThat(tableResult).isEqualTo(TableResultInternal.TABLE_RESULT_OK);
assertThat(planPath.toFile()).exists();
// This should not mutate the plan, as it already exists
assertThat(
tableEnv.executeSql(
String.format(
"COMPILE PLAN '%s' IF NOT EXISTS FOR INSERT INTO sink SELECT a + 1, b + 1, CONCAT(c, '-something') FROM src",
planPath)))
.isEqualTo(TableResultInternal.TABLE_RESULT_OK);
tableEnv.executeSql(String.format("EXECUTE PLAN '%s'", planPath)).await();
assertResult(DATA, sinkPath);
}
@Test
void testCompilePlanOverwrite() throws Exception {
tableEnv.getConfig().set(TableConfigOptions.PLAN_FORCE_RECOMPILE, true);
Path planPath =
Paths.get(
URI.create(TempDirUtils.newFolder(tempFolder, "plan").getPath())
.getPath(),
"plan.json")
.toAbsolutePath();
List<String> expectedData =
Arrays.asList(
"2,2,hi-something", "3,2,hello-something", "4,3,hello world-something");
File sinkPath = createSourceSinkTables();
TableResult tableResult =
tableEnv.executeSql(
String.format(
"COMPILE PLAN '%s' FOR INSERT INTO sink "
+ "SELECT IF(a > b, a, b) AS a, b + 1 AS b, SUBSTR(c, 1, 4) AS c FROM src WHERE a > 10",
planPath));
assertThat(tableResult).isEqualTo(TableResultInternal.TABLE_RESULT_OK);
assertThat(planPath.toFile()).exists();
// This should overwrite the plan
assertThat(
tableEnv.executeSql(
String.format(
"COMPILE PLAN '%s' FOR INSERT INTO sink SELECT a + 1, b + 1, CONCAT(c, '-something') FROM src",
planPath)))
.isEqualTo(TableResultInternal.TABLE_RESULT_OK);
assertThat(
TableTestUtil.isValidJson(
FileUtils.readFileToString(
planPath.toFile(), StandardCharsets.UTF_8)))
.isTrue();
tableEnv.executeSql(String.format("EXECUTE PLAN '%s'", planPath)).await();
assertResult(expectedData, sinkPath);
}
@Test
void testCompileAndExecutePlan() throws Exception {
Path planPath =
Paths.get(TempDirUtils.newFolder(tempFolder, "plan").getPath(), "plan.json")
.toAbsolutePath();
File sinkPath = createSourceSinkTables();
tableEnv.executeSql(
String.format(
"COMPILE AND EXECUTE PLAN '%s' FOR INSERT INTO sink SELECT * FROM src",
planPath))
.await();
assertThat(planPath.toFile()).exists();
assertResult(DATA, sinkPath);
}
@Test
void testCompileAndExecutePlanWithStatementSet() throws Exception {
Path planPath =
Paths.get(TempDirUtils.newFolder(tempFolder, "plan").getPath(), "plan.json")
.toAbsolutePath();
createTestCsvSourceTable("src", DATA, COLUMNS_DEFINITION);
File sinkAPath = createTestCsvSinkTable("sinkA", COLUMNS_DEFINITION);
File sinkBPath = createTestCsvSinkTable("sinkB", COLUMNS_DEFINITION);
tableEnv.executeSql(
String.format(
"COMPILE AND EXECUTE PLAN '%s' FOR STATEMENT SET BEGIN "
+ "INSERT INTO sinkA SELECT * FROM src;"
+ "INSERT INTO sinkB SELECT a + 1, b + 1, CONCAT(c, '-something') FROM src;"
+ "END",
planPath))
.await();
assertThat(planPath.toFile()).exists();
assertResult(DATA, sinkAPath);
assertResult(
Arrays.asList(
"2,2,hi-something", "3,2,hello-something", "4,3,hello world-something"),
sinkBPath);
}
@Test
void testExplainPlan() throws IOException {
String planFromResources =
JsonTestUtils.setFlinkVersion(
JsonTestUtils.readFromResource("/jsonplan/testGetJsonPlan.out"),
FlinkVersion.current())
.toString();
String actual =
tableEnv.loadPlan(PlanReference.fromJsonString(planFromResources))
.explain(ExplainDetail.JSON_EXECUTION_PLAN);
String expected = TableTestUtil.readFromResource("/explain/testExplainJsonPlan.out");
assertThat(TableTestUtil.replaceNodeIdInOperator(TableTestUtil.replaceStreamNodeId(actual)))
.isEqualTo(expected);
}
@Test
void testPersistedConfigOption() throws Exception {
List<String> data =
Stream.concat(
DATA.stream(),
Stream.of(
"4,2,This string is long",
"5,3,This is an even longer string"))
.collect(Collectors.toList());
String[] sinkColumnDefinitions = new String[] {"a bigint", "b int", "c varchar(11)"};
createTestCsvSourceTable("src", data, COLUMNS_DEFINITION);
File sinkPath = createTestCsvSinkTable("sink", sinkColumnDefinitions);
// Set config option to trim the strings, so it's persisted in the json plan
tableEnv.getConfig()
.getConfiguration()
.set(
ExecutionConfigOptions.TABLE_EXEC_SINK_TYPE_LENGTH_ENFORCER,
ExecutionConfigOptions.TypeLengthEnforcer.TRIM_PAD);
CompiledPlan plan = tableEnv.compilePlanSql("INSERT INTO sink SELECT * FROM src");
// Set config option to trim the strings to IGNORE, to validate that the persisted config
// is overriding the environment setting.
tableEnv.getConfig()
.getConfiguration()
.set(
ExecutionConfigOptions.TABLE_EXEC_SINK_TYPE_LENGTH_ENFORCER,
ExecutionConfigOptions.TypeLengthEnforcer.IGNORE);
plan.execute().await();
List<String> expected =
Stream.concat(DATA.stream(), Stream.of("4,2,This string", "5,3,This is an "))
.collect(Collectors.toList());
assertResult(expected, sinkPath);
}
@Test
void testCompileAndExecutePlanBatchMode() throws Exception {
tableEnv = TableEnvironment.create(EnvironmentSettings.inBatchMode());
File sinkPath = createSourceSinkTables();
tableEnv.compilePlanSql("INSERT INTO sink SELECT * FROM src").execute().await();
assertResult(DATA, sinkPath);
}
private File createSourceSinkTables() throws IOException {
createTestCsvSourceTable("src", DATA, COLUMNS_DEFINITION);
return createTestCsvSinkTable("sink", COLUMNS_DEFINITION);
}
private String getPreparedToCompareCompiledPlan(final String planAsString) {
return TableTestUtil.replaceExecNodeId(TableTestUtil.replaceFlinkVersion(planAsString));
}
}
|
CompiledPlanITCase
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/internal/IndexedDiff.java
|
{
"start": 774,
"end": 1786
}
|
class ____ {
public final Object actual;
public final Object expected;
public final int index;
/**
* Create a {@link IndexedDiff}.
* @param actual the actual value of the diff.
* @param expected the expected value of the diff.
* @param index the index the diff occurred at.
*/
public IndexedDiff(Object actual, Object expected, int index) {
this.actual = actual;
this.expected = expected;
this.index = index;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IndexedDiff that = (IndexedDiff) o;
return index == that.index && Objects.equals(actual, that.actual) && Objects.equals(expected, that.expected);
}
@Override
public String toString() {
return "IndexedDiff(actual=%s, expected=%s, index=%s)".formatted(this.actual, this.expected, this.index);
}
@Override
public int hashCode() {
return Objects.hash(actual, expected, index);
}
}
|
IndexedDiff
|
java
|
spring-projects__spring-boot
|
loader/spring-boot-loader/src/test/java/org/springframework/boot/loader/nio/file/NestedFileSystemTests.java
|
{
"start": 1180,
"end": 5661
}
|
class ____ {
@TempDir
File temp;
private NestedFileSystemProvider provider;
private Path jarPath;
private NestedFileSystem fileSystem;
@BeforeEach
void setup() {
this.provider = new NestedFileSystemProvider();
this.jarPath = new File(this.temp, "test.jar").toPath();
this.fileSystem = new NestedFileSystem(this.provider, this.jarPath);
}
@Test
void providerReturnsProvider() {
assertThat(this.fileSystem.provider()).isSameAs(this.provider);
}
@Test
void getJarPathReturnsJarPath() {
assertThat(this.fileSystem.getJarPath()).isSameAs(this.jarPath);
}
@Test
void closeClosesFileSystem() throws Exception {
this.fileSystem.close();
assertThat(this.fileSystem.isOpen()).isFalse();
}
@Test
void closeWhenAlreadyClosedDoesNothing() throws Exception {
this.fileSystem.close();
this.fileSystem.close();
assertThat(this.fileSystem.isOpen()).isFalse();
}
@Test
void isOpenWhenOpenReturnsTrue() {
assertThat(this.fileSystem.isOpen()).isTrue();
}
@Test
void isOpenWhenClosedReturnsFalse() throws Exception {
this.fileSystem.close();
assertThat(this.fileSystem.isOpen()).isFalse();
}
@Test
void isReadOnlyReturnsTrue() {
assertThat(this.fileSystem.isReadOnly()).isTrue();
}
@Test
void getSeparatorReturnsSeparator() {
assertThat(this.fileSystem.getSeparator()).isEqualTo("/!");
}
@Test
void getRootDirectoryWhenOpenReturnsEmptyIterable() {
assertThat(this.fileSystem.getRootDirectories()).isEmpty();
}
@Test
void getRootDirectoryWhenClosedThrowsException() throws Exception {
this.fileSystem.close();
assertThatExceptionOfType(ClosedFileSystemException.class)
.isThrownBy(() -> this.fileSystem.getRootDirectories());
}
@Test
void supportedFileAttributeViewsWhenOpenReturnsBasic() {
assertThat(this.fileSystem.supportedFileAttributeViews()).containsExactly("basic");
}
@Test
void supportedFileAttributeViewsWhenClosedThrowsException() throws Exception {
this.fileSystem.close();
assertThatExceptionOfType(ClosedFileSystemException.class)
.isThrownBy(() -> this.fileSystem.supportedFileAttributeViews());
}
@Test
void getPathWhenClosedThrowsException() throws Exception {
this.fileSystem.close();
assertThatExceptionOfType(ClosedFileSystemException.class)
.isThrownBy(() -> this.fileSystem.getPath("nested.jar"));
}
@Test
void getPathWhenFirstIsNull() {
Path path = this.fileSystem.getPath(null);
assertThat(path.toString()).endsWith(File.separator + "test.jar");
}
@Test
void getPathWhenFirstIsBlank() {
Path path = this.fileSystem.getPath("");
assertThat(path.toString()).endsWith(File.separator + "test.jar");
}
@Test
void getPathWhenMoreIsNotEmptyThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.fileSystem.getPath("nested.jar", "another.jar"))
.withMessage("Nested paths must contain a single element");
}
@Test
void getPathReturnsPath() {
assertThat(this.fileSystem.getPath("nested.jar")).isInstanceOf(NestedPath.class);
}
@Test
void getPathMatchThrowsException() {
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(() -> this.fileSystem.getPathMatcher("*"))
.withMessage("Nested paths do not support path matchers");
}
@Test
void getUserPrincipalLookupServiceThrowsException() {
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(() -> this.fileSystem.getUserPrincipalLookupService())
.withMessage("Nested paths do not have a user principal lookup service");
}
@Test
void newWatchServiceThrowsException() {
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(() -> this.fileSystem.newWatchService())
.withMessage("Nested paths do not support the WatchService");
}
@Test
void toStringReturnsString() {
assertThat(this.fileSystem).hasToString(this.jarPath.toAbsolutePath().toString());
}
@Test
void equalsAndHashCode() {
Path jp1 = new File(this.temp, "test1.jar").toPath();
Path jp2 = new File(this.temp, "test1.jar").toPath();
Path jp3 = new File(this.temp, "test2.jar").toPath();
NestedFileSystem f1 = new NestedFileSystem(this.provider, jp1);
NestedFileSystem f2 = new NestedFileSystem(this.provider, jp1);
NestedFileSystem f3 = new NestedFileSystem(this.provider, jp2);
NestedFileSystem f4 = new NestedFileSystem(this.provider, jp3);
assertThat(f1).isEqualTo(f1).isEqualTo(f2).isEqualTo(f3).isNotEqualTo(f4);
assertThat(f1).hasSameHashCodeAs(f2);
}
}
|
NestedFileSystemTests
|
java
|
apache__camel
|
components/camel-rest/src/main/java/org/apache/camel/component/rest/RestApiEndpoint.java
|
{
"start": 2063,
"end": 11832
}
|
class ____ extends DefaultEndpoint {
public static final String[] DEFAULT_REST_API_CONSUMER_COMPONENTS
= new String[] { "platform-http", "servlet", "jetty", "undertow", "netty-http" };
public static final String DEFAULT_API_COMPONENT_NAME = "openapi";
public static final String RESOURCE_PATH = "META-INF/services/org/apache/camel/restapi/";
private static final Logger LOG = LoggerFactory.getLogger(RestApiEndpoint.class);
@UriPath
@Metadata(required = true)
private String path;
@UriParam
private String consumerComponentName;
@UriParam
private String apiComponentName;
private Map<String, Object> parameters;
public RestApiEndpoint(String endpointUri, RestApiComponent component) {
super(endpointUri, component);
setExchangePattern(ExchangePattern.InOut);
}
@Override
public boolean isRemote() {
return false;
}
@Override
public RestApiComponent getComponent() {
return (RestApiComponent) super.getComponent();
}
public String getPath() {
return path;
}
/**
* The base path
*/
public void setPath(String path) {
this.path = path;
}
public String getConsumerComponentName() {
return consumerComponentName;
}
/**
* The Camel Rest component to use for the consumer REST transport, such as jetty, servlet, undertow. If no
* component has been explicitly configured, then Camel will lookup if there is a Camel component that integrates
* with the Rest DSL, or if a org.apache.camel.spi.RestConsumerFactory is registered in the registry. If either one
* is found, then that is being used.
*/
public void setConsumerComponentName(String consumerComponentName) {
this.consumerComponentName = consumerComponentName;
}
public String getApiComponentName() {
return apiComponentName;
}
/**
* The Camel Rest API component to use for generating the API of the REST services, such as openapi.
*/
public void setApiComponentName(String apiComponentName) {
this.apiComponentName = apiComponentName;
}
public Map<String, Object> getParameters() {
return parameters;
}
/**
* Additional parameters to configure the consumer of the REST transport for this REST service
*/
public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
@Override
public Producer createProducer() throws Exception {
RestApiProcessorFactory factory = null;
RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), getConsumerComponentName());
// lookup in registry
Set<RestApiProcessorFactory> factories = getCamelContext().getRegistry().findByType(RestApiProcessorFactory.class);
if (factories != null && factories.size() == 1) {
factory = factories.iterator().next();
}
// lookup on classpath using factory finder to automatic find it (just add camel-openapi-java to classpath etc)
if (factory == null) {
String name = apiComponentName != null ? apiComponentName : config.getApiComponent();
if (name == null) {
name = DEFAULT_API_COMPONENT_NAME; //use openapi first
}
FactoryFinder finder = getCamelContext().getCamelContextExtension().getFactoryFinder(RESOURCE_PATH);
factory = finder.newInstance(name, RestApiProcessorFactory.class).orElse(null);
}
if (factory == null) {
String name = apiComponentName != null ? apiComponentName : config.getApiComponent();
if (name == null) {
name = "swagger"; //use swagger as fallback
}
FactoryFinder finder = getCamelContext().getCamelContextExtension().getFactoryFinder(RESOURCE_PATH);
factory = finder.newInstance(name, RestApiProcessorFactory.class).orElse(null);
}
if (factory != null) {
// if no explicit port/host configured, then use port from rest configuration
String host = "";
int port = 80;
if (config.getApiHost() != null) {
host = config.getApiHost();
} else if (config.getHost() != null) {
host = config.getHost();
}
int num = config.getPort();
if (num > 0) {
port = num;
}
// if no explicit hostname set then resolve the hostname
if (ObjectHelper.isEmpty(host)) {
if (config.getHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
host = "0.0.0.0";
} else if (config.getHostNameResolver() == RestConfiguration.RestHostNameResolver.localHostName) {
host = HostUtils.getLocalHostName();
} else if (config.getHostNameResolver() == RestConfiguration.RestHostNameResolver.localIp) {
host = HostUtils.getLocalIp();
}
// no host was configured so calculate a host to use
// there should be no schema in the host (but only port)
String targetHost = host + (port != 80 ? ":" + port : "");
getParameters().put("host", targetHost);
}
// the base path should start with a leading slash
String path = getPath();
if (path != null && !path.startsWith("/")) {
path = "/" + path;
}
Processor processor = factory.createApiProcessor(getCamelContext(), path, config, getParameters());
return new RestApiProducer(this, processor);
} else {
throw new IllegalStateException(
"Cannot find RestApiProcessorFactory in Registry or classpath (such as the camel-openapi-java component)");
}
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
RestApiConsumerFactory factory = null;
String cname = null;
// we use the rest component as the HTTP consumer to service the API
// the API then uses the api component (eg usually camel-openapi-java) to build the API
if (getConsumerComponentName() != null) {
Object comp = getCamelContext().getRegistry().lookupByName(getConsumerComponentName());
if (comp instanceof RestApiConsumerFactory restApiConsumerFactory) {
factory = restApiConsumerFactory;
} else {
comp = getCamelContext().getComponent(getConsumerComponentName());
if (comp instanceof RestApiConsumerFactory restApiConsumerFactory) {
factory = restApiConsumerFactory;
}
}
if (factory == null) {
if (comp != null) {
throw new IllegalArgumentException(
"Component " + getConsumerComponentName() + " is not a RestApiConsumerFactory");
} else {
throw new NoSuchBeanException(getConsumerComponentName(), RestApiConsumerFactory.class.getName());
}
}
cname = getConsumerComponentName();
}
// try all components
if (factory == null) {
for (String name : getCamelContext().getComponentNames()) {
Component comp = getCamelContext().getComponent(name);
if (comp instanceof RestApiConsumerFactory restApiConsumerFactory) {
factory = restApiConsumerFactory;
cname = name;
break;
}
}
}
// lookup in registry
if (factory == null) {
Set<RestApiConsumerFactory> factories = getCamelContext().getRegistry().findByType(RestApiConsumerFactory.class);
if (factories != null && factories.size() == 1) {
factory = factories.iterator().next();
}
}
// no explicit factory found then try to see if we can find any of the default rest consumer components
if (factory == null) {
RestApiConsumerFactory found = null;
String foundName = null;
for (String name : DEFAULT_REST_API_CONSUMER_COMPONENTS) {
Object comp = getCamelContext().getComponent(name, true);
if (comp instanceof RestApiConsumerFactory restApiConsumerFactory) {
found = restApiConsumerFactory;
foundName = name;
break;
}
}
if (found != null) {
LOG.debug("Auto discovered {} as RestApiConsumerFactory", foundName);
factory = found;
}
}
if (factory != null) {
// calculate the url to the rest API service
RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), cname);
// calculate the url to the rest API service
String path = getPath();
if (path != null && !path.startsWith("/")) {
path = "/" + path;
}
Consumer consumer = factory.createApiConsumer(getCamelContext(), processor, path, config, getParameters());
configureConsumer(consumer);
return consumer;
} else {
throw new IllegalStateException("Cannot find RestApiConsumerFactory in Registry or as a Component to use");
}
}
@Override
public boolean isLenientProperties() {
return true;
}
}
|
RestApiEndpoint
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/api/common/typeutils/CompositeTypeSerializerSnapshotTest.java
|
{
"start": 1470,
"end": 12233
}
|
class ____ {
// ------------------------------------------------------------------------------------------------
// Scope: tests CompositeTypeSerializerSnapshot#resolveSchemaCompatibility
// ------------------------------------------------------------------------------------------------
@Test
void testIncompatiblePrecedence() throws IOException {
final TypeSerializer<?>[] testNestedSerializers = {
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
new NestedSerializer(TargetCompatibility.COMPATIBLE_AFTER_MIGRATION),
new NestedSerializer(TargetCompatibility.INCOMPATIBLE),
new NestedSerializer(TargetCompatibility.COMPATIBLE_WITH_RECONFIGURED_SERIALIZER)
};
TypeSerializerSchemaCompatibility<String> compatibility =
snapshotCompositeSerializerAndGetSchemaCompatibilityAfterRestore(
testNestedSerializers,
testNestedSerializers,
OuterSchemaCompatibility.COMPATIBLE_AS_IS);
assertThat(compatibility.isIncompatible()).isTrue();
}
@Test
void testCompatibleAfterMigrationPrecedence() throws IOException {
TypeSerializer<?>[] testNestedSerializers = {
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
new NestedSerializer(TargetCompatibility.COMPATIBLE_AFTER_MIGRATION),
new NestedSerializer(TargetCompatibility.COMPATIBLE_WITH_RECONFIGURED_SERIALIZER),
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
};
TypeSerializerSchemaCompatibility<String> compatibility =
snapshotCompositeSerializerAndGetSchemaCompatibilityAfterRestore(
testNestedSerializers,
testNestedSerializers,
OuterSchemaCompatibility.COMPATIBLE_AS_IS);
assertThat(compatibility.isCompatibleAfterMigration()).isTrue();
}
@Test
void testCompatibleWithReconfiguredSerializerPrecedence() throws IOException {
TypeSerializer<?>[] testNestedSerializers = {
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
new NestedSerializer(TargetCompatibility.COMPATIBLE_WITH_RECONFIGURED_SERIALIZER),
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
};
TypeSerializerSchemaCompatibility<String> compatibility =
snapshotCompositeSerializerAndGetSchemaCompatibilityAfterRestore(
testNestedSerializers,
testNestedSerializers,
OuterSchemaCompatibility.COMPATIBLE_AS_IS);
assertThat(compatibility.isCompatibleWithReconfiguredSerializer()).isTrue();
TestCompositeTypeSerializer reconfiguredSerializer =
(TestCompositeTypeSerializer) compatibility.getReconfiguredSerializer();
TypeSerializer<?>[] reconfiguredNestedSerializers =
reconfiguredSerializer.getNestedSerializers();
// nested serializer at index 1 should strictly be a ReconfiguredNestedSerializer
// nested serializer at index 0 and 2 is RestoredNestedSerializer after checking
// compatibility
assertThat(reconfiguredNestedSerializers[0]).isInstanceOf(RestoredNestedSerializer.class);
assertThat(reconfiguredNestedSerializers[1])
.isInstanceOf(ReconfiguredNestedSerializer.class);
assertThat(reconfiguredNestedSerializers[2]).isInstanceOf(RestoredNestedSerializer.class);
}
@Test
void testCompatibleAsIsPrecedence() throws IOException {
TypeSerializer<?>[] testNestedSerializers = {
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
};
TypeSerializerSchemaCompatibility<String> compatibility =
snapshotCompositeSerializerAndGetSchemaCompatibilityAfterRestore(
testNestedSerializers,
testNestedSerializers,
OuterSchemaCompatibility.COMPATIBLE_AS_IS);
assertThat(compatibility.isCompatibleAsIs()).isTrue();
}
@Test
void testOuterSnapshotIncompatiblePrecedence() throws IOException {
TypeSerializer<?>[] testNestedSerializers = {
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
};
TypeSerializerSchemaCompatibility<String> compatibility =
snapshotCompositeSerializerAndGetSchemaCompatibilityAfterRestore(
testNestedSerializers,
testNestedSerializers,
OuterSchemaCompatibility.INCOMPATIBLE);
// even though nested serializers are compatible, incompatibility of the outer
// snapshot should have higher precedence in the final result
assertThat(compatibility.isIncompatible()).isTrue();
}
@Test
void testOuterSnapshotRequiresMigrationPrecedence() throws IOException {
TypeSerializer<?>[] testNestedSerializers = {
new NestedSerializer(TargetCompatibility.COMPATIBLE_WITH_RECONFIGURED_SERIALIZER),
};
TypeSerializerSchemaCompatibility<String> compatibility =
snapshotCompositeSerializerAndGetSchemaCompatibilityAfterRestore(
testNestedSerializers,
testNestedSerializers,
OuterSchemaCompatibility.COMPATIBLE_AFTER_MIGRATION);
// even though nested serializers can be compatible with reconfiguration, the outer
// snapshot requiring migration should have higher precedence in the final result
assertThat(compatibility.isCompatibleAfterMigration()).isTrue();
}
@Test
void testNestedFieldSerializerArityMismatchPrecedence() throws IOException {
final TypeSerializer<?>[] initialNestedSerializers = {
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
};
final TypeSerializer<?>[] newNestedSerializers = {
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
};
TypeSerializerSchemaCompatibility<String> compatibility =
snapshotCompositeSerializerAndGetSchemaCompatibilityAfterRestore(
initialNestedSerializers,
newNestedSerializers,
OuterSchemaCompatibility.COMPATIBLE_AS_IS);
// arity mismatch in the nested serializers should return incompatible as the result
assertThat(compatibility.isIncompatible()).isTrue();
}
private TypeSerializerSchemaCompatibility<String>
snapshotCompositeSerializerAndGetSchemaCompatibilityAfterRestore(
TypeSerializer<?>[] initialNestedSerializers,
TypeSerializer<?>[] newNestedSerializer,
OuterSchemaCompatibility mockOuterSchemaCompatibilityResult)
throws IOException {
TestCompositeTypeSerializer testSerializer =
new TestCompositeTypeSerializer(initialNestedSerializers);
TypeSerializerSnapshot<String> testSerializerSnapshot =
testSerializer.snapshotConfiguration();
DataOutputSerializer out = new DataOutputSerializer(128);
TypeSerializerSnapshot.writeVersionedSnapshot(out, testSerializerSnapshot);
DataInputDeserializer in = new DataInputDeserializer(out.getCopyOfBuffer());
testSerializerSnapshot =
TypeSerializerSnapshot.readVersionedSnapshot(
in, Thread.currentThread().getContextClassLoader());
TestCompositeTypeSerializer newTestSerializer =
new TestCompositeTypeSerializer(
mockOuterSchemaCompatibilityResult, newNestedSerializer);
return newTestSerializer
.snapshotConfiguration()
.resolveSchemaCompatibility(testSerializerSnapshot);
}
// ------------------------------------------------------------------------------------------------
// Scope: tests CompositeTypeSerializerSnapshot#restoreSerializer
// ------------------------------------------------------------------------------------------------
@Test
void testRestoreCompositeTypeSerializer() throws IOException {
// the target compatibilities of the nested serializers doesn't matter,
// because we're only testing the restore serializer
TypeSerializer<?>[] testNestedSerializers = {
new NestedSerializer(TargetCompatibility.COMPATIBLE_AS_IS),
new NestedSerializer(TargetCompatibility.INCOMPATIBLE),
new NestedSerializer(TargetCompatibility.COMPATIBLE_AFTER_MIGRATION)
};
TestCompositeTypeSerializer testSerializer =
new TestCompositeTypeSerializer(testNestedSerializers);
TypeSerializerSnapshot<String> testSerializerSnapshot =
testSerializer.snapshotConfiguration();
DataOutputSerializer out = new DataOutputSerializer(128);
TypeSerializerSnapshot.writeVersionedSnapshot(out, testSerializerSnapshot);
DataInputDeserializer in = new DataInputDeserializer(out.getCopyOfBuffer());
testSerializerSnapshot =
TypeSerializerSnapshot.readVersionedSnapshot(
in, Thread.currentThread().getContextClassLoader());
// now, restore the composite type serializer;
// the restored nested serializer should be a RestoredNestedSerializer
testSerializer = (TestCompositeTypeSerializer) testSerializerSnapshot.restoreSerializer();
assertThat(RestoredNestedSerializer.class)
.isSameAs(testSerializer.getNestedSerializers()[0].getClass());
assertThat(RestoredNestedSerializer.class)
.isSameAs(testSerializer.getNestedSerializers()[1].getClass());
assertThat(RestoredNestedSerializer.class)
.isSameAs(testSerializer.getNestedSerializers()[2].getClass());
}
// ------------------------------------------------------------------------------------------------
// Test utilities
// ------------------------------------------------------------------------------------------------
/**
* A simple composite serializer used for testing. It can be configured with an array of nested
* serializers, as well as outer configuration (represented as String).
*/
public static
|
CompositeTypeSerializerSnapshotTest
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/ComponentHierarchyValidationTest.java
|
{
"start": 10103,
"end": 11226
}
|
interface ____ {}");
CompilerTests.daggerCompiler(
testScope, moduleWithScopedProvides, moduleWithScopedBinds, parent, child)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining(
String.join(
"\n",
"test.Child repeats modules with scoped bindings or declarations:",
"- test.Parent also includes:",
" - test.ModuleWithScopedProvides with scopes: @test.TestScope",
" - test.ModuleWithScopedBinds with scopes: @test.TestScope"));
});
}
@Test
public void repeatedModulesWithReusableScope() {
Source moduleWithScopedProvides =
CompilerTests.javaSource(
"test.ModuleWithScopedProvides",
"package test;",
"",
"import dagger.Module;",
"import dagger.Provides;",
"import dagger.Reusable;",
"",
"@Module",
"
|
Child
|
java
|
quarkusio__quarkus
|
extensions/vertx/runtime/src/main/java/io/quarkus/vertx/core/runtime/graal/VertxSubstitutions.java
|
{
"start": 6280,
"end": 6412
}
|
class ____ {
@Alias
static List<String> get() {
return null;
}
}
|
Target_io_vertx_core_spi_tls_DefaultJDKCipherSuite
|
java
|
grpc__grpc-java
|
interop-testing/src/test/java/io/grpc/testing/integration/TransportCompressionTest.java
|
{
"start": 2137,
"end": 6667
}
|
class ____ extends AbstractInteropTest {
// Masquerade as identity.
private static final Fzip FZIPPER = new Fzip("gzip", new Codec.Gzip());
private volatile boolean expectFzip;
private static final DecompressorRegistry decompressors = DecompressorRegistry.emptyInstance()
.with(Codec.Identity.NONE, false)
.with(FZIPPER, true);
private static final CompressorRegistry compressors = CompressorRegistry.newEmptyInstance();
@Before
public void beforeTests() {
FZIPPER.anyRead = false;
FZIPPER.anyWritten = false;
}
@BeforeClass
public static void registerCompressors() {
compressors.register(FZIPPER);
compressors.register(Codec.Identity.NONE);
}
@Override
protected ServerBuilder<?> getServerBuilder() {
NettyServerBuilder builder = NettyServerBuilder.forPort(0, InsecureServerCredentials.create())
.maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
.compressorRegistry(compressors)
.decompressorRegistry(decompressors)
.intercept(new ServerInterceptor() {
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
Metadata headers, ServerCallHandler<ReqT, RespT> next) {
Listener<ReqT> listener = next.startCall(call, headers);
// TODO(carl-mastrangelo): check that encoding was set.
call.setMessageCompression(true);
return listener;
}
});
// Disable the default census stats tracer, use testing tracer instead.
InternalNettyServerBuilder.setStatsEnabled(builder, false);
return builder.addStreamTracerFactory(createCustomCensusTracerFactory());
}
@Test
public void compresses() {
expectFzip = true;
final SimpleRequest request = SimpleRequest.newBuilder()
.setResponseSize(314159)
.setResponseCompressed(BoolValue.newBuilder().setValue(true))
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[271828])))
.build();
final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[314159])))
.build();
assertEquals(goldenResponse, blockingStub.unaryCall(request));
// Assert that compression took place
assertTrue(FZIPPER.anyRead);
assertTrue(FZIPPER.anyWritten);
}
@Override
protected NettyChannelBuilder createChannelBuilder() {
NettyChannelBuilder builder = NettyChannelBuilder.forAddress(getListenAddress())
.maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
.decompressorRegistry(decompressors)
.compressorRegistry(compressors)
.intercept(new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
final ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
return new ForwardingClientCall<ReqT, RespT>() {
@Override
protected ClientCall<ReqT, RespT> delegate() {
return call;
}
@Override
public void start(
final ClientCall.Listener<RespT> responseListener, Metadata headers) {
ClientCall.Listener<RespT> listener = new ForwardingClientCallListener<RespT>() {
@Override
protected io.grpc.ClientCall.Listener<RespT> delegate() {
return responseListener;
}
@Override
public void onHeaders(Metadata headers) {
super.onHeaders(headers);
if (expectFzip) {
String encoding = headers.get(GrpcUtil.MESSAGE_ENCODING_KEY);
assertEquals(encoding, FZIPPER.getMessageEncoding());
}
}
};
super.start(listener, headers);
setMessageCompression(true);
}
};
}
})
.usePlaintext();
// Disable the default census stats interceptor, use testing interceptor instead.
InternalNettyChannelBuilder.setStatsEnabled(builder, false);
return builder.intercept(createCensusStatsClientInterceptor());
}
/**
* Fzip is a custom compressor.
*/
static
|
TransportCompressionTest
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/error/ShouldNotBeEqualIgnoringCase.java
|
{
"start": 858,
"end": 1604
}
|
class ____ extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link org.assertj.core.error.ShouldNotBeEqualIgnoringCase}</code>.
*
* @param actual the actual value in the failed assertion.
* @param expected the expected value in the failed assertion.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldNotBeEqualIgnoringCase(CharSequence actual, CharSequence expected) {
return new ShouldNotBeEqualIgnoringCase(actual, expected);
}
private ShouldNotBeEqualIgnoringCase(CharSequence actual, CharSequence expected) {
super("%nExpecting actual:%n %s%nnot to be equal to:%n %s%nignoring case considerations", actual, expected);
}
}
|
ShouldNotBeEqualIgnoringCase
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java
|
{
"start": 1334,
"end": 12648
}
|
class ____ extends AbstractFormTagTests {
private InputTag tag;
private TestBean rob;
@Override
protected void onSetUp() {
this.tag = createTag(getWriter());
this.tag.setParent(getFormTag());
this.tag.setPageContext(getPageContext());
}
@Override
protected TestBean createTestBean() {
// set up test data
this.rob = new TestBean();
this.rob.setName("Rob");
this.rob.setMyFloat(12.34f);
TestBean sally = new TestBean();
sally.setName("Sally");
this.rob.setSpouse(sally);
return this.rob;
}
protected final InputTag getTag() {
return this.tag;
}
@Test
void simpleBind() throws Exception {
this.tag.setPath("name");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "Rob");
}
@Test
void simpleBindTagWithinForm() throws Exception {
BindTag bindTag = new BindTag();
bindTag.setPath("name");
bindTag.setPageContext(getPageContext());
bindTag.doStartTag();
BindStatus bindStatus = (BindStatus) getPageContext().findAttribute(BindTag.STATUS_VARIABLE_NAME);
assertThat(bindStatus.getValue()).isEqualTo("Rob");
}
@Test
void simpleBindWithHtmlEscaping() throws Exception {
final String NAME = "Rob \"I Love Cafés\" Harrop";
final String HTML_ESCAPED_NAME = "Rob "I Love Cafés" Harrop";
this.tag.setPath("name");
this.rob.setName(NAME);
assertThat(this.tag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, HTML_ESCAPED_NAME);
}
@Test
void simpleBindWithHtmlEscapingAndCharacterEncoding() throws Exception {
final String NAME = "Rob \"I Love Cafés\" Harrop";
final String HTML_ESCAPED_NAME = "Rob "I Love Cafés" Harrop";
getPageContext().getResponse().setCharacterEncoding("UTF-8");
this.tag.setPath("name");
this.rob.setName(NAME);
assertThat(this.tag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, HTML_ESCAPED_NAME);
}
protected void assertValueAttribute(String output, String expectedValue) {
assertContainsAttribute(output, "value", expectedValue);
}
@Test
void complexBind() throws Exception {
this.tag.setPath("spouse.name");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "id", "spouse.name");
assertContainsAttribute(output, "name", "spouse.name");
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "Sally");
}
@Test
void withAllAttributes() throws Exception {
String title = "aTitle";
String id = "123";
String size = "12";
String cssClass = "textfield";
String cssStyle = "width:10px";
String lang = "en";
String dir = "ltr";
String tabindex = "2";
boolean disabled = true;
String onclick = "doClick()";
String ondblclick = "doDblclick()";
String onkeydown = "doKeydown()";
String onkeypress = "doKeypress()";
String onkeyup = "doKeyup()";
String onmousedown = "doMouseDown()";
String onmousemove = "doMouseMove()";
String onmouseout = "doMouseOut()";
String onmouseover = "doMouseOver()";
String onmouseup = "doMouseUp()";
String onfocus = "doFocus()";
String onblur = "doBlur()";
String onchange = "doChange()";
String accesskey = "a";
String maxlength = "12";
String alt = "Some text";
String onselect = "doSelect()";
boolean readonly = true;
String autocomplete = "off";
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
this.tag.setId(id);
this.tag.setPath("name");
this.tag.setSize(size);
this.tag.setCssClass(cssClass);
this.tag.setCssStyle(cssStyle);
this.tag.setTitle(title);
this.tag.setLang(lang);
this.tag.setDir(dir);
this.tag.setTabindex(tabindex);
this.tag.setDisabled(disabled);
this.tag.setOnclick(onclick);
this.tag.setOndblclick(ondblclick);
this.tag.setOnkeydown(onkeydown);
this.tag.setOnkeypress(onkeypress);
this.tag.setOnkeyup(onkeyup);
this.tag.setOnmousedown(onmousedown);
this.tag.setOnmousemove(onmousemove);
this.tag.setOnmouseout(onmouseout);
this.tag.setOnmouseover(onmouseover);
this.tag.setOnmouseup(onmouseup);
this.tag.setOnfocus(onfocus);
this.tag.setOnblur(onblur);
this.tag.setOnchange(onchange);
this.tag.setAccesskey(accesskey);
this.tag.setMaxlength(maxlength);
this.tag.setAlt(alt);
this.tag.setOnselect(onselect);
this.tag.setReadonly(readonly);
this.tag.setAutocomplete(autocomplete);
this.tag.setDynamicAttribute(null, dynamicAttribute1, dynamicAttribute1);
this.tag.setDynamicAttribute(null, dynamicAttribute2, dynamicAttribute2);
assertThat(this.tag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertContainsAttribute(output, "id", id);
assertValueAttribute(output, "Rob");
assertContainsAttribute(output, "size", size);
assertContainsAttribute(output, "class", cssClass);
assertContainsAttribute(output, "style", cssStyle);
assertContainsAttribute(output, "title", title);
assertContainsAttribute(output, "lang", lang);
assertContainsAttribute(output, "dir", dir);
assertContainsAttribute(output, "tabindex", tabindex);
assertContainsAttribute(output, "disabled", "disabled");
assertContainsAttribute(output, "onclick", onclick);
assertContainsAttribute(output, "ondblclick", ondblclick);
assertContainsAttribute(output, "onkeydown", onkeydown);
assertContainsAttribute(output, "onkeypress", onkeypress);
assertContainsAttribute(output, "onkeyup", onkeyup);
assertContainsAttribute(output, "onmousedown", onmousedown);
assertContainsAttribute(output, "onmousemove", onmousemove);
assertContainsAttribute(output, "onmouseout", onmouseout);
assertContainsAttribute(output, "onmouseover", onmouseover);
assertContainsAttribute(output, "onmouseup", onmouseup);
assertContainsAttribute(output, "onfocus", onfocus);
assertContainsAttribute(output, "onblur", onblur);
assertContainsAttribute(output, "onchange", onchange);
assertContainsAttribute(output, "accesskey", accesskey);
assertContainsAttribute(output, "maxlength", maxlength);
assertContainsAttribute(output, "alt", alt);
assertContainsAttribute(output, "onselect", onselect);
assertContainsAttribute(output, "readonly", "readonly");
assertContainsAttribute(output, "autocomplete", autocomplete);
assertContainsAttribute(output, dynamicAttribute1, dynamicAttribute1);
assertContainsAttribute(output, dynamicAttribute2, dynamicAttribute2);
}
@Test
void withNestedBind() throws Exception {
NestedPathTag nestedPathTag = new NestedPathTag();
nestedPathTag.setPath("spouse.");
nestedPathTag.setPageContext(getPageContext());
nestedPathTag.doStartTag();
this.tag.setPath("name");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "Sally");
}
@Test
void withNestedBindTagWithinForm() throws Exception {
NestedPathTag nestedPathTag = new NestedPathTag();
nestedPathTag.setPath("spouse.");
nestedPathTag.setPageContext(getPageContext());
nestedPathTag.doStartTag();
BindTag bindTag = new BindTag();
bindTag.setPath("name");
bindTag.setPageContext(getPageContext());
bindTag.doStartTag();
BindStatus bindStatus = (BindStatus) getPageContext().findAttribute(BindTag.STATUS_VARIABLE_NAME);
assertThat(bindStatus.getValue()).isEqualTo("Sally");
}
@Test
void withErrors() throws Exception {
this.tag.setPath("name");
this.tag.setCssClass("good");
this.tag.setCssErrorClass("bad");
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.rob, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
assertThat(this.tag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "Rob");
assertContainsAttribute(output, "class", "bad");
}
@Test
void disabledFalse() throws Exception {
this.tag.setPath("name");
this.tag.setDisabled(false);
this.tag.doStartTag();
String output = getOutput();
assertAttributeNotPresent(output, "disabled");
}
@Test
void withCustomBinder() throws Exception {
this.tag.setPath("myFloat");
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.rob, COMMAND_NAME);
errors.getPropertyAccessor().registerCustomEditor(Float.class, new SimpleFloatEditor());
exposeBindingResult(errors);
assertThat(this.tag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "12.34f");
}
@Test // SPR-3127
void readOnlyAttributeRenderingWhenReadonlyIsTrue() throws Exception {
this.tag.setPath("name");
this.tag.setReadonly(true);
assertThat(this.tag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertContainsAttribute(output, "readonly", "readonly");
assertValueAttribute(output, "Rob");
}
@Test
void dynamicTypeAttribute() throws JspException {
this.tag.setPath("myFloat");
this.tag.setDynamicAttribute(null, "type", "number");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", "number");
assertValueAttribute(output, "12.34");
}
@Test
void dynamicTypeRadioAttribute() {
assertThatIllegalArgumentException().isThrownBy(() ->
this.tag.setDynamicAttribute(null, "type", "radio"))
.withMessage("Attribute type=\"radio\" is not allowed");
}
@Test
void dynamicTypeCheckboxAttribute() {
assertThatIllegalArgumentException().isThrownBy(() ->
this.tag.setDynamicAttribute(null, "type", "checkbox"))
.withMessage("Attribute type=\"checkbox\" is not allowed");
}
protected final void assertTagClosed(String output) {
assertThat(output).as("Tag not closed properly").endsWith("/>");
}
protected final void assertTagOpened(String output) {
assertThat(output).as("Tag not opened properly").startsWith("<input ");
}
@SuppressWarnings("serial")
protected InputTag createTag(final Writer writer) {
return new InputTag() {
@Override
protected TagWriter createTagWriter() {
return new TagWriter(writer);
}
};
}
protected String getType() {
return "text";
}
}
|
InputTagTests
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/ITestAzureBlobFileSystemBackCompat.java
|
{
"start": 1322,
"end": 3929
}
|
class ____ extends
AbstractAbfsIntegrationTest {
public ITestAzureBlobFileSystemBackCompat() throws Exception {
super();
}
@Test
public void testBlobBackCompat() throws Exception {
final AzureBlobFileSystem fs = this.getFileSystem();
assumeThat(getIsNamespaceEnabled(getFileSystem()))
.as("This test does not support namespace enabled account")
.isFalse();
String storageConnectionString = getBlobConnectionString();
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
CloudBlobContainer container = blobClient.getContainerReference(this.getFileSystemName());
container.createIfNotExists();
Path testPath = getUniquePath("test");
CloudBlockBlob blockBlob = container
.getBlockBlobReference(testPath + "/10/10/10");
blockBlob.uploadText("");
blockBlob = container.getBlockBlobReference(testPath + "/10/123/3/2/1/3");
blockBlob.uploadText("");
FileStatus[] fileStatuses = fs
.listStatus(new Path(String.format("/%s/10/", testPath)));
assertEquals(2, fileStatuses.length);
assertEquals("10", fileStatuses[0].getPath().getName());
assertTrue(fileStatuses[0].isDirectory());
assertEquals(0, fileStatuses[0].getLen());
assertEquals("123", fileStatuses[1].getPath().getName());
assertTrue(fileStatuses[1].isDirectory());
assertEquals(0, fileStatuses[1].getLen());
}
private String getBlobConnectionString() {
String connectionString;
if (isIPAddress()) {
connectionString = "DefaultEndpointsProtocol=http;BlobEndpoint=http://"
+ this.getHostName() + ":8880/" + this.getAccountName().split("\\.") [0]
+ ";AccountName=" + this.getAccountName().split("\\.")[0]
+ ";AccountKey=" + this.getAccountKey();
}
else if (this.getConfiguration().isHttpsAlwaysUsed()) {
connectionString = "DefaultEndpointsProtocol=https;BlobEndpoint=https://"
+ this.getAccountName().replaceFirst("\\.dfs\\.", ".blob.")
+ ";AccountName=" + this.getAccountName().split("\\.")[0]
+ ";AccountKey=" + this.getAccountKey();
}
else {
connectionString = "DefaultEndpointsProtocol=http;BlobEndpoint=http://"
+ this.getAccountName().replaceFirst("\\.dfs\\.", ".blob.")
+ ";AccountName=" + this.getAccountName().split("\\.")[0]
+ ";AccountKey=" + this.getAccountKey();
}
return connectionString;
}
}
|
ITestAzureBlobFileSystemBackCompat
|
java
|
apache__camel
|
core/camel-main/src/main/java/org/apache/camel/main/MainShutdownStrategy.java
|
{
"start": 933,
"end": 1029
}
|
interface ____ {
/**
* Event listener when shutting down.
*/
|
MainShutdownStrategy
|
java
|
apache__maven
|
impl/maven-core/src/main/java/org/apache/maven/plugin/MavenPluginManager.java
|
{
"start": 5179,
"end": 5670
}
|
class ____ for the specified build extensions plugin.
*
* @since 3.3.0
*/
ExtensionRealmCache.CacheRecord setupExtensionsRealm(
MavenProject project, Plugin plugin, RepositorySystemSession session) throws PluginManagerException;
/**
* Looks up the mojo for the specified mojo execution and populates its parameters from the configuration given by
* the mojo execution. The mojo/plugin descriptor associated with the mojo execution provides the
|
realm
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.