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 | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/global_variables_defaults/ConfigurationTest.java | {
"start": 1372,
"end": 5115
} | class ____ {
@Test
void applyDefaultValueOnXmlConfiguration() throws IOException {
Properties props = new Properties();
props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "true");
Reader reader = Resources
.getResourceAsReader("org/apache/ibatis/submitted/global_variables_defaults/mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, props);
Configuration configuration = factory.getConfiguration();
Assertions.assertThat(configuration.getJdbcTypeForNull()).isEqualTo(JdbcType.NULL);
Assertions.assertThat(((UnpooledDataSource) configuration.getEnvironment().getDataSource()).getUrl())
.isEqualTo("jdbc:hsqldb:mem:global_variables_defaults");
Assertions.assertThat(configuration.getDatabaseId()).isEqualTo("hsql");
Assertions
.assertThat(
((SupportClasses.CustomObjectFactory) configuration.getObjectFactory()).getProperties().getProperty("name"))
.isEqualTo("default");
}
@Test
void applyPropertyValueOnXmlConfiguration() throws IOException {
Properties props = new Properties();
props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "true");
props.setProperty("settings.jdbcTypeForNull", JdbcType.CHAR.name());
props.setProperty("db.name", "global_variables_defaults_custom");
props.setProperty("productName.hsql", "Hsql");
props.setProperty("objectFactory.name", "custom");
Reader reader = Resources
.getResourceAsReader("org/apache/ibatis/submitted/global_variables_defaults/mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, props);
Configuration configuration = factory.getConfiguration();
Assertions.assertThat(configuration.getJdbcTypeForNull()).isEqualTo(JdbcType.CHAR);
Assertions.assertThat(((UnpooledDataSource) configuration.getEnvironment().getDataSource()).getUrl())
.isEqualTo("jdbc:hsqldb:mem:global_variables_defaults_custom");
Assertions.assertThat(configuration.getDatabaseId()).isNull();
Assertions
.assertThat(
((SupportClasses.CustomObjectFactory) configuration.getObjectFactory()).getProperties().getProperty("name"))
.isEqualTo("custom");
}
@Test
void testAmbiguityCache() {
Configuration configuration = new Configuration();
configuration.addMappedStatement(
new MappedStatement.Builder(configuration, "org.apache.ibatis.submitted.DemoMapper1.selectById",
new StaticSqlSource(configuration, "select * from test where id = 1"), SqlCommandType.SELECT).build());
configuration
.addMappedStatement(new MappedStatement.Builder(configuration, "org.apache.ibatis.submitted.DemoMapper1.test",
new StaticSqlSource(configuration, "select * from test"), SqlCommandType.SELECT).build());
configuration
.addMappedStatement(new MappedStatement.Builder(configuration, "org.apache.ibatis.submitted.DemoMapper2.test",
new StaticSqlSource(configuration, "select * from test"), SqlCommandType.SELECT).build());
Assertions.assertThat(configuration.getMappedStatement("selectById")).isNotNull();
Assertions.assertThat(configuration.getMappedStatement("org.apache.ibatis.submitted.DemoMapper1.test")).isNotNull();
Assertions.assertThat(configuration.getMappedStatement("org.apache.ibatis.submitted.DemoMapper2.test")).isNotNull();
Assertions.assertThatThrownBy(() -> configuration.getMappedStatement("test"))
.isInstanceOf(IllegalArgumentException.class).hasMessage(
"test is ambiguous in Mapped Statements collection (try using the full name including the namespace, or rename one of the entries)");
}
}
| ConfigurationTest |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isAfterOrEqualTo_Test.java | {
"start": 1234,
"end": 3585
} | class ____ extends OffsetTimeAssertBaseTest {
@Test
void test_isAfterOrEqual_assertion() {
// WHEN
assertThat(AFTER).isAfterOrEqualTo(REFERENCE);
assertThat(AFTER).isAfterOrEqualTo(REFERENCE.toString());
assertThat(REFERENCE).isAfterOrEqualTo(REFERENCE);
assertThat(REFERENCE).isAfterOrEqualTo(REFERENCE.toString());
// THEN
verify_that_isAfterOrEqual_assertion_fails_and_throws_AssertionError(BEFORE, REFERENCE);
}
@Test
void test_isAfterOrEqual_assertion_error_message() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(REFERENCE).isAfterOrEqualTo(AFTER))
.withMessage(shouldBeAfterOrEqualTo(REFERENCE, AFTER).create());
}
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> {
OffsetTime actual = null;
assertThat(actual).isAfterOrEqualTo(OffsetTime.now());
}).withMessage(actualIsNull());
}
@Test
void should_fail_if_offsetTime_parameter_is_null() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThat(OffsetTime.now()).isAfterOrEqualTo((OffsetTime) null))
.withMessage("The OffsetTime to compare actual with should not be null");
}
@Test
void should_fail_if_offsetTime_as_string_parameter_is_null() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThat(OffsetTime.now()).isAfterOrEqualTo((String) null))
.withMessage("The String representing the OffsetTime to compare actual with should not be null");
}
private static void verify_that_isAfterOrEqual_assertion_fails_and_throws_AssertionError(OffsetTime timeToCheck,
OffsetTime reference) {
try {
assertThat(timeToCheck).isAfterOrEqualTo(reference);
} catch (AssertionError e) {
// AssertionError was expected, test same assertion with String based parameter
try {
assertThat(timeToCheck).isAfterOrEqualTo(reference.toString());
} catch (AssertionError e2) {
// AssertionError was expected (again)
return;
}
}
fail("Should have thrown AssertionError");
}
}
| OffsetTimeAssert_isAfterOrEqualTo_Test |
java | spring-projects__spring-framework | spring-expression/src/test/java/org/springframework/expression/spel/testresources/RecordPerson.java | {
"start": 693,
"end": 1023
} | class ____ {
private String name;
private Company company;
public RecordPerson(String name) {
this.name = name;
}
public RecordPerson(String name, Company company) {
this.name = name;
this.company = company;
}
public String name() {
return name;
}
public Company company() {
return company;
}
}
| RecordPerson |
java | redisson__redisson | redisson/src/main/java/org/redisson/connection/ReplicatedConnectionManager.java | {
"start": 1932,
"end": 2279
} | class ____ extends MasterSlaveConnectionManager {
private static final String ROLE_KEY = "role";
private final Logger log = LoggerFactory.getLogger(getClass());
private final AtomicReference<InetSocketAddress> currentMaster = new AtomicReference<>();
private volatile Timeout monitorFuture;
private | ReplicatedConnectionManager |
java | apache__dubbo | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientToServerTest.java | {
"start": 1338,
"end": 3071
} | class ____ {
protected static final String LOCALHOST = "127.0.0.1";
protected ExchangeServer server;
protected ExchangeChannel client;
protected WorldHandler handler = new WorldHandler();
protected abstract ExchangeServer newServer(int port, Replier<?> receiver) throws RemotingException;
protected abstract ExchangeChannel newClient(int port) throws RemotingException;
@BeforeEach
protected void setUp() throws Exception {
int port = NetUtils.getAvailablePort();
server = newServer(port, handler);
client = newClient(port);
}
@BeforeEach
protected void tearDown() {
try {
if (server != null) server.close();
} finally {
if (client != null) client.close();
}
}
@Test
void testFuture() throws Exception {
CompletableFuture<Object> future = client.request(new World("world"));
Hello result = (Hello) future.get();
Assertions.assertEquals("hello,world", result.getName());
}
// @Test
// public void testCallback() throws Exception {
// final Object waitter = new Object();
// client.invoke(new World("world"), new InvokeCallback<Hello>() {
// public void callback(Hello result) {
// Assertions.assertEquals("hello,world", result.getName());
// synchronized (waitter) {
// waitter.notifyAll();
// }
// }
// public void onException(Throwable exception) {
// }
// });
// synchronized (waitter) {
// waitter.wait();
// }
// }
}
| ClientToServerTest |
java | quarkusio__quarkus | independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BuiltinBean.java | {
"start": 6941,
"end": 27800
} | interface ____ {
Validator NOOP = ctx -> {
};
void validate(ValidatorContext context);
}
private static boolean cdiAndRawTypeMatches(InjectionPointInfo injectionPoint, DotName... rawTypeDotNames) {
if (injectionPoint.getKind() != InjectionPointKind.CDI) {
return false;
}
for (DotName rawTypeDotName : rawTypeDotNames) {
if (rawTypeDotName.equals(injectionPoint.getType().name())) {
return true;
}
}
return false;
}
private static void generateInstanceBytecode(GeneratorContext ctx) {
Var qualifiers = BeanGenerator.collectInjectionPointQualifiers(
ctx.beanDeployment, ctx.constructor, ctx.injectionPoint, ctx.annotationLiterals);
LocalVar parameterizedType = RuntimeTypeCreator.of(ctx.constructor).create(ctx.injectionPoint.getType());
// Note that we only collect the injection point metadata if needed, i.e. if any of the resolved beans is dependent,
// and requires InjectionPoint metadata
Set<BeanInfo> beans = ctx.beanDeployment.beanResolver.resolveBeans(ctx.injectionPoint.getRequiredType(),
ctx.injectionPoint.getRequiredQualifiers());
boolean collectMetadata = beans.stream()
.anyMatch(b -> BuiltinScope.DEPENDENT.isDeclaredBy(b) && b.requiresInjectionPointMetadata());
Expr bean;
Expr annotations;
Expr javaMember;
if (collectMetadata) {
bean = switch (ctx.injectionTarget.kind()) {
case OBSERVER -> ctx.constructor.invokeInterface(MethodDescs.SUPPLIER_GET, ctx.declaringBeanSupplier);
case BEAN -> ctx.clazzCreator.this_();
case INVOKER -> loadInvokerTargetBean(ctx.injectionTarget.asInvoker(), ctx.constructor);
default -> throw new IllegalStateException("Unsupported target info: " + ctx.injectionTarget);
};
annotations = BeanGenerator.collectInjectionPointAnnotations(
ctx.beanDeployment, ctx.constructor, ctx.injectionPoint, ctx.annotationLiterals,
ctx.injectionPointAnnotationsPredicate);
javaMember = BeanGenerator.getJavaMember(ctx.constructor, ctx.injectionPoint,
ctx.reflectionRegistration);
} else {
bean = Const.ofNull(InjectableBean.class);
annotations = collectWithCaching(ctx.beanDeployment, ctx.constructor, ctx.injectionPoint);
javaMember = Const.ofNull(Member.class);
}
Expr instanceProvider = ctx.constructor.new_(ConstructorDesc.of(InstanceProvider.class,
java.lang.reflect.Type.class, Set.class, InjectableBean.class, Set.class, Member.class,
int.class, boolean.class),
parameterizedType, qualifiers, bean, annotations, javaMember,
Const.of(ctx.injectionPoint.getPosition()), Const.of(ctx.injectionPoint.isTransient()));
Expr instanceProviderSupplier = ctx.constructor.new_(MethodDescs.FIXED_VALUE_SUPPLIER_CONSTRUCTOR, instanceProvider);
ctx.constructor.set(ctx.clazzCreator.this_().field(ctx.providerField), instanceProviderSupplier);
}
private static void generateEventBytecode(GeneratorContext ctx) {
LocalVar qualifiers = ctx.constructor.localVar("qualifiers", ctx.constructor.new_(HashSet.class));
if (!ctx.injectionPoint.getRequiredQualifiers().isEmpty()) {
// Set<Annotation> instanceProvider1Qualifiers = new HashSet<>()
// instanceProvider1Qualifiers.add(jakarta.enterprise.inject.Default.Literal.INSTANCE)
for (AnnotationInstance qualifier : ctx.injectionPoint.getRequiredQualifiers()) {
BuiltinQualifier builtinQualifier = BuiltinQualifier.of(qualifier);
if (builtinQualifier != null) {
ctx.constructor.withSet(qualifiers).add(builtinQualifier.getLiteralInstance());
} else {
// Create annotation literal first
ClassInfo qualifierClass = ctx.beanDeployment.getQualifier(qualifier.name());
ctx.constructor.withSet(qualifiers).add(
ctx.annotationLiterals.create(ctx.constructor, qualifierClass, qualifier));
}
}
}
LocalVar parameterizedType = RuntimeTypeCreator.of(ctx.constructor).create(ctx.injectionPoint.getType());
Var annotations = BeanGenerator.collectInjectionPointAnnotations(ctx.beanDeployment, ctx.constructor,
ctx.injectionPoint, ctx.annotationLiterals, ctx.injectionPointAnnotationsPredicate);
Var javaMember = BeanGenerator.getJavaMember(ctx.constructor, ctx.injectionPoint,
ctx.reflectionRegistration);
Expr bean = switch (ctx.injectionTarget.kind()) {
case OBSERVER -> ctx.constructor.invokeInterface(MethodDescs.SUPPLIER_GET, ctx.declaringBeanSupplier);
case BEAN -> ctx.clazzCreator.this_();
case INVOKER -> loadInvokerTargetBean(ctx.injectionTarget.asInvoker(), ctx.constructor);
default -> throw new IllegalStateException("Unsupported target info: " + ctx.injectionTarget);
};
Expr injectionPoint = ctx.constructor.new_(MethodDescs.INJECTION_POINT_IMPL_CONSTRUCTOR,
parameterizedType, parameterizedType, qualifiers, bean, annotations, javaMember,
Const.of(ctx.injectionPoint.getPosition()), Const.of(ctx.injectionPoint.isTransient()));
Expr eventProvider = ctx.constructor.new_(ConstructorDesc.of(EventProvider.class,
java.lang.reflect.Type.class, Set.class, InjectionPoint.class),
parameterizedType, qualifiers, injectionPoint);
Expr eventProviderSupplier = ctx.constructor.new_(MethodDescs.FIXED_VALUE_SUPPLIER_CONSTRUCTOR, eventProvider);
ctx.constructor.set(ctx.clazzCreator.this_().field(ctx.providerField), eventProviderSupplier);
}
private static void generateInjectionPointBytecode(GeneratorContext ctx) {
// this.injectionPointProvider1 = () -> new InjectionPointProvider();
Expr injectionPointProvider = ctx.constructor.new_(InjectionPointProvider.class);
Expr injectionPointProviderSupplier = ctx.constructor.new_(MethodDescs.FIXED_VALUE_SUPPLIER_CONSTRUCTOR,
injectionPointProvider);
ctx.constructor.set(ctx.clazzCreator.this_().field(ctx.providerField), injectionPointProviderSupplier);
}
private static void generateBeanBytecode(GeneratorContext ctx) {
// this.beanProvider1 = () -> new BeanMetadataProvider<>();
Expr beanProvider = ctx.constructor.new_(ConstructorDesc.of(BeanMetadataProvider.class, String.class),
Const.of(ctx.injectionTarget.asBean().getIdentifier()));
Expr beanProviderSupplier = ctx.constructor.new_(MethodDescs.FIXED_VALUE_SUPPLIER_CONSTRUCTOR, beanProvider);
ctx.constructor.set(ctx.clazzCreator.this_().field(ctx.providerField), beanProviderSupplier);
}
private static void generateInterceptedDecoratedBeanBytecode(GeneratorContext ctx) {
Expr beanMetadataProvider = ctx.constructor.new_(InterceptedDecoratedBeanMetadataProvider.class);
Expr beanMetadataProviderSupplier = ctx.constructor.new_(
MethodDescs.FIXED_VALUE_SUPPLIER_CONSTRUCTOR, beanMetadataProvider);
ctx.constructor.set(ctx.clazzCreator.this_().field(ctx.providerField), beanMetadataProviderSupplier);
}
private static void generateBeanManagerBytecode(GeneratorContext ctx) {
Expr beanManagerProvider = ctx.constructor.new_(BeanManagerProvider.class);
Expr beanManagerProviderSupplier = ctx.constructor.new_(MethodDescs.FIXED_VALUE_SUPPLIER_CONSTRUCTOR,
beanManagerProvider);
ctx.constructor.set(ctx.clazzCreator.this_().field(ctx.providerField), beanManagerProviderSupplier);
}
private static void generateResourceBytecode(GeneratorContext ctx) {
LocalVar annotations = ctx.constructor.localVar("annotations", ctx.constructor.new_(HashSet.class));
// For a resource field the required qualifiers contain all runtime-retained annotations
// declared on the field (hence we need to check if their classes are available)
if (!ctx.injectionPoint.getRequiredQualifiers().isEmpty()) {
for (AnnotationInstance annotation : ctx.injectionPoint.getRequiredQualifiers()) {
ClassInfo annotationClass = getClassByName(ctx.beanDeployment.getBeanArchiveIndex(), annotation.name());
if (annotationClass == null) {
continue;
}
ctx.constructor.withSet(annotations).add(
ctx.annotationLiterals.create(ctx.constructor, annotationClass, annotation));
}
}
LocalVar parameterizedType = RuntimeTypeCreator.of(ctx.constructor).create(ctx.injectionPoint.getType());
Expr resourceProvider = ctx.constructor.new_(ConstructorDesc.of(ResourceProvider.class,
java.lang.reflect.Type.class, Set.class), parameterizedType, annotations);
Expr resourceProviderSupplier = ctx.constructor.new_(MethodDescs.FIXED_VALUE_SUPPLIER_CONSTRUCTOR, resourceProvider);
ctx.constructor.set(ctx.clazzCreator.this_().field(ctx.providerField), resourceProviderSupplier);
}
private static void generateListBytecode(GeneratorContext ctx) {
// Register injection point for reflection
InjectionPointInfo injectionPoint = ctx.injectionPoint;
if (injectionPoint.isField()) {
ctx.reflectionRegistration.registerField(injectionPoint.getAnnotationTarget().asField());
} else if (injectionPoint.isParam()) {
ctx.reflectionRegistration.registerMethod(injectionPoint.getAnnotationTarget().asMethodParameter().method());
}
LocalVar injectionPointType = RuntimeTypeCreator.of(ctx.constructor).create(ctx.injectionPoint.getType());
// List<T> or List<InstanceHandle<T>
LocalVar requiredType;
Const usesInstance;
Type type = ctx.injectionPoint.getType().asParameterizedType().arguments().get(0);
if (type.name().equals(DotNames.INSTANCE_HANDLE)) {
requiredType = RuntimeTypeCreator.of(ctx.constructor).create(type.asParameterizedType().arguments().get(0));
usesInstance = Const.of(true);
} else {
requiredType = RuntimeTypeCreator.of(ctx.constructor).create(type);
usesInstance = Const.of(false);
}
Var qualifiers = BeanGenerator.collectInjectionPointQualifiers(ctx.beanDeployment, ctx.constructor,
ctx.injectionPoint, ctx.annotationLiterals);
// Note that we only collect the injection point metadata if needed, i.e. if any of the resolved beans is dependent,
// and requires InjectionPoint metadata
Set<BeanInfo> beans = ctx.beanDeployment.beanResolver.resolveBeans(
type.name().equals(DotNames.INSTANCE_HANDLE) ? type.asParameterizedType().arguments().get(0) : type,
ctx.injectionPoint.getRequiredQualifiers()
.stream()
.filter(a -> !a.name().equals(DotNames.ALL))
.collect(Collectors.toSet()));
boolean collectMetadata = beans.stream()
.anyMatch(b -> BuiltinScope.DEPENDENT.isDeclaredBy(b) && b.requiresInjectionPointMetadata());
Expr bean;
Expr annotations;
Expr javaMember;
if (collectMetadata) {
bean = switch (ctx.injectionTarget.kind()) {
case OBSERVER -> ctx.constructor.invokeInterface(MethodDescs.SUPPLIER_GET, ctx.declaringBeanSupplier);
case BEAN -> ctx.clazzCreator.this_();
case INVOKER -> loadInvokerTargetBean(ctx.injectionTarget.asInvoker(), ctx.constructor);
default -> throw new IllegalStateException("Unsupported target info: " + ctx.injectionTarget);
};
annotations = BeanGenerator.collectInjectionPointAnnotations(ctx.beanDeployment, ctx.constructor,
ctx.injectionPoint, ctx.annotationLiterals, ctx.injectionPointAnnotationsPredicate);
javaMember = BeanGenerator.getJavaMember(ctx.constructor, ctx.injectionPoint,
ctx.reflectionRegistration);
} else {
bean = Const.ofNull(InjectableBean.class);
annotations = Const.ofNull(Set.class);
javaMember = Const.ofNull(Member.class);
}
Expr listProvider = ctx.constructor.new_(ConstructorDesc.of(ListProvider.class, java.lang.reflect.Type.class,
java.lang.reflect.Type.class, Set.class, InjectableBean.class, Set.class, Member.class, int.class,
boolean.class, boolean.class), requiredType, injectionPointType, qualifiers, bean, annotations,
javaMember, Const.of(ctx.injectionPoint.getPosition()), Const.of(ctx.injectionPoint.isTransient()),
usesInstance);
Expr listProviderSupplier = ctx.constructor.new_(MethodDescs.FIXED_VALUE_SUPPLIER_CONSTRUCTOR, listProvider);
ctx.constructor.set(ctx.clazzCreator.this_().field(ctx.providerField), listProviderSupplier);
}
private static void generateInterceptionProxyBytecode(GeneratorContext ctx) {
BeanInfo bean = ctx.injectionTarget.asBean();
String name = InterceptionProxyGenerator.interceptionProxyProviderName(bean);
Expr supplier = ctx.constructor.new_(ConstructorDesc.of(ClassDesc.of(name)));
ctx.constructor.set(ctx.clazzCreator.this_().field(ctx.providerField), supplier);
}
private static Expr loadInvokerTargetBean(InvokerInfo invoker, BlockCreator bc) {
return bc.invokeInterface(MethodDescs.ARC_CONTAINER_BEAN, bc.invokeStatic(MethodDescs.ARC_REQUIRE_CONTAINER),
Const.of(invoker.targetBean.getIdentifier()));
}
private static Expr collectWithCaching(BeanDeployment beanDeployment, BlockCreator bc,
InjectionPointInfo injectionPoint) {
AnnotationTarget annotationTarget = injectionPoint.isParam()
? injectionPoint.getAnnotationTarget().asMethodParameter().method()
: injectionPoint.getAnnotationTarget();
Expr annotations;
if (!injectionPoint.isSynthetic()
&& Annotations.contains(beanDeployment.getAnnotations(annotationTarget), DotNames.WITH_CACHING)) {
annotations = bc.setOf(Expr.staticField(FieldDesc.of(WithCaching.Literal.class, "INSTANCE")));
} else {
annotations = bc.setOf();
}
return annotations;
}
private static void validateInstance(ValidatorContext ctx) {
if (ctx.injectionPoint.getType().kind() != Kind.PARAMETERIZED_TYPE) {
ctx.errors.accept(new DefinitionException(
"An injection point of raw type jakarta.enterprise.inject.Instance is defined: "
+ ctx.injectionPoint.getTargetInfo()));
} else if (ctx.injectionPoint.getRequiredType().kind() == Kind.WILDCARD_TYPE) {
ctx.errors.accept(new DefinitionException(
"Wildcard is not a legal type argument for jakarta.enterprise.inject.Instance: "
+ ctx.injectionPoint.getTargetInfo()));
} else if (ctx.injectionPoint.getRequiredType().kind() == Kind.TYPE_VARIABLE) {
ctx.errors.accept(new DefinitionException(
"Type variable is not a legal type argument for jakarta.enterprise.inject.Instance: "
+ ctx.injectionPoint.getTargetInfo()));
}
}
private static void validateList(ValidatorContext ctx) {
if (ctx.injectionPoint.getType().kind() != Kind.PARAMETERIZED_TYPE) {
ctx.errors.accept(new DefinitionException(
"An injection point of raw type is defined: " + ctx.injectionPoint.getTargetInfo()));
} else {
// Note that at this point we can be sure that the required type is List<>
Type typeParam = ctx.injectionPoint.getType().asParameterizedType().arguments().get(0);
if (typeParam.kind() == Type.Kind.WILDCARD_TYPE) {
if (ctx.injectionPoint.isSynthetic()) {
ctx.errors.accept(new DefinitionException(
"Wildcard is not a legal type argument for a synthetic @All List<?> injection point used in: "
+ ctx.injectionTarget.toString()));
return;
}
ClassInfo declaringClass;
if (ctx.injectionPoint.isField()) {
declaringClass = ctx.injectionPoint.getAnnotationTarget().asField().declaringClass();
} else {
declaringClass = ctx.injectionPoint.getAnnotationTarget().asMethodParameter().method().declaringClass();
}
if (isKotlinClass(declaringClass)) {
ctx.errors.accept(new DefinitionException(
"kotlin.collections.List cannot be used together with the @All qualifier, please use MutableList or java.util.List instead: "
+ ctx.injectionPoint.getTargetInfo()));
} else {
ctx.errors.accept(new DefinitionException(
"Wildcard is not a legal type argument for: " + ctx.injectionPoint.getTargetInfo()));
}
} else if (typeParam.kind() == Type.Kind.TYPE_VARIABLE) {
ctx.errors.accept(new DefinitionException(
"Type variable is not a legal type argument for: " + ctx.injectionPoint.getTargetInfo()));
}
}
}
private static void validateInjectionPoint(ValidatorContext ctx) {
if (ctx.injectionTarget.kind() != TargetKind.BEAN
|| !BuiltinScope.DEPENDENT.is(ctx.injectionTarget.asBean().getScope())) {
String msg = ctx.injectionPoint.getTargetInfo();
if (msg.isBlank()) {
msg = ctx.injectionTarget.toString();
}
ctx.errors.accept(new DefinitionException(
"Only @Dependent beans can access metadata about an injection point: " + msg));
}
}
private static void validateBean(ValidatorContext ctx) {
if (ctx.injectionTarget.kind() != InjectionTargetInfo.TargetKind.BEAN) {
ctx.errors.accept(new DefinitionException("Only beans can access bean metadata"));
}
}
private static void validateInterceptedBean(ValidatorContext ctx) {
if (ctx.injectionTarget.kind() != InjectionTargetInfo.TargetKind.BEAN
|| !ctx.injectionTarget.asBean().isInterceptor()) {
ctx.errors.accept(new DefinitionException("Only interceptors can access intercepted bean metadata"));
}
}
private static void validateDecoratedBean(ValidatorContext ctx) {
if (ctx.injectionTarget.kind() != InjectionTargetInfo.TargetKind.BEAN
|| !ctx.injectionTarget.asBean().isDecorator()) {
ctx.errors.accept(new DefinitionException("Only decorators can access decorated bean metadata"));
}
}
private static void validateEventMetadata(ValidatorContext ctx) {
if (ctx.injectionTarget.kind() != TargetKind.OBSERVER) {
ctx.errors.accept(new DefinitionException(
"EventMetadata can be only injected into an observer method: " + ctx.injectionPoint.getTargetInfo()));
}
}
private static void validateInterceptionProxy(ValidatorContext ctx) {
if (ctx.injectionTarget.kind() != TargetKind.BEAN
|| (!ctx.injectionTarget.asBean().isProducerMethod() && !ctx.injectionTarget.asBean().isSynthetic())
|| ctx.injectionTarget.asBean().getInterceptionProxy() == null) {
ctx.errors.accept(new DefinitionException(
"InterceptionProxy can only be injected into a producer method or a synthetic bean"));
}
if (ctx.injectionPoint.getType().kind() != Kind.PARAMETERIZED_TYPE) {
ctx.errors.accept(new DefinitionException("InterceptionProxy must be a parameterized type"));
}
Type interceptionProxyType = ctx.injectionPoint.getType().asParameterizedType().arguments().get(0);
if (interceptionProxyType.kind() != Kind.CLASS && interceptionProxyType.kind() != Kind.PARAMETERIZED_TYPE) {
ctx.errors.accept(new DefinitionException(
"Type argument of InterceptionProxy may only be a | Validator |
java | elastic__elasticsearch | libs/core/src/main/java/org/elasticsearch/core/XmlUtils.java | {
"start": 7936,
"end": 8861
} | class ____ implements org.xml.sax.ErrorHandler {
/**
* Enabling schema validation with `setValidating(true)` in our
* DocumentBuilderFactory requires that we provide our own
* ErrorHandler implementation
*
* @throws SAXException If the document we attempt to parse is not valid according to the specified schema.
*/
@Override
public void warning(SAXParseException e) throws SAXException {
LOGGER.debug("XML Parser error ", e);
throw e;
}
@Override
public void error(SAXParseException e) throws SAXException {
LOGGER.debug("XML Parser error ", e);
throw e;
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
LOGGER.debug("XML Parser error ", e);
throw e;
}
}
private static | ErrorHandler |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/field/mapinjection/Cat.java | {
"start": 101,
"end": 133
} | class ____ implements Animal {
}
| Cat |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/TrainedModelCacheInfoResponseTests.java | {
"start": 921,
"end": 2529
} | class ____ extends AbstractWireSerializingTestCase<TrainedModelCacheInfoAction.Response> {
@Override
protected Writeable.Reader<TrainedModelCacheInfoAction.Response> instanceReader() {
return TrainedModelCacheInfoAction.Response::new;
}
@Override
protected TrainedModelCacheInfoAction.Response createTestInstance() {
int numNodes = randomIntBetween(1, 20);
List<CacheInfo> nodes = new ArrayList<>(numNodes);
for (int i = 0; i < numNodes; ++i) {
DiscoveryNode node = DiscoveryNodeUtils.create(
randomAlphaOfLength(20),
new TransportAddress(InetAddress.getLoopbackAddress(), 9200 + i)
);
nodes.add(CacheInfoTests.createTestInstance(node));
}
int numFailures = randomIntBetween(0, 5);
List<FailedNodeException> failures = (numFailures > 0) ? new ArrayList<>(numFailures) : List.of();
for (int i = 0; i < numFailures; ++i) {
failures.add(
new FailedNodeException(
randomAlphaOfLength(20),
randomAlphaOfLength(50),
new ElasticsearchException(randomAlphaOfLength(30))
)
);
}
return new TrainedModelCacheInfoAction.Response(ClusterName.DEFAULT, nodes, failures);
}
@Override
protected TrainedModelCacheInfoAction.Response mutateInstance(TrainedModelCacheInfoAction.Response instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
}
| TrainedModelCacheInfoResponseTests |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/plugins/scanners/StablePluginsRegistryTests.java | {
"start": 793,
"end": 2913
} | class ____ extends ESTestCase {
public void testAddingNamedComponentsFromMultiplePlugins() {
NamedComponentReader scanner = Mockito.mock(NamedComponentReader.class);
ClassLoader loader = Mockito.mock(ClassLoader.class);
ClassLoader loader2 = Mockito.mock(ClassLoader.class);
NameToPluginInfo pluginInfo1 = new NameToPluginInfo().put(
"namedComponentName1",
new PluginInfo("namedComponentName1", "XXClassName", loader)
);
NameToPluginInfo pluginInfo2 = new NameToPluginInfo().put(
"namedComponentName2",
new PluginInfo("namedComponentName2", "YYClassName", loader)
);
NameToPluginInfo pluginInfo3 = new NameToPluginInfo().put(
"namedComponentName3",
new PluginInfo("namedComponentName3", "ZZClassName", loader2)
);
Mockito.when(scanner.findNamedComponents(any(PluginBundle.class), any(ClassLoader.class)))
.thenReturn(Map.of("extensibleInterfaceName", pluginInfo1))
.thenReturn(Map.of("extensibleInterfaceName", pluginInfo2))
.thenReturn(Map.of("extensibleInterfaceName2", pluginInfo3));
StablePluginsRegistry registry = new StablePluginsRegistry(scanner, new HashMap<>());
registry.scanBundleForStablePlugins(Mockito.mock(PluginBundle.class), loader); // bundle 1
registry.scanBundleForStablePlugins(Mockito.mock(PluginBundle.class), loader); // bundle 2
registry.scanBundleForStablePlugins(Mockito.mock(PluginBundle.class), loader2); // bundle 3
assertThat(
registry.getPluginInfosForExtensible("extensibleInterfaceName"),
containsInAnyOrder(
new PluginInfo("namedComponentName1", "XXClassName", loader),
new PluginInfo("namedComponentName2", "YYClassName", loader)
)
);
assertThat(
registry.getPluginInfosForExtensible("extensibleInterfaceName2"),
containsInAnyOrder(new PluginInfo("namedComponentName3", "ZZClassName", loader2))
);
}
}
| StablePluginsRegistryTests |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/dataframe/stats/ProgressTracker.java | {
"start": 729,
"end": 5059
} | class ____ {
public static final String REINDEXING = "reindexing";
public static final String LOADING_DATA = "loading_data";
public static final String WRITING_RESULTS = "writing_results";
public static final String INFERENCE = "inference";
private final String[] phasesInOrder;
private final Map<String, Integer> progressPercentPerPhase;
public static ProgressTracker fromZeroes(List<String> analysisProgressPhases, boolean hasInferencePhase) {
List<PhaseProgress> phases = new ArrayList<>(3 + analysisProgressPhases.size() + (hasInferencePhase ? 1 : 0));
phases.add(new PhaseProgress(REINDEXING, 0));
phases.add(new PhaseProgress(LOADING_DATA, 0));
analysisProgressPhases.forEach(analysisPhase -> phases.add(new PhaseProgress(analysisPhase, 0)));
phases.add(new PhaseProgress(WRITING_RESULTS, 0));
if (hasInferencePhase) {
phases.add(new PhaseProgress(INFERENCE, 0));
}
return new ProgressTracker(phases);
}
public ProgressTracker(List<PhaseProgress> phaseProgresses) {
phasesInOrder = new String[phaseProgresses.size()];
progressPercentPerPhase = new ConcurrentHashMap<>();
for (int i = 0; i < phaseProgresses.size(); i++) {
PhaseProgress phaseProgress = phaseProgresses.get(i);
phasesInOrder[i] = phaseProgress.getPhase();
progressPercentPerPhase.put(phaseProgress.getPhase(), phaseProgress.getProgressPercent());
}
assert progressPercentPerPhase.containsKey(REINDEXING);
assert progressPercentPerPhase.containsKey(LOADING_DATA);
assert progressPercentPerPhase.containsKey(WRITING_RESULTS);
// If there is inference it should be the last phase otherwise there
// are assumptions that do not hold.
assert progressPercentPerPhase.containsKey(INFERENCE) == false || INFERENCE.equals(phasesInOrder[phasesInOrder.length - 1]);
}
public void updateReindexingProgress(int progressPercent) {
updatePhase(REINDEXING, progressPercent);
}
public int getReindexingProgressPercent() {
return progressPercentPerPhase.get(REINDEXING);
}
public void updateLoadingDataProgress(int progressPercent) {
updatePhase(LOADING_DATA, progressPercent);
}
public int getLoadingDataProgressPercent() {
return progressPercentPerPhase.get(LOADING_DATA);
}
public void updateWritingResultsProgress(int progressPercent) {
updatePhase(WRITING_RESULTS, progressPercent);
}
public int getWritingResultsProgressPercent() {
return progressPercentPerPhase.get(WRITING_RESULTS);
}
public void updateInferenceProgress(int progressPercent) {
updatePhase(INFERENCE, progressPercent);
}
public int getInferenceProgressPercent() {
return progressPercentPerPhase.getOrDefault(INFERENCE, 0);
}
public void updatePhase(PhaseProgress phase) {
updatePhase(phase.getPhase(), phase.getProgressPercent());
}
private void updatePhase(String phase, int progress) {
progressPercentPerPhase.computeIfPresent(phase, (k, v) -> Math.max(v, progress));
}
/**
* Resets progress to reflect all phases are complete except for inference
* which is set to zero.
*/
public void resetForInference() {
for (Map.Entry<String, Integer> phaseProgress : progressPercentPerPhase.entrySet()) {
if (phaseProgress.getKey().equals(INFERENCE)) {
progressPercentPerPhase.put(phaseProgress.getKey(), 0);
} else {
progressPercentPerPhase.put(phaseProgress.getKey(), 100);
}
}
}
/**
* Returns whether all phases before inference are complete
*/
public boolean areAllPhasesExceptInferenceComplete() {
for (Map.Entry<String, Integer> phaseProgress : progressPercentPerPhase.entrySet()) {
if (phaseProgress.getKey().equals(INFERENCE) == false && phaseProgress.getValue() < 100) {
return false;
}
}
return true;
}
public List<PhaseProgress> report() {
return Arrays.stream(phasesInOrder).map(phase -> new PhaseProgress(phase, progressPercentPerPhase.get(phase))).toList();
}
}
| ProgressTracker |
java | elastic__elasticsearch | x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathFunctionProcessorTests.java | {
"start": 669,
"end": 3552
} | class ____ extends AbstractWireSerializingTestCase<MathProcessor> {
public static MathProcessor randomMathFunctionProcessor() {
return new MathProcessor(randomFrom(MathOperation.values()));
}
@Override
protected MathProcessor createTestInstance() {
return randomMathFunctionProcessor();
}
@Override
protected Reader<MathProcessor> instanceReader() {
return MathProcessor::new;
}
@Override
protected MathProcessor mutateInstance(MathProcessor instance) {
return new MathProcessor(randomValueOtherThan(instance.processor(), () -> randomFrom(MathOperation.values())));
}
public void testApply() {
MathProcessor proc = new MathProcessor(MathOperation.E);
assertEquals(Math.E, proc.process(null));
assertEquals(Math.E, proc.process(Math.PI));
proc = new MathProcessor(MathOperation.SQRT);
assertEquals(2.0, (double) proc.process(4), 0);
assertEquals(3.0, (double) proc.process(9d), 0);
assertEquals(1.77, (double) proc.process(3.14), 0.01);
}
public void testNumberCheck() {
MathProcessor proc = new MathProcessor(MathOperation.E);
SqlIllegalArgumentException siae = expectThrows(SqlIllegalArgumentException.class, () -> proc.process("string"));
assertEquals("A number is required; received [string]", siae.getMessage());
}
public void testRandom() {
MathProcessor proc = new MathProcessor(MathOperation.RANDOM);
assertNull(proc.process(null));
assertNotNull(proc.process(randomLong()));
}
public void testFloor() {
MathProcessor proc = new MathProcessor(MathOperation.FLOOR);
assertNull(proc.process(null));
assertNotNull(proc.process(randomLong()));
assertEquals(3.0, proc.process(3.3));
assertEquals(3.0, proc.process(3.9));
assertEquals(-13.0, proc.process(-12.1));
}
public void testCeil() {
MathProcessor proc = new MathProcessor(MathOperation.CEIL);
assertNull(proc.process(null));
assertNotNull(proc.process(randomLong()));
assertEquals(4.0, proc.process(3.3));
assertEquals(4.0, proc.process(3.9));
assertEquals(-12.0, proc.process(-12.1));
}
public void testUnsignedLongAbs() {
MathProcessor proc = new MathProcessor(MathOperation.ABS);
BigInteger bi = randomBigInteger();
assertEquals(bi, proc.process(bi));
}
public void testUnsignedLongSign() {
MathProcessor proc = new MathProcessor(MathOperation.SIGN);
for (BigInteger bi : Arrays.asList(BigInteger.valueOf(randomNonNegativeLong()), BigInteger.ZERO)) {
Object val = proc.process(bi);
assertEquals(bi.intValue() == 0 ? 0 : 1, val);
assertTrue(val instanceof Integer);
}
}
}
| MathFunctionProcessorTests |
java | spring-projects__spring-security | config/src/main/java/org/springframework/security/config/annotation/rsocket/RSocketSecurity.java | {
"start": 11103,
"end": 11976
} | class ____ {
private ReactiveAuthenticationManager authenticationManager;
private BasicAuthenticationSpec() {
}
public BasicAuthenticationSpec authenticationManager(ReactiveAuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
return this;
}
private ReactiveAuthenticationManager getAuthenticationManager() {
if (this.authenticationManager == null) {
return RSocketSecurity.this.authenticationManager;
}
return this.authenticationManager;
}
protected AuthenticationPayloadInterceptor build() {
ReactiveAuthenticationManager manager = getAuthenticationManager();
AuthenticationPayloadInterceptor result = new AuthenticationPayloadInterceptor(manager);
result.setOrder(PayloadInterceptorOrder.AUTHENTICATION.getOrder());
return result;
}
}
public final | BasicAuthenticationSpec |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/state/ManualWindowSpeedITCase.java | {
"start": 9868,
"end": 10930
} | class ____
implements ParallelSourceFunction<Tuple2<String, Integer>> {
private static final long serialVersionUID = 1L;
private int numKeys;
private volatile boolean running = true;
public InfiniteTupleSource(int numKeys) {
this.numKeys = numKeys;
}
@Override
public void run(SourceContext<Tuple2<String, Integer>> out) throws Exception {
Random random = new Random(42);
while (running) {
Tuple2<String, Integer> tuple =
new Tuple2<String, Integer>("Tuple " + (random.nextInt(numKeys)), 1);
out.collect(tuple);
}
}
@Override
public void cancel() {
this.running = false;
}
}
/**
* This {@link WatermarkStrategy} assigns the current system time as the event-time timestamp.
* In a real use case you should use proper timestamps and an appropriate {@link
* WatermarkStrategy}.
*/
private static | InfiniteTupleSource |
java | junit-team__junit5 | junit-platform-engine/src/main/java/org/junit/platform/engine/support/hierarchical/WorkerThreadPoolHierarchicalTestExecutorService.java | {
"start": 21660,
"end": 21725
} | enum ____ {
NON_BLOCKING, BLOCKING
}
private static | BlockingMode |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/rest/validate/RestValidateDetectorAction.java | {
"start": 941,
"end": 1714
} | class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(POST, BASE_PATH + "anomaly_detectors/_validate/detector"));
}
@Override
public String getName() {
return "ml_validate_detector_action";
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException {
XContentParser parser = restRequest.contentOrSourceParamParser();
ValidateDetectorAction.Request validateDetectorRequest = ValidateDetectorAction.Request.parseRequest(parser);
return channel -> client.execute(ValidateDetectorAction.INSTANCE, validateDetectorRequest, new RestToXContentListener<>(channel));
}
}
| RestValidateDetectorAction |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/core/publisher/ParallelMergeSequentialTest.java | {
"start": 1077,
"end": 4552
} | class ____ {
@Test
public void scanOperator() {
ParallelFlux<Integer> source = Flux.just(500, 300).parallel(10);
ParallelMergeSequential<Integer> test = new ParallelMergeSequential<>(source, 123, Queues.one());
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(source);
assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(123);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
}
@Test
public void scanMainSubscriber() {
LambdaSubscriber<Integer> subscriber = new LambdaSubscriber<>(null, e -> { }, null,
s -> s.request(2));
MergeSequentialMain<Integer>
test = new MergeSequentialMain<>(subscriber, 4, 123, Queues.small());
subscriber.onSubscribe(test);
assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(subscriber);
assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(2);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
assertThat(test.scan(Scannable.Attr.ERROR)).isNull();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
test.cancel();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
}
@Test
public void scanMainSubscriberDoneAfterNComplete() {
LambdaSubscriber<Integer> subscriber = new LambdaSubscriber<>(null, e -> { }, null,
s -> s.request(2));
int n = 4;
MergeSequentialMain<Integer>
test = new MergeSequentialMain<>(subscriber, n, 123, Queues.small());
subscriber.onSubscribe(test);
for (int i = 0; i < n; i++) {
assertThat(test.scan(Scannable.Attr.TERMINATED)).as("complete %d", i)
.isFalse();
test.onComplete();
}
assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();
}
@Test
public void scanMainSubscriberError() {
LambdaSubscriber<Integer> subscriber = new LambdaSubscriber<>(null, e -> { }, null,
s -> s.request(2));
MergeSequentialMain<Integer>
test = new MergeSequentialMain<>(subscriber, 4, 123, Queues.small());
subscriber.onSubscribe(test);
assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
assertThat(test.scan(Scannable.Attr.ERROR)).isNull();
test.onError(new IllegalStateException("boom"));
assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
assertThat(test.scan(Scannable.Attr.ERROR)).hasMessage("boom");
}
@Test
public void scanInnerSubscriber() {
CoreSubscriber<Integer>
mainActual = new LambdaSubscriber<>(null, e -> { }, null, null);
MergeSequentialMain<Integer> main = new MergeSequentialMain<>(mainActual, 2, 123, Queues.small());
MergeSequentialInner<Integer> test = new MergeSequentialInner<>(main, 456);
Subscription subscription = Operators.emptySubscription();
test.onSubscribe(subscription);
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(subscription);
assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(main);
assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(456);
assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(0);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
assertThat(test.scan(Scannable.Attr.ERROR)).isNull();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
test.cancel();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
}
}
| ParallelMergeSequentialTest |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/lib/chain/TestMapReduceChain.java | {
"start": 6512,
"end": 6609
} | class ____ extends IDMap {
public FMap() {
super("F", "X");
}
}
public static | FMap |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/TestingCoordinationRequestHandler.java | {
"start": 1713,
"end": 2412
} | class ____ implements OperatorCoordinator.Provider {
private static final long serialVersionUID = 1L;
private final OperatorID operatorId;
public Provider(OperatorID operatorId) {
this.operatorId = operatorId;
}
@Override
public OperatorID getOperatorId() {
return operatorId;
}
@Override
public OperatorCoordinator create(Context context) {
return new TestingCoordinationRequestHandler(context);
}
}
/**
* A {@link CoordinationRequest} that a {@link TestingCoordinationRequestHandler} receives.
*
* @param <T> payload type
*/
public static | Provider |
java | playframework__playframework | documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/dependencyinjection/controllers/HomeController.java | {
"start": 268,
"end": 359
} | class ____ extends Controller {
public Result index() {
return ok();
}
}
| HomeController |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/filter/FilterWithILikeTest.java | {
"start": 2013,
"end": 2328
} | class ____ {
@Id
private Integer id;
@Column(name = "NAME")
private String name;
public TestEntity() {
}
public TestEntity(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
}
}
| TestEntity |
java | quarkusio__quarkus | integration-tests/spring-data-jpa/src/main/java/io/quarkus/it/spring/data/jpa/complex/ParentBase.java | {
"start": 119,
"end": 1217
} | class ____ {
private String name;
private String detail;
private int age;
private float test;
private TestEnum testEnum;
public ParentBase(String name, String detail, int age, float test, TestEnum testEnum) {
this.name = name;
this.detail = detail;
this.age = age;
this.test = test;
this.testEnum = testEnum;
}
public ParentBase() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getTest() {
return test;
}
public void setTest(float test) {
this.test = test;
}
public TestEnum getTestEnum() {
return testEnum;
}
public void setTestEnum(TestEnum testEnum) {
this.testEnum = testEnum;
}
}
| ParentBase |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/wall/spi/SQLiteWallVisitor.java | {
"start": 906,
"end": 1246
} | class ____ extends WallVisitorBase implements WallVisitor, MySqlASTVisitor {
public SQLiteWallVisitor(WallProvider provider) {
super(provider);
}
@Override
public DbType getDbType() {
return DbType.postgresql;
}
public boolean visit(SQLIdentifierExpr x) {
return true;
}
}
| SQLiteWallVisitor |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/future/FutureAssert_isNotCancelled_Test.java | {
"start": 1007,
"end": 1627
} | class ____ {
@Test
void should_pass_if_actual_is_not_cancelled() {
// GIVEN
Future<?> actual = mock(Future.class);
// WHEN
when(actual.isCancelled()).thenReturn(false);
// THEN
then(actual).isNotCancelled();
}
@Test
void should_fail_if_actual_is_cancelled() {
// GIVEN
Future<?> actual = mock(Future.class);
when(actual.isCancelled()).thenReturn(true);
// WHEN
var assertionError = expectAssertionError(() -> assertThat(actual).isNotCancelled());
// THEN
then(assertionError).hasMessageContaining("not to be cancelled");
}
}
| FutureAssert_isNotCancelled_Test |
java | quarkusio__quarkus | integration-tests/test-extension/tests/src/test/java/io/quarkus/it/extension/it/ParameterDevModeIT.java | {
"start": 2305,
"end": 3126
} | class ____ class 'io.quarkus.test.config.QuarkusClassOrderer' set via the 'junit.jupiter.testclass.order.default' configuration parameter. Falling back to default behavior.: java.lang.ClassNotFoundException: io.quarkus.test.config.QuarkusClassOrderer
// at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
// at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
// at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:526)
// These are hard to test directly for but are not wanted
String logs = running.log();
assertThat(logs).doesNotContainIgnoringCase("java.lang.ClassNotFoundException")
.doesNotContainIgnoringCase(QuarkusClassOrderer.class.getName());
}
}
| orderer |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/jmx/export/naming/MetadataNamingStrategy.java | {
"start": 2947,
"end": 5352
} | interface ____ use
* when reading the source-level metadata.
*/
public void setAttributeSource(JmxAttributeSource attributeSource) {
Assert.notNull(attributeSource, "JmxAttributeSource must not be null");
this.attributeSource = attributeSource;
}
/**
* Specify the default domain to be used for generating ObjectNames
* when no source-level metadata has been specified.
* <p>The default is to use the domain specified in the bean name
* (if the bean name follows the JMX ObjectName syntax); else,
* the package name of the managed bean class.
*/
public void setDefaultDomain(String defaultDomain) {
this.defaultDomain = defaultDomain;
}
@Override
public void afterPropertiesSet() {
if (this.attributeSource == null) {
throw new IllegalArgumentException("Property 'attributeSource' is required");
}
}
/**
* Reads the {@code ObjectName} from the source-level metadata associated
* with the managed resource's {@code Class}.
*/
@Override
public ObjectName getObjectName(Object managedBean, @Nullable String beanKey) throws MalformedObjectNameException {
Assert.state(this.attributeSource != null, "No JmxAttributeSource set");
Class<?> managedClass = AopUtils.getTargetClass(managedBean);
ManagedResource mr = this.attributeSource.getManagedResource(managedClass);
// Check that an object name has been specified.
if (mr != null && StringUtils.hasText(mr.getObjectName())) {
return ObjectNameManager.getInstance(mr.getObjectName());
}
else {
Assert.state(beanKey != null, "No ManagedResource attribute and no bean key specified");
try {
return ObjectNameManager.getInstance(beanKey);
}
catch (MalformedObjectNameException ex) {
String domain = this.defaultDomain;
if (domain == null) {
domain = ClassUtils.getPackageName(managedClass);
}
Hashtable<String, String> properties = new Hashtable<>();
properties.put("type", ClassUtils.getShortName(managedClass));
properties.put("name", quoteIfNecessary(beanKey));
return ObjectNameManager.getInstance(domain, properties);
}
}
}
private static String quoteIfNecessary(String value) {
return shouldQuote(value) ? ObjectName.quote(value) : value;
}
private static boolean shouldQuote(String value) {
for (char quotableChar : QUOTABLE_CHARS) {
if (value.indexOf(quotableChar) != -1) {
return true;
}
}
return false;
}
}
| to |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/UseBindsTest.java | {
"start": 5106,
"end": 5489
} | class ____ {",
" @Binds abstract Random provideRandom(SecureRandom impl);",
"}")
.doTest();
}
@Test
public void multipleBindsMethods() {
testHelper
.addInputLines(
"in/Test.java",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
" | Test |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/RexLiteralUtil.java | {
"start": 3424,
"end": 7920
} | class ____ value does not match the expectations
* of valueType
*/
public static Object toFlinkInternalValue(Comparable<?> value, LogicalType valueType) {
if (value == null) {
return null;
}
switch (valueType.getTypeRoot()) {
case CHAR:
case VARCHAR:
if (value instanceof NlsString) {
return BinaryStringData.fromString(((NlsString) value).getValue());
}
if (value instanceof String) {
return BinaryStringData.fromString((String) value);
}
break;
case BOOLEAN:
if (value instanceof Boolean) {
return value;
}
break;
case BINARY:
case VARBINARY:
if (value instanceof ByteString) {
return ((ByteString) value).getBytes();
}
break;
case DECIMAL:
if (value instanceof BigDecimal) {
return DecimalData.fromBigDecimal(
(BigDecimal) value,
LogicalTypeChecks.getPrecision(valueType),
LogicalTypeChecks.getScale(valueType));
}
break;
case TINYINT:
if (value instanceof Number) {
return ((Number) value).byteValue();
}
break;
case SMALLINT:
if (value instanceof Number) {
return ((Number) value).shortValue();
}
break;
case INTEGER:
case INTERVAL_YEAR_MONTH:
if (value instanceof Number) {
return ((Number) value).intValue();
}
break;
case BIGINT:
case INTERVAL_DAY_TIME:
if (value instanceof Number) {
return ((Number) value).longValue();
}
break;
case FLOAT:
if (value instanceof Number) {
return ((Number) value).floatValue();
}
break;
case DOUBLE:
if (value instanceof Number) {
return ((Number) value).doubleValue();
}
break;
case DATE:
if (value instanceof DateString) {
return ((DateString) value).getDaysSinceEpoch();
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
break;
case TIME_WITHOUT_TIME_ZONE:
if (value instanceof TimeString) {
return ((TimeString) value).getMillisOfDay();
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
break;
case TIMESTAMP_WITHOUT_TIME_ZONE:
if (value instanceof TimestampString) {
return TimestampData.fromLocalDateTime(
toLocalDateTime((TimestampString) value));
}
break;
case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
if (value instanceof TimestampString) {
return TimestampData.fromInstant(
toLocalDateTime((TimestampString) value)
.atOffset(ZoneOffset.UTC)
.toInstant());
}
break;
case DISTINCT_TYPE:
return toFlinkInternalValue(value, ((DistinctType) valueType).getSourceType());
case SYMBOL:
if (value instanceof Enum) {
return value;
}
break;
case TIMESTAMP_WITH_TIME_ZONE:
case ARRAY:
case MULTISET:
case MAP:
case ROW:
case STRUCTURED_TYPE:
case NULL:
case UNRESOLVED:
case DESCRIPTOR:
throw new CodeGenException("Type not supported: " + valueType);
}
throw new IllegalStateException(
"Unexpected class " + value.getClass() + " for value of type " + valueType);
}
}
| of |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/StateTrackingMockExecutionGraph.java | {
"start": 9611,
"end": 14324
} | interface ____: all unsupported
@Override
public SchedulingTopology getSchedulingTopology() {
return new TestingSchedulingTopology();
}
@Override
public void enableCheckpointing(
CheckpointCoordinatorConfiguration chkConfig,
List<MasterTriggerRestoreHook<?>> masterHooks,
CheckpointIDCounter checkpointIDCounter,
CompletedCheckpointStore checkpointStore,
StateBackend checkpointStateBackend,
CheckpointStorage checkpointStorage,
CheckpointStatsTracker statsTracker,
CheckpointsCleaner checkpointsCleaner,
String changelogStorage) {
throw new UnsupportedOperationException();
}
@Nullable
@Override
public CheckpointCoordinator getCheckpointCoordinator() {
throw new UnsupportedOperationException();
}
@Override
public KvStateLocationRegistry getKvStateLocationRegistry() {
throw new UnsupportedOperationException();
}
@Override
public Configuration getJobConfiguration() {
throw new UnsupportedOperationException();
}
@Override
public Throwable getFailureCause() {
throw new UnsupportedOperationException();
}
@Override
public ExecutionJobVertex getJobVertex(JobVertexID id) {
throw new UnsupportedOperationException();
}
@Override
public long getNumberOfRestarts() {
throw new UnsupportedOperationException();
}
@Override
public Map<IntermediateDataSetID, IntermediateResult> getAllIntermediateResults() {
throw new UnsupportedOperationException();
}
@Override
public IntermediateResultPartition getResultPartitionOrThrow(IntermediateResultPartitionID id) {
throw new UnsupportedOperationException();
}
@Override
public Map<String, OptionalFailure<Accumulator<?, ?>>> aggregateUserAccumulators() {
throw new UnsupportedOperationException();
}
@Override
public void attachJobGraph(
List<JobVertex> topologicallySorted, JobManagerJobMetricGroup jobManagerJobMetricGroup)
throws JobException {
throw new UnsupportedOperationException();
}
@Override
public JobStatus waitUntilTerminal() throws InterruptedException {
throw new UnsupportedOperationException();
}
@Override
public boolean transitionState(JobStatus current, JobStatus newState) {
throw new UnsupportedOperationException();
}
@Override
public void incrementRestarts() {
throw new UnsupportedOperationException();
}
@Override
public void initFailureCause(Throwable t, long timestamp) {
throw new UnsupportedOperationException();
}
@Override
public void updateAccumulators(AccumulatorSnapshot accumulatorSnapshot) {
throw new UnsupportedOperationException();
}
@Override
public void registerJobStatusListener(JobStatusListener listener) {
throw new UnsupportedOperationException();
}
@Override
public ResultPartitionAvailabilityChecker getResultPartitionAvailabilityChecker() {
throw new UnsupportedOperationException();
}
@Override
public int getNumFinishedVertices() {
throw new UnsupportedOperationException();
}
@Nonnull
@Override
public ComponentMainThreadExecutor getJobMasterMainThreadExecutor() {
throw new UnsupportedOperationException();
}
@Override
public void initializeJobVertex(
ExecutionJobVertex ejv,
long createTimestamp,
Map<IntermediateDataSetID, JobVertexInputInfo> jobVertexInputInfos)
throws JobException {
throw new UnsupportedOperationException();
}
@Override
public void notifyNewlyInitializedJobVertices(List<ExecutionJobVertex> vertices) {
throw new UnsupportedOperationException();
}
@Override
public void addNewJobVertices(
List<JobVertex> sortedJobVertices,
JobManagerJobMetricGroup jobManagerJobMetricGroup,
VertexParallelismStore newVerticesParallelismStore)
throws JobException {
throw new UnsupportedOperationException();
}
public void registerExecution(TestingAccessExecution execution) {
executions.put(execution.getAttemptId(), execution);
}
@Override
public Optional<String> findVertexWithAttempt(ExecutionAttemptID attemptId) {
return Optional.of("dummy");
}
@Override
public Optional<AccessExecution> findExecution(ExecutionAttemptID attemptId) {
return Optional.ofNullable(executions.get(attemptId));
}
}
| implementations |
java | apache__hadoop | hadoop-tools/hadoop-aliyun/src/main/java/org/apache/hadoop/fs/aliyun/oss/ReadBuffer.java | {
"start": 1109,
"end": 2182
} | enum ____ {
INIT, SUCCESS, ERROR
}
private final ReentrantLock lock = new ReentrantLock();
private Condition readyCondition = lock.newCondition();
private byte[] buffer;
private STATUS status;
private long byteStart;
private long byteEnd;
public ReadBuffer(long byteStart, long byteEnd) {
this.buffer = new byte[(int)(byteEnd - byteStart) + 1];
this.status = STATUS.INIT;
this.byteStart = byteStart;
this.byteEnd = byteEnd;
}
public void lock() {
lock.lock();
}
public void unlock() {
lock.unlock();
}
public void await(STATUS waitStatus) throws InterruptedException {
while (this.status == waitStatus) {
readyCondition.await();
}
}
public void signalAll() {
readyCondition.signalAll();
}
public byte[] getBuffer() {
return buffer;
}
public STATUS getStatus() {
return status;
}
public void setStatus(STATUS status) {
this.status = status;
}
public long getByteStart() {
return byteStart;
}
public long getByteEnd() {
return byteEnd;
}
}
| STATUS |
java | quarkusio__quarkus | extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/instrumentation/VertxOpenTelemetryXForwardedTest.java | {
"start": 1250,
"end": 2908
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest unitTest = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addPackage(TestSpanExporter.class.getPackage())
.addClasses(TracerRouter.class, SemconvResolver.class)
.addAsResource(new StringAsset(TestSpanExporterProvider.class.getCanonicalName()),
"META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider")
.addAsResource(new StringAsset(InMemoryMetricExporterProvider.class.getCanonicalName()),
"META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider")
.addAsResource(new StringAsset(InMemoryLogRecordExporterProvider.class.getCanonicalName()),
"META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider"))
.withConfigurationResource("application-default.properties");
@Inject
TestSpanExporter testSpanExporter;
@Test
void trace() {
RestAssured.given().header("X-Forwarded-For", "203.0.113.195, 70.41.3.18, 150.172.238.178")
.when().get("/tracer").then()
.statusCode(200)
.body(is("Hello Tracer!"));
List<SpanData> spans = testSpanExporter.getFinishedSpanItems(2);
SpanData server = getSpanByKindAndParentId(spans, SERVER, "0000000000000000");
assertSemanticAttribute(server, "203.0.113.195", CLIENT_ADDRESS);
}
}
| VertxOpenTelemetryXForwardedTest |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/dynamic/ReactiveTypeAdapters.java | {
"start": 25865,
"end": 26332
} | enum ____ implements Function<Publisher<?>, io.reactivex.rxjava3.core.Flowable<?>> {
INSTANCE;
@Override
public io.reactivex.rxjava3.core.Flowable<?> apply(Publisher<?> source) {
return io.reactivex.rxjava3.core.Flowable.fromPublisher(source);
}
}
/**
* An adapter {@link Function} to adopt a {@link io.reactivex.rxjava3.core.Flowable} to {@link Publisher}.
*/
public | PublisherToRxJava3FlowableAdapter |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/observers/QueueDrainObserver.java | {
"start": 4142,
"end": 4309
} | class ____ extends QueueDrainSubscriberPad0 {
final AtomicInteger wip = new AtomicInteger();
}
/** Pads away the wip from the other fields. */
| QueueDrainSubscriberWip |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/util/Booleans.java | {
"start": 889,
"end": 1657
} | class ____ {
private Booleans() {}
/**
* Returns {@code true} if {@code s} is {@code "true"} (case-insensitive), {@code false} if {@code s} is
* {@code "false"} (case-insensitive), and {@code defaultValue} if {@code s} is anything else (including null or
* empty).
*
* @param s The {@code String} to parse into a {@code boolean}
* @param defaultValue The default value to use if {@code s} is neither {@code "true"} nor {@code "false"}
* @return the {@code boolean} value represented by the argument, or {@code defaultValue}.
*/
public static boolean parseBoolean(final String s, final boolean defaultValue) {
return "true".equalsIgnoreCase(s) || (defaultValue && !"false".equalsIgnoreCase(s));
}
}
| Booleans |
java | quarkusio__quarkus | extensions/hibernate-envers/deployment/src/main/java/io/quarkus/hibernate/envers/deployment/HibernateEnversDisabledProcessor.java | {
"start": 804,
"end": 3393
} | class ____ {
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
public void disableHibernateEnversStaticInit(HibernateEnversRecorder recorder,
HibernateEnversBuildTimeConfig buildTimeConfig,
List<PersistenceUnitDescriptorBuildItem> persistenceUnitDescriptorBuildItems,
BuildProducer<HibernateOrmIntegrationStaticConfiguredBuildItem> integrationProducer) {
checkNoExplicitActiveTrue(buildTimeConfig);
for (PersistenceUnitDescriptorBuildItem puDescriptor : persistenceUnitDescriptorBuildItems) {
integrationProducer.produce(
new HibernateOrmIntegrationStaticConfiguredBuildItem(HibernateEnversProcessor.HIBERNATE_ENVERS,
puDescriptor.getPersistenceUnitName())
.setInitListener(recorder.createStaticInitInactiveListener())
// We don't need XML mapping if Envers is disabled
.setXmlMappingRequired(false));
}
}
// TODO move this to runtime init once we implement in Hibernate ORM a way
// to remove entity types from the metamodel on runtime init
public void checkNoExplicitActiveTrue(HibernateEnversBuildTimeConfig buildTimeConfig) {
for (var entry : buildTimeConfig.persistenceUnits().entrySet()) {
var config = entry.getValue();
if (config.active().isPresent() && config.active().get()) {
var puName = entry.getKey();
String enabledPropertyKey = HibernateEnversBuildTimeConfig.extensionPropertyKey("enabled");
String activePropertyKey = HibernateEnversBuildTimeConfig.persistenceUnitPropertyKey(puName, "active");
throw new ConfigurationException(
"Hibernate Envers activated explicitly for persistence unit '" + puName
+ "', but the Hibernate Envers extension was disabled at build time."
+ " If you want Hibernate Envers to be active for this persistence unit, you must set '"
+ enabledPropertyKey
+ "' to 'true' at build time."
+ " If you don't want Hibernate Envers to be active for this persistence unit, you must leave '"
+ activePropertyKey
+ "' unset or set it to 'false'.",
Set.of(enabledPropertyKey, activePropertyKey));
}
}
}
}
| HibernateEnversDisabledProcessor |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/producer/ProducerWithPrivateZeroParamCtorAndInterceptionTest.java | {
"start": 881,
"end": 1603
} | class ____ {
@RegisterExtension
public ArcTestContainer container = ArcTestContainer.builder()
.beanClasses(MyBinding.class, MyInterceptor.class, MyProducer.class)
.shouldFail()
.build();
@Test
public void test() {
Throwable error = container.getFailure();
assertNotNull(error);
assertTrue(error instanceof DeploymentException);
assertTrue(error.getMessage().contains("is not proxyable because it has a private no-args constructor"));
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR })
@InterceptorBinding
@ | ProducerWithPrivateZeroParamCtorAndInterceptionTest |
java | reactor__reactor-core | reactor-test/src/test/java/reactor/test/DefaultContextExpectationsTest.java | {
"start": 1418,
"end": 12268
} | class ____ {
private void assertContextExpectation(
Function<Flux<Integer>, Flux<Integer>> sourceTransformer,
Function<DefaultContextExpectations<Integer>, ContextExpectations<Integer>> expectations,
long count) {
Flux<Integer> source = sourceTransformer.apply(Flux.range(1, 10));
Step<Integer> step = StepVerifier.create(source);
final DefaultContextExpectations<Integer> base = new DefaultContextExpectations<>(step, new MessageFormatter(null, null, null));
expectations
.apply(base)
.then()
.expectNextCount(count)
.verifyComplete();
}
private void assertContextExpectation(
Function<Flux<Integer>, Flux<Integer>> sourceTransformer,
Function<DefaultContextExpectations<Integer>, ContextExpectations<Integer>> expectations) {
assertContextExpectation(sourceTransformer, expectations, 10);
}
private ThrowableAssertAlternative<AssertionError> assertContextExpectationFails(
Function<Flux<Integer>, Flux<Integer>> sourceTransformer,
Function<DefaultContextExpectations<Integer>, ContextExpectations<Integer>> expectations) {
return assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertContextExpectation(sourceTransformer, expectations));
}
@AfterEach
void tearDown() {
Hooks.resetOnOperatorDebug();
}
@Test
public void contextAccessibleLastInChain() {
assertContextExpectation(s -> s.take(3, false).contextWrite(Context.of("a", "b")),
e -> e, 3);
}
@Test
public void contextAccessibleFirstInChain() {
assertContextExpectation(s -> s.contextWrite(Context.of("a", "b")).take(3, false),
e -> e, 3);
}
@Test
public void contextAccessibleSoloInChain() {
assertContextExpectation(s -> s.contextWrite(Context.of("a", "b")), e -> e);
}
@Test
public void notContextAccessibleDueToPublisher() {
Publisher<Integer> publisher = subscriber -> subscriber.onSubscribe(new Subscription() {
@Override
public void request(long l) {
subscriber.onComplete();
}
@Override
public void cancel() {
//NO-OP
}
});
Step<Integer> step = StepVerifier.create(publisher);
DefaultContextExpectations<Integer> expectations = new DefaultContextExpectations<>(step, new MessageFormatter(null, null, null));
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> expectations.then().verifyComplete())
.withMessage("No propagated Context");
}
@Test
public void hasKey() throws Exception {
assertContextExpectation(s -> s.contextWrite(Context.of("foo", "bar")),
e -> e.hasKey("foo"));
}
@Test
public void notHasKey() throws Exception {
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar")),
e -> e.hasKey("bar"))
.withMessageStartingWith("" +
"Key bar not found\n" +
"Context: Context1{foo=bar}"
);
}
@Test
public void hasSize() throws Exception {
assertContextExpectation(s -> s.contextWrite(Context.of("foo", "bar", "foobar", "baz")),
e -> e.hasSize(2));
}
@Test
public void notHasSize() throws Exception {
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar", "foobar", "baz"))
.contextWrite(Context.of("fails", true)),
e -> e.hasSize(2))
.withMessageStartingWith("" +
"Expected Context of size 2, got 3\n" +
"Context: Context3{fails=true, foo=bar, foobar=baz}"
);
}
@Test
public void contains() throws Exception {
assertContextExpectation(s -> s.contextWrite(Context.of("foo", "bar", "foobar", "baz")),
e -> e.contains("foo", "bar"));
}
@Test
public void notContainsKey() throws Exception {
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar", "foobar", "baz")),
e -> e.contains("fooz", "bar"))
.withMessageStartingWith("" +
"Expected value bar for key fooz, key not present\n" +
"Context: Context2{foo=bar, foobar=baz}"
);
}
@Test
public void notContainsValue() throws Exception {
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar", "foobar", "baz")),
e -> e.contains("foo", "baz"))
.withMessageStartingWith("" +
"Expected value baz for key foo, got bar\n" +
"Context: Context2{foo=bar, foobar=baz}"
);
}
@Test
public void containsAllOfContext() throws Exception {
assertContextExpectation(s -> s.contextWrite(Context.of("foo", "bar", "foobar", "baz")),
e -> e.containsAllOf(Context.of("foo", "bar")));
}
@Test
public void notContainsAllOfContext() throws Exception {
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar", "foobar", "baz")),
e -> e.containsAllOf(Context.of("foo", "bar", "other", "stuff")))
.withMessageStartingWith("" +
"Expected Context to contain all of Context2{foo=bar, other=stuff}\n" +
"Context: Context2{foo=bar, foobar=baz}"
);
}
@Test
public void containsAllOfMap() throws Exception {
assertContextExpectation(s -> s.contextWrite(Context.of("foo", "bar", "foobar", "baz")),
e -> e.containsAllOf(Collections.singletonMap("foo", "bar")));
}
@Test
public void notContainsAllOfMap() throws Exception {
Map<String, String> expected = new HashMap<>();
expected.put("foo", "bar");
expected.put("other", "stuff");
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar", "foobar", "baz")),
e -> e.containsAllOf(expected))
.withMessageStartingWith("" +
"Expected Context to contain all of {other=stuff, foo=bar}\n" +
"Context: Context2{foo=bar, foobar=baz}"
);
}
@Test
public void containsOnlyOfContext() throws Exception {
assertContextExpectation(s -> s.contextWrite(Context.of("foo", "bar")),
e -> e.containsOnly(Context.of("foo", "bar")));
}
@Test
public void notContainsOnlyOfContextSize() throws Exception {
Context expected = Context.of("foo", "bar", "other", "stuff");
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar")),
e -> e.containsOnly(expected))
.withMessageStartingWith("" +
"Expected Context to contain same values as Context2{foo=bar, other=stuff}, but they differ in size\n" +
"Context: Context1{foo=bar}"
);
}
@Test
public void notContainsOnlyOfContextContent() throws Exception {
Context expected = Context.of("foo", "bar", "other", "stuff");
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar", "foobar", "baz")),
e -> e.containsOnly(expected))
.withMessageStartingWith("" +
"Expected Context to contain same values as Context2{foo=bar, other=stuff}, but they differ in content\n" +
"Context: Context2{foo=bar, foobar=baz}"
);
}
@Test
public void containsOnlyOfMap() throws Exception {
assertContextExpectation(s -> s.contextWrite(Context.of("foo", "bar")),
e -> e.containsOnly(Collections.singletonMap("foo", "bar")));
}
@Test
public void notContainsOnlyOfMapSize() throws Exception {
Map<String, String> expected = new HashMap<>();
expected.put("foo", "bar");
expected.put("other", "stuff");
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar")),
e -> e.containsOnly(expected))
.withMessageStartingWith("" +
"Expected Context to contain same values as {other=stuff, foo=bar}, but they differ in size\n" +
"Context: Context1{foo=bar}"
);
}
@Test
public void notContainsOnlyOfMapContent() throws Exception {
Map<String, String> expected = new HashMap<>();
expected.put("foo", "bar");
expected.put("other", "stuff");
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar", "foobar", "baz")),
e -> e.containsOnly(expected))
.withMessageStartingWith("" +
"Expected Context to contain same values as {other=stuff, foo=bar}, but they differ in content\n" +
"Context: Context2{foo=bar, foobar=baz}"
);
}
@Test
public void assertThat() throws Exception {
assertContextExpectation(s -> s.contextWrite(Context.of("foo", "bar")),
e -> e.assertThat(c -> Assertions.assertThat(c).isNotNull()));
}
@Test
public void notAssertThat() throws Exception {
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar")),
e -> e.assertThat(c -> { throw new AssertionError("boom"); }))
.withMessage("boom");
}
@Test
public void matches() throws Exception {
assertContextExpectation(s -> s.contextWrite(Context.of("foo", "bar")),
e -> e.matches(Objects::nonNull));
}
@Test
public void notMatches() throws Exception {
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar")),
e -> e.matches(Objects::isNull))
.withMessageStartingWith("" +
"Context doesn't match predicate\n" +
"Context: Context1{foo=bar}"
);
}
@Test
public void matchesWithDescription() throws Exception {
assertContextExpectation(s -> s.contextWrite(Context.of("foo", "bar")),
e -> e.matches(Objects::nonNull, "desc"));
}
@Test
public void notMatchesWithDescription() throws Exception {
assertContextExpectationFails(s -> s.contextWrite(Context.of("foo", "bar")),
e -> e.matches(Objects::isNull, "desc"))
.withMessageStartingWith("" +
"Context doesn't match predicate desc\n" +
"Context: Context1{foo=bar}"
);
}
@Test
public void notMatchesWithDescriptionAndScenarioName() {
Flux<Integer> source = Flux.range(1, 10)
.contextWrite(Context.of("foo", "bar"));
Step<Integer> step = StepVerifier.create(source);
final DefaultContextExpectations<Integer> base = new DefaultContextExpectations<>(step, new MessageFormatter("scenario", null, null));
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
base.matches(Objects::isNull, "someDescription")
.then()
.expectNextCount(10)::verifyComplete)
.withMessageStartingWith("" +
"[scenario] Context doesn't match predicate someDescription\n" +
"Context: Context1{foo=bar}"
);
}
@Test
public void capturedOperator() {
assertContextExpectationFails(
s -> s.doOnEach(__ -> {}),
e -> e.hasKey("foo")
).withMessageEndingWith("Captured at: range");
}
@Test
public void capturedOperatorWithDebug() {
Hooks.onOperatorDebug();
assertContextExpectationFails(
s -> s.doOnEach(__ -> {}),
e -> e.hasKey("foo")
).withMessageContaining("Captured at: Flux.range ⇢ at reactor.test.DefaultContextExpectationsTest.assertContextExpectation(DefaultContextExpectationsTest.java:");
}
@Test
public void capturedOperatorWithDebugAndConditionalSubscriber() {
Hooks.onOperatorDebug();
assertContextExpectationFails(
s -> s.contextWrite(Context.empty()),
e -> e.hasKey("foo")
).withMessageContaining("Captured at: Flux.range ⇢ at reactor.test.DefaultContextExpectationsTest.assertContextExpectation(DefaultContextExpectationsTest.java:");
}
} | DefaultContextExpectationsTest |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/scheduler/BoundedElasticScheduler.java | {
"start": 2887,
"end": 14978
} | class ____ implements Scheduler,
SchedulerState.DisposeAwaiter<BoundedElasticScheduler.BoundedServices>,
Scannable {
static final Logger LOGGER = Loggers.getLogger(BoundedElasticScheduler.class);
static final int DEFAULT_TTL_SECONDS = 60;
static final AtomicLong COUNTER = new AtomicLong();
final int maxThreads;
final int maxTaskQueuedPerThread;
final Clock clock;
final ThreadFactory factory;
final long ttlMillis;
@SuppressWarnings("NotNullFieldNotInitialized") // lazy-initialized in constructor
volatile SchedulerState<BoundedServices> state;
@SuppressWarnings("rawtypes")
static final AtomicReferenceFieldUpdater<BoundedElasticScheduler, SchedulerState> STATE =
AtomicReferenceFieldUpdater.newUpdater(BoundedElasticScheduler.class, SchedulerState.class, "state");
private static final SchedulerState<BoundedServices> INIT =
SchedulerState.init(SHUTDOWN);
/**
* This constructor lets define millisecond-grained TTLs and a custom {@link Clock},
* which can be useful for tests.
*/
BoundedElasticScheduler(int maxThreads, int maxTaskQueuedPerThread,
ThreadFactory threadFactory, long ttlMillis, Clock clock) {
if (ttlMillis <= 0) {
throw new IllegalArgumentException("TTL must be strictly positive, was " + ttlMillis + "ms");
}
if (maxThreads <= 0) {
throw new IllegalArgumentException("maxThreads must be strictly positive, was " + maxThreads);
}
if (maxTaskQueuedPerThread <= 0) {
throw new IllegalArgumentException("maxTaskQueuedPerThread must be strictly positive, was " + maxTaskQueuedPerThread);
}
this.maxThreads = maxThreads;
this.maxTaskQueuedPerThread = maxTaskQueuedPerThread;
this.factory = threadFactory;
this.clock = Objects.requireNonNull(clock, "A Clock must be provided");
this.ttlMillis = ttlMillis;
STATE.lazySet(this, INIT);
}
/**
* Create a {@link BoundedElasticScheduler} with the given configuration. Note that backing threads
* (or executors) can be shared by each {@link reactor.core.scheduler.Scheduler.Worker}, so each worker
* can contribute to the task queue size.
*
* @param maxThreads the maximum number of backing threads to spawn, must be strictly positive
* @param maxTaskQueuedPerThread the maximum amount of tasks an executor can queue up
* @param factory the {@link ThreadFactory} to name the backing threads
* @param ttlSeconds the time-to-live (TTL) of idle threads, in seconds
*/
BoundedElasticScheduler(int maxThreads, int maxTaskQueuedPerThread, ThreadFactory factory, int ttlSeconds) {
this(maxThreads, maxTaskQueuedPerThread, factory, ttlSeconds * 1000L,
Clock.tickSeconds(BoundedServices.ZONE_UTC));
}
/**
* Instantiates the default {@link ScheduledExecutorService} for the scheduler
* ({@code Executors.newScheduledThreadPoolExecutor} with core and max pool size of 1).
*/
BoundedScheduledExecutorService createBoundedExecutorService() {
return new BoundedScheduledExecutorService(this.maxTaskQueuedPerThread, this.factory);
}
@Override
public boolean isDisposed() {
// we only consider disposed as actually shutdown
SchedulerState<BoundedServices> current = this.state;
return current != INIT && current.currentResource == SHUTDOWN;
}
@Override
public void init() {
SchedulerState<BoundedServices> a = this.state;
if (a != INIT) {
if (a.currentResource == SHUTDOWN) {
throw new IllegalStateException(
"Initializing a disposed scheduler is not permitted"
);
}
// return early - scheduler already initialized
return;
}
SchedulerState<BoundedServices> b =
SchedulerState.init(new BoundedServices(this));
if (STATE.compareAndSet(this, INIT, b)) {
try {
b.currentResource.evictor.scheduleAtFixedRate(
b.currentResource::eviction,
ttlMillis, ttlMillis, TimeUnit.MILLISECONDS
);
return;
} catch (RejectedExecutionException ree) {
// The executor was most likely shut down in parallel.
// If the state is SHUTDOWN - it's ok, no eviction schedule required;
// If it's running - the other thread did a restart and will run its own schedule.
// In both cases we throw an exception, as the caller of init() should
// expect the scheduler to be running when this method returns.
throw new IllegalStateException(
"Scheduler disposed during initialization"
);
}
} else {
b.currentResource.evictor.shutdownNow();
// Currently, isDisposed() is true for non-initialized state, but that will
// be fixed in 3.5.0. At this stage we know however that the state is no
// longer INIT, so isDisposed() actually means disposed state.
if (isDisposed()) {
throw new IllegalStateException(
"Initializing a disposed scheduler is not permitted"
);
}
}
}
@Override
@SuppressWarnings("deprecation")
public void start() {
SchedulerState<BoundedServices> a = this.state;
if (a.currentResource != SHUTDOWN) {
return;
}
SchedulerState<BoundedServices> b =
SchedulerState.init(new BoundedServices(this));
if (STATE.compareAndSet(this, a, b)) {
try {
b.currentResource.evictor.scheduleAtFixedRate(
b.currentResource::eviction,
ttlMillis, ttlMillis, TimeUnit.MILLISECONDS
);
return;
} catch (RejectedExecutionException ree) {
// The executor was most likely shut down in parallel.
// If the state is SHUTDOWN - it's ok, no eviction schedule required;
// If it's running - the other thread did a restart and will run its own schedule.
// In both cases we ignore it.
}
}
// someone else shutdown or started successfully, free the resource
b.currentResource.evictor.shutdownNow();
}
@Override
public boolean await(BoundedServices boundedServices, long timeout, TimeUnit timeUnit) throws InterruptedException {
if (!boundedServices.evictor.awaitTermination(timeout, timeUnit)) {
return false;
}
for (BoundedState bs : boundedServices.busyStates.array) {
if (!bs.executor.awaitTermination(timeout, timeUnit)) {
return false;
}
}
return true;
}
@Override
public void dispose() {
SchedulerState<BoundedServices> previous = state;
if (previous.currentResource == SHUTDOWN) {
// A dispose process might be ongoing, but we want a forceful shutdown,
// so we do our best to release the resources without updating the state.
if (previous.initialResource != null) {
previous.initialResource.evictor.shutdownNow();
for (BoundedState bs : previous.initialResource.busyStates.array) {
bs.shutdown(true);
}
}
return;
}
final BoundedState[] toAwait = previous.currentResource.dispose();
SchedulerState<BoundedServices> shutDown = SchedulerState.transition(
previous.currentResource,
SHUTDOWN, this
);
STATE.compareAndSet(this, previous, shutDown);
// If unsuccessful - either another thread disposed or restarted - no issue,
// we only care about the one stored in shutDown.
assert shutDown.initialResource != null;
shutDown.initialResource.evictor.shutdownNow();
for (BoundedState bs : toAwait) {
bs.shutdown(true);
}
}
@Override
public Mono<Void> disposeGracefully() {
return Mono.defer(() -> {
SchedulerState<BoundedServices> previous = state;
if (previous.currentResource == SHUTDOWN) {
return previous.onDispose;
}
final BoundedState[] toAwait = previous.currentResource.dispose();
SchedulerState<BoundedServices> shutDown = SchedulerState.transition(
previous.currentResource,
SHUTDOWN, this
);
STATE.compareAndSet(this, previous, shutDown);
// If unsuccessful - either another thread disposed or restarted - no issue,
// we only care about the one stored in shutDown.
assert shutDown.initialResource != null;
shutDown.initialResource.evictor.shutdown();
for (BoundedState bs : toAwait) {
bs.shutdown(false);
}
return shutDown.onDispose;
});
}
@Override
public Disposable schedule(Runnable task) {
//tasks running once will call dispose on the BoundedState, decreasing its usage by one
BoundedState picked = state.currentResource.pick();
try {
return Schedulers.directSchedule(picked.executor, task, picked, 0L, TimeUnit.MILLISECONDS);
} catch (RejectedExecutionException ex) {
// ensure to free the BoundedState so it can be reused
picked.dispose();
throw ex;
}
}
@Override
public Disposable schedule(Runnable task, long delay, TimeUnit unit) {
//tasks running once will call dispose on the BoundedState, decreasing its usage by one
final BoundedState picked = state.currentResource.pick();
try {
return Schedulers.directSchedule(picked.executor, task, picked, delay, unit);
} catch (RejectedExecutionException ex) {
// ensure to free the BoundedState so it can be reused
picked.dispose();
throw ex;
}
}
@Override
public Disposable schedulePeriodically(Runnable task,
long initialDelay,
long period,
TimeUnit unit) {
final BoundedState picked = state.currentResource.pick();
try {
Disposable scheduledTask = Schedulers.directSchedulePeriodically(picked.executor,
task,
initialDelay,
period,
unit);
//a composite with picked ensures the cancellation of the task releases the BoundedState
// (ie decreases its usage by one)
return Disposables.composite(scheduledTask, picked);
} catch (RejectedExecutionException ex) {
// ensure to free the BoundedState so it can be reused
picked.dispose();
throw ex;
}
}
@Override
public String toString() {
StringBuilder ts = new StringBuilder(Schedulers.BOUNDED_ELASTIC)
.append('(');
if (factory instanceof ReactorThreadFactory) {
ts.append('\"').append(((ReactorThreadFactory) factory).get()).append("\",");
}
ts.append("maxThreads=").append(maxThreads)
.append(",maxTaskQueuedPerThread=").append(maxTaskQueuedPerThread == Integer.MAX_VALUE ? "unbounded" : maxTaskQueuedPerThread)
.append(",ttl=");
if (ttlMillis < 1000) {
ts.append(ttlMillis).append("ms)");
}
else {
ts.append(ttlMillis / 1000).append("s)");
}
return ts.toString();
}
/**
* @return a best effort total count of the spinned up executors
*/
int estimateSize() {
return state.currentResource.get();
}
/**
* @return a best effort total count of the busy executors
*/
int estimateBusy() {
return state.currentResource.busyStates.array.length;
}
/**
* @return a best effort total count of the idle executors
*/
int estimateIdle() {
return state.currentResource.idleQueue.size();
}
/**
* Best effort snapshot of the remaining queue capacity for pending tasks across all the backing executors.
*
* @return the total task capacity, or {@literal -1} if any backing executor's task queue size cannot be instrumented
*/
int estimateRemainingTaskCapacity() {
BoundedState[] busyArray = state.currentResource.busyStates.array;
int totalTaskCapacity = maxTaskQueuedPerThread * maxThreads;
for (BoundedState state : busyArray) {
int stateQueueSize = state.estimateQueueSize();
if (stateQueueSize >= 0) {
totalTaskCapacity -= stateQueueSize;
}
else {
return -1;
}
}
return totalTaskCapacity;
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.TERMINATED || key == Attr.CANCELLED) return isDisposed();
if (key == Attr.BUFFERED) return estimateSize();
if (key == Attr.CAPACITY) return maxThreads;
if (key == Attr.NAME) return this.toString();
return null;
}
@Override
public Stream<? extends Scannable> inners() {
BoundedServices services = state.currentResource;
return Stream.concat(Stream.of(services.busyStates.array), services.idleQueue.stream())
.filter(obj -> obj != null && obj != CREATING);
}
@Override
public Worker createWorker() {
BoundedState picked = state.currentResource.pick();
ExecutorServiceWorker worker = new ExecutorServiceWorker(picked.executor);
worker.disposables.add(picked); //this ensures the BoundedState will be released when worker is disposed
return worker;
}
static final | BoundedElasticScheduler |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerLivenessContext.java | {
"start": 1244,
"end": 1394
} | class ____ {
private final Container container;
private final String user;
private final String pid;
public static final | ContainerLivenessContext |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/main/java/org/springframework/data/jpa/convert/threeten/Jsr310JpaConverters.java | {
"start": 2992,
"end": 3484
} | class ____ implements AttributeConverter<@Nullable LocalTime, @Nullable Date> {
@Override
public @Nullable Date convertToDatabaseColumn(@Nullable LocalTime time) {
return time == null ? null : LocalTimeToDateConverter.INSTANCE.convert(time);
}
@Override
public @Nullable LocalTime convertToEntityAttribute(@Nullable Date date) {
return date == null ? null : DateToLocalTimeConverter.INSTANCE.convert(date);
}
}
@Converter(autoApply = true)
public static | LocalTimeConverter |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/registerclientheaders/HeaderNoPassingClient.java | {
"start": 424,
"end": 526
} | interface ____ {
@GET
@Path("/describe-request")
RequestData call();
}
| HeaderNoPassingClient |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/test/hamcrest/WellKnownBinaryBytesRefMatcher.java | {
"start": 889,
"end": 1942
} | class ____<G extends Geometry> extends TypeSafeMatcher<BytesRef> {
private final Matcher<G> matcher;
public WellKnownBinaryBytesRefMatcher(Matcher<G> matcher) {
this.matcher = matcher;
}
public static <G extends Geometry> Matcher<BytesRef> encodes(TypeSafeMatcher<G> matcher) {
return new WellKnownBinaryBytesRefMatcher<G>(matcher);
}
@Override
public boolean matchesSafely(BytesRef bytesRef) {
return matcher.matches(fromBytesRef(bytesRef));
}
@Override
public void describeMismatchSafely(BytesRef bytesRef, Description description) {
matcher.describeMismatch(fromBytesRef(bytesRef), description);
}
@SuppressWarnings("unchecked")
private G fromBytesRef(BytesRef bytesRef) {
return (G) WellKnownBinary.fromWKB(GeometryValidator.NOOP, false /* coerce */, bytesRef.bytes, bytesRef.offset, bytesRef.length);
}
@Override
public void describeTo(Description description) {
matcher.describeTo(description);
}
}
| WellKnownBinaryBytesRefMatcher |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyTest.java | {
"start": 2268,
"end": 2483
} | class ____ implements SettingProvider.Provider<CollectionClassification> {
@Override
public CollectionClassification getSetting() {
return CollectionClassification.BAG;
}
}
public static | ListSemanticProvider |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/bean/scope/ScopeInheritanceTest.java | {
"start": 1821,
"end": 1882
} | interface ____ {
}
@MyStereotype
static | MyStereotype |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/engine/support/hierarchical/ParallelExecutionIntegrationTests.java | {
"start": 24335,
"end": 24929
} | class ____ {
static AtomicInteger sharedResource;
static CountDownLatch countDownLatch;
@BeforeAll
static void initialize() {
sharedResource = new AtomicInteger();
countDownLatch = new CountDownLatch(3);
}
@Test
void firstTest() throws Exception {
incrementBlockAndCheck(sharedResource, countDownLatch);
}
@Test
void secondTest() throws Exception {
incrementBlockAndCheck(sharedResource, countDownLatch);
}
@Test
void thirdTest() throws Exception {
incrementBlockAndCheck(sharedResource, countDownLatch);
}
}
static | SuccessfulWithClassLockTestCase |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/xcontent/LoggingDeprecationHandler.java | {
"start": 1291,
"end": 4836
} | class ____ implements DeprecationHandler {
/**
* The logger to which to send deprecation messages.
* <p>
* This uses ParseField's logger because that is the logger that
* we have been using for many releases for deprecated fields.
* Changing that will require some research to make super duper
* sure it is safe.
*/
private static final DeprecationLogger deprecationLogger = DeprecationLogger.getLogger(ParseField.class);
public static final LoggingDeprecationHandler INSTANCE = new LoggingDeprecationHandler();
public static final XContentParserConfiguration XCONTENT_PARSER_CONFIG = XContentParserConfiguration.EMPTY.withDeprecationHandler(
INSTANCE
);
private LoggingDeprecationHandler() {
// one instance only
}
@Override
public void logRenamedField(String parserName, Supplier<XContentLocation> location, String oldName, String currentName) {
logRenamedField(parserName, location, oldName, currentName, false);
}
@Override
public void logReplacedField(String parserName, Supplier<XContentLocation> location, String oldName, String replacedName) {
logReplacedField(parserName, location, oldName, replacedName, false);
}
@Override
public void logRemovedField(String parserName, Supplier<XContentLocation> location, String removedName) {
logRemovedField(parserName, location, removedName, false);
}
@Override
public void logRenamedField(
String parserName,
Supplier<XContentLocation> location,
String oldName,
String currentName,
boolean isCompatibleDeprecation
) {
String prefix = parserLocation(parserName, location);
log(
isCompatibleDeprecation,
"{}Deprecated field [{}] used, expected [{}] instead",
new Object[] { prefix, oldName, currentName },
oldName
);
}
@Override
public void logReplacedField(
String parserName,
Supplier<XContentLocation> location,
String oldName,
String replacedName,
boolean isCompatibleDeprecation
) {
String prefix = parserLocation(parserName, location);
log(
isCompatibleDeprecation,
"{}Deprecated field [{}] used, replaced by [{}]",
new Object[] { prefix, oldName, replacedName },
oldName
);
}
@Override
public void logRemovedField(
String parserName,
Supplier<XContentLocation> location,
String removedName,
boolean isCompatibleDeprecation
) {
String prefix = parserLocation(parserName, location);
log(
isCompatibleDeprecation,
"{}Deprecated field [{}] used, this field is unused and will be removed entirely",
new Object[] { prefix, removedName },
removedName
);
}
private static String parserLocation(String parserName, Supplier<XContentLocation> location) {
return parserName == null ? "" : "[" + parserName + "][" + location.get() + "] ";
}
private static void log(boolean isCompatibleDeprecation, String message, Object[] params, String fieldName) {
if (isCompatibleDeprecation) {
deprecationLogger.compatibleCritical("deprecated_field_" + fieldName, message, params);
} else {
deprecationLogger.warn(DeprecationCategory.API, "deprecated_field_" + fieldName, message, params);
}
}
}
| LoggingDeprecationHandler |
java | square__retrofit | retrofit-converters/scalars/src/main/java/retrofit2/converter/scalars/ScalarResponseBodyConverters.java | {
"start": 2936,
"end": 3265
} | class ____ implements Converter<ResponseBody, Integer> {
static final IntegerResponseBodyConverter INSTANCE = new IntegerResponseBodyConverter();
@Override
public Integer convert(ResponseBody value) throws IOException {
return Integer.valueOf(value.string());
}
}
static final | IntegerResponseBodyConverter |
java | netty__netty | codec-smtp/src/main/java/io/netty/handler/codec/smtp/SmtpRequest.java | {
"start": 790,
"end": 1085
} | interface ____ {
/**
* Returns the {@link SmtpCommand} that belongs to the request.
*/
SmtpCommand command();
/**
* Returns a {@link List} which holds all the parameters of a request, which may be an empty list.
*/
List<CharSequence> parameters();
}
| SmtpRequest |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/writer/BeanDefinitionWriter.java | {
"start": 201606,
"end": 201727
} | class
____ executableMethodInstance = innerTypeDef.instantiate(
// 1st argument: pass outer | ExpressionDef |
java | google__error-prone | refaster/src/main/java/com/google/errorprone/refaster/RefasterRuleCompilerAnalyzer.java | {
"start": 1306,
"end": 1383
} | class ____ outputs a serialized analyzer
* to the specified path.
*/
public | and |
java | eclipse-vertx__vert.x | vertx-core/src/test/java/io/vertx/tests/vertx/VertxUseDaemonThreadTest.java | {
"start": 879,
"end": 1724
} | class ____ extends VertxTestBase {
@Parameter
public Boolean useDaemonThread;
@Parameters(name = "{index}: useDaemonThread={0}")
public static List<Object[]> params() {
return Arrays.asList(new Object[] {true}, new Object[] {false}, new Object[] {null});
}
@Override
protected VertxOptions getOptions() {
return super.getOptions().setUseDaemonThread(useDaemonThread);
}
@Test
public void testUseDaemonThread() {
vertx.runOnContext(v -> {
Thread current = Thread.currentThread();
if (useDaemonThread != null) {
assertEquals(useDaemonThread.booleanValue(), current.isDaemon());
} else {
// null means do not change the daemon flag, so it should be non daemon
assertFalse(current.isDaemon());
}
testComplete();
});
await();
}
}
| VertxUseDaemonThreadTest |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/common/geo/LuceneGeometriesUtilsTests.java | {
"start": 1422,
"end": 22298
} | class ____ extends ESTestCase {
public void testLatLonPoint() {
Point point = GeometryTestUtils.randomPoint();
{
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(point, false, t -> assertEquals(ShapeType.POINT, t));
assertEquals(1, geometries.length);
assertLatLonPoint(point, geometries[0]);
}
{
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(point, true, t -> assertEquals(ShapeType.POINT, t));
assertEquals(1, geometries.length);
assertLatLonPoint(quantize(point), geometries[0]);
}
}
public void testLatLonMultiPoint() {
MultiPoint multiPoint = GeometryTestUtils.randomMultiPoint(randomBoolean());
{
int[] counter = new int[] { 0 };
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(multiPoint, false, t -> {
if (counter[0]++ == 0) {
assertEquals(ShapeType.MULTIPOINT, t);
} else {
assertEquals(ShapeType.POINT, t);
}
});
assertEquals(multiPoint.size(), geometries.length);
for (int i = 0; i < multiPoint.size(); i++) {
assertLatLonPoint(multiPoint.get(i), geometries[i]);
}
}
{
int[] counter = new int[] { 0 };
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(multiPoint, true, t -> {
if (counter[0]++ == 0) {
assertEquals(ShapeType.MULTIPOINT, t);
} else {
assertEquals(ShapeType.POINT, t);
}
});
assertEquals(multiPoint.size(), geometries.length);
for (int i = 0; i < multiPoint.size(); i++) {
assertLatLonPoint(quantize(multiPoint.get(i)), geometries[i]);
}
}
}
private void assertLatLonPoint(Point point, LatLonGeometry geometry) {
assertThat(geometry, instanceOf(org.apache.lucene.geo.Point.class));
org.apache.lucene.geo.Point lalonPoint = (org.apache.lucene.geo.Point) geometry;
assertThat(lalonPoint.getLon(), equalTo(point.getLon()));
assertThat(lalonPoint.getLat(), equalTo(point.getLat()));
assertThat(geometry, equalTo(LuceneGeometriesUtils.toLatLonPoint(point)));
}
public void testXYPoint() {
Point point = ShapeTestUtils.randomPoint();
XYGeometry[] geometries = LuceneGeometriesUtils.toXYGeometry(point, t -> assertEquals(ShapeType.POINT, t));
assertEquals(1, geometries.length);
assertXYPoint(point, geometries[0]);
assertThat(geometries[0], instanceOf(org.apache.lucene.geo.XYPoint.class));
}
public void testXYMultiPoint() {
MultiPoint multiPoint = ShapeTestUtils.randomMultiPoint(randomBoolean());
int[] counter = new int[] { 0 };
XYGeometry[] geometries = LuceneGeometriesUtils.toXYGeometry(multiPoint, t -> {
if (counter[0]++ == 0) {
assertEquals(ShapeType.MULTIPOINT, t);
} else {
assertEquals(ShapeType.POINT, t);
}
});
assertEquals(multiPoint.size(), geometries.length);
for (int i = 0; i < multiPoint.size(); i++) {
assertXYPoint(multiPoint.get(i), geometries[i]);
}
}
private void assertXYPoint(Point point, XYGeometry geometry) {
assertThat(geometry, instanceOf(org.apache.lucene.geo.XYPoint.class));
org.apache.lucene.geo.XYPoint xyPoint = (org.apache.lucene.geo.XYPoint) geometry;
assertThat(xyPoint.getX(), equalTo((float) point.getX()));
assertThat(xyPoint.getY(), equalTo((float) point.getY()));
assertThat(geometry, equalTo(LuceneGeometriesUtils.toXYPoint(point)));
}
public void testLatLonLine() {
Line line = GeometryTestUtils.randomLine(randomBoolean());
{
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(line, false, t -> assertEquals(ShapeType.LINESTRING, t));
assertEquals(1, geometries.length);
assertLatLonLine(line, geometries[0]);
}
{
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(line, true, t -> assertEquals(ShapeType.LINESTRING, t));
assertEquals(1, geometries.length);
assertLatLonLine(quantize(line), geometries[0]);
}
}
public void testLatLonMultiLine() {
MultiLine multiLine = GeometryTestUtils.randomMultiLine(randomBoolean());
{
int[] counter = new int[] { 0 };
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(multiLine, false, t -> {
if (counter[0]++ == 0) {
assertEquals(ShapeType.MULTILINESTRING, t);
} else {
assertEquals(ShapeType.LINESTRING, t);
}
});
assertEquals(multiLine.size(), geometries.length);
for (int i = 0; i < multiLine.size(); i++) {
assertLatLonLine(multiLine.get(i), geometries[i]);
}
}
{
int[] counter = new int[] { 0 };
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(multiLine, true, t -> {
if (counter[0]++ == 0) {
assertEquals(ShapeType.MULTILINESTRING, t);
} else {
assertEquals(ShapeType.LINESTRING, t);
}
});
assertEquals(multiLine.size(), geometries.length);
for (int i = 0; i < multiLine.size(); i++) {
assertLatLonLine(quantize(multiLine.get(i)), geometries[i]);
}
}
}
private void assertLatLonLine(Line line, LatLonGeometry geometry) {
assertThat(geometry, instanceOf(org.apache.lucene.geo.Line.class));
org.apache.lucene.geo.Line lalonLine = (org.apache.lucene.geo.Line) geometry;
assertThat(lalonLine.getLons(), equalTo(line.getLons()));
assertThat(lalonLine.getLats(), equalTo(line.getLats()));
assertThat(geometry, equalTo(LuceneGeometriesUtils.toLatLonLine(line)));
}
public void testXYLine() {
Line line = ShapeTestUtils.randomLine(randomBoolean());
XYGeometry[] geometries = LuceneGeometriesUtils.toXYGeometry(line, t -> assertEquals(ShapeType.LINESTRING, t));
assertEquals(1, geometries.length);
assertXYLine(line, geometries[0]);
}
public void testXYMultiLine() {
MultiLine multiLine = ShapeTestUtils.randomMultiLine(randomBoolean());
int[] counter = new int[] { 0 };
XYGeometry[] geometries = LuceneGeometriesUtils.toXYGeometry(multiLine, t -> {
if (counter[0]++ == 0) {
assertEquals(ShapeType.MULTILINESTRING, t);
} else {
assertEquals(ShapeType.LINESTRING, t);
}
});
assertEquals(multiLine.size(), geometries.length);
for (int i = 0; i < multiLine.size(); i++) {
assertXYLine(multiLine.get(i), geometries[i]);
}
}
private void assertXYLine(Line line, XYGeometry geometry) {
assertThat(geometry, instanceOf(org.apache.lucene.geo.XYLine.class));
org.apache.lucene.geo.XYLine xyLine = (org.apache.lucene.geo.XYLine) geometry;
assertThat(xyLine.getX(), equalTo(LuceneGeometriesUtils.doubleArrayToFloatArray(line.getLons())));
assertThat(xyLine.getY(), equalTo(LuceneGeometriesUtils.doubleArrayToFloatArray(line.getLats())));
assertThat(geometry, equalTo(LuceneGeometriesUtils.toXYLine(line)));
}
public void testLatLonPolygon() {
Polygon polygon = validRandomPolygon(randomBoolean());
{
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(polygon, false, t -> assertEquals(ShapeType.POLYGON, t));
assertEquals(1, geometries.length);
assertLatLonPolygon(polygon, geometries[0]);
}
{
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(polygon, true, t -> assertEquals(ShapeType.POLYGON, t));
assertEquals(1, geometries.length);
assertLatLonPolygon(quantize(polygon), geometries[0]);
}
}
public void testLatLonMultiPolygon() {
MultiPolygon multiPolygon = validRandomMultiPolygon(randomBoolean());
{
int[] counter = new int[] { 0 };
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(multiPolygon, false, t -> {
if (counter[0]++ == 0) {
assertEquals(ShapeType.MULTIPOLYGON, t);
} else {
assertEquals(ShapeType.POLYGON, t);
}
});
assertEquals(multiPolygon.size(), geometries.length);
for (int i = 0; i < multiPolygon.size(); i++) {
assertLatLonPolygon(multiPolygon.get(i), geometries[i]);
}
}
{
int[] counter = new int[] { 0 };
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(multiPolygon, true, t -> {
if (counter[0]++ == 0) {
assertEquals(ShapeType.MULTIPOLYGON, t);
} else {
assertEquals(ShapeType.POLYGON, t);
}
});
assertEquals(multiPolygon.size(), geometries.length);
for (int i = 0; i < multiPolygon.size(); i++) {
assertLatLonPolygon(quantize(multiPolygon.get(i)), geometries[i]);
}
}
}
private void assertLatLonPolygon(Polygon polygon, LatLonGeometry geometry) {
assertThat(geometry, instanceOf(org.apache.lucene.geo.Polygon.class));
org.apache.lucene.geo.Polygon lalonPolygon = (org.apache.lucene.geo.Polygon) geometry;
assertThat(lalonPolygon.getPolyLons(), equalTo(polygon.getPolygon().getLons()));
assertThat(lalonPolygon.getPolyLats(), equalTo(polygon.getPolygon().getLats()));
assertThat(geometry, equalTo(LuceneGeometriesUtils.toLatLonPolygon(polygon)));
}
public void testXYPolygon() {
Polygon polygon = ShapeTestUtils.randomPolygon(randomBoolean());
XYGeometry[] geometries = LuceneGeometriesUtils.toXYGeometry(polygon, t -> assertEquals(ShapeType.POLYGON, t));
assertEquals(1, geometries.length);
assertXYPolygon(polygon, geometries[0]);
}
public void testXYMultiPolygon() {
MultiPolygon multiPolygon = ShapeTestUtils.randomMultiPolygon(randomBoolean());
int[] counter = new int[] { 0 };
XYGeometry[] geometries = LuceneGeometriesUtils.toXYGeometry(multiPolygon, t -> {
if (counter[0]++ == 0) {
assertEquals(ShapeType.MULTIPOLYGON, t);
} else {
assertEquals(ShapeType.POLYGON, t);
}
});
assertEquals(multiPolygon.size(), geometries.length);
for (int i = 0; i < multiPolygon.size(); i++) {
assertXYPolygon(multiPolygon.get(i), geometries[i]);
}
}
private void assertXYPolygon(Polygon polygon, XYGeometry geometry) {
assertThat(geometry, instanceOf(org.apache.lucene.geo.XYPolygon.class));
org.apache.lucene.geo.XYPolygon xyPolygon = (org.apache.lucene.geo.XYPolygon) geometry;
assertThat(xyPolygon.getPolyX(), equalTo(LuceneGeometriesUtils.doubleArrayToFloatArray(polygon.getPolygon().getX())));
assertThat(xyPolygon.getPolyY(), equalTo(LuceneGeometriesUtils.doubleArrayToFloatArray(polygon.getPolygon().getY())));
assertThat(geometry, equalTo(LuceneGeometriesUtils.toXYPolygon(polygon)));
}
public void testLatLonGeometryCollection() {
boolean hasZ = randomBoolean();
Point point = GeometryTestUtils.randomPoint(hasZ);
Line line = GeometryTestUtils.randomLine(hasZ);
Polygon polygon = validRandomPolygon(hasZ);
GeometryCollection<Geometry> geometryCollection = new GeometryCollection<>(List.of(point, line, polygon));
{
int[] counter = new int[] { 0 };
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(geometryCollection, false, t -> {
if (counter[0] == 0) {
assertEquals(ShapeType.GEOMETRYCOLLECTION, t);
} else if (counter[0] == 1) {
assertEquals(ShapeType.POINT, t);
} else if (counter[0] == 2) {
assertEquals(ShapeType.LINESTRING, t);
} else if (counter[0] == 3) {
assertEquals(ShapeType.POLYGON, t);
} else {
fail("Unexpected counter value");
}
counter[0]++;
});
assertEquals(geometryCollection.size(), geometries.length);
assertLatLonPoint(point, geometries[0]);
assertLatLonLine(line, geometries[1]);
assertLatLonPolygon(polygon, geometries[2]);
}
{
int[] counter = new int[] { 0 };
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(geometryCollection, true, t -> {
if (counter[0] == 0) {
assertEquals(ShapeType.GEOMETRYCOLLECTION, t);
} else if (counter[0] == 1) {
assertEquals(ShapeType.POINT, t);
} else if (counter[0] == 2) {
assertEquals(ShapeType.LINESTRING, t);
} else if (counter[0] == 3) {
assertEquals(ShapeType.POLYGON, t);
} else {
fail("Unexpected counter value");
}
counter[0]++;
});
assertEquals(geometryCollection.size(), geometries.length);
assertLatLonPoint(quantize(point), geometries[0]);
assertLatLonLine(quantize(line), geometries[1]);
assertLatLonPolygon(quantize(polygon), geometries[2]);
}
}
public void testXYGeometryCollection() {
boolean hasZ = randomBoolean();
Point point = ShapeTestUtils.randomPoint(hasZ);
Line line = ShapeTestUtils.randomLine(hasZ);
Polygon polygon = ShapeTestUtils.randomPolygon(hasZ);
GeometryCollection<Geometry> geometryCollection = new GeometryCollection<>(List.of(point, line, polygon));
int[] counter = new int[] { 0 };
XYGeometry[] geometries = LuceneGeometriesUtils.toXYGeometry(geometryCollection, t -> {
if (counter[0] == 0) {
assertEquals(ShapeType.GEOMETRYCOLLECTION, t);
} else if (counter[0] == 1) {
assertEquals(ShapeType.POINT, t);
} else if (counter[0] == 2) {
assertEquals(ShapeType.LINESTRING, t);
} else if (counter[0] == 3) {
assertEquals(ShapeType.POLYGON, t);
} else {
fail("Unexpected counter value");
}
counter[0]++;
});
assertEquals(geometryCollection.size(), geometries.length);
assertXYPoint(point, geometries[0]);
assertXYLine(line, geometries[1]);
assertXYPolygon(polygon, geometries[2]);
}
private Polygon validRandomPolygon(boolean hasLat) {
return randomValueOtherThanMany(
polygon -> GeometryNormalizer.needsNormalize(Orientation.CCW, polygon),
() -> GeometryTestUtils.randomPolygon(hasLat)
);
}
public void testLatLonRectangle() {
Rectangle rectangle = GeometryTestUtils.randomRectangle();
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(rectangle, false, t -> assertEquals(ShapeType.ENVELOPE, t));
assertEquals(1, geometries.length);
assertLatLonRectangle(rectangle, geometries[0]);
}
private void assertLatLonRectangle(Rectangle rectangle, LatLonGeometry geometry) {
assertThat(geometry, instanceOf(org.apache.lucene.geo.Rectangle.class));
org.apache.lucene.geo.Rectangle lalonRectangle = (org.apache.lucene.geo.Rectangle) geometry;
assertThat(lalonRectangle.maxLon, equalTo(rectangle.getMaxLon()));
assertThat(lalonRectangle.minLon, equalTo(rectangle.getMinLon()));
assertThat(lalonRectangle.maxLat, equalTo(rectangle.getMaxLat()));
assertThat(lalonRectangle.minLat, equalTo(rectangle.getMinLat()));
assertThat(geometry, equalTo(LuceneGeometriesUtils.toLatLonRectangle(rectangle)));
}
public void testXYRectangle() {
Rectangle rectangle = ShapeTestUtils.randomRectangle();
XYGeometry[] geometries = LuceneGeometriesUtils.toXYGeometry(rectangle, t -> assertEquals(ShapeType.ENVELOPE, t));
assertEquals(1, geometries.length);
assertXYRectangle(rectangle, geometries[0]);
}
private void assertXYRectangle(Rectangle rectangle, XYGeometry geometry) {
assertThat(geometry, instanceOf(org.apache.lucene.geo.XYRectangle.class));
org.apache.lucene.geo.XYRectangle xyRectangle = (org.apache.lucene.geo.XYRectangle) geometry;
assertThat(xyRectangle.maxX, equalTo((float) rectangle.getMaxX()));
assertThat(xyRectangle.minX, equalTo((float) rectangle.getMinX()));
assertThat(xyRectangle.maxY, equalTo((float) rectangle.getMaxY()));
assertThat(xyRectangle.minY, equalTo((float) rectangle.getMinY()));
assertThat(geometry, equalTo(LuceneGeometriesUtils.toXYRectangle(rectangle)));
}
public void testLatLonCircle() {
Circle circle = GeometryTestUtils.randomCircle(randomBoolean());
LatLonGeometry[] geometries = LuceneGeometriesUtils.toLatLonGeometry(circle, false, t -> assertEquals(ShapeType.CIRCLE, t));
assertEquals(1, geometries.length);
assertLatLonCircle(circle, geometries[0]);
}
private void assertLatLonCircle(Circle circle, LatLonGeometry geometry) {
assertThat(geometry, instanceOf(org.apache.lucene.geo.Circle.class));
org.apache.lucene.geo.Circle lalonCircle = (org.apache.lucene.geo.Circle) geometry;
assertThat(lalonCircle.getLon(), equalTo(circle.getLon()));
assertThat(lalonCircle.getLat(), equalTo(circle.getLat()));
assertThat(lalonCircle.getRadius(), equalTo(circle.getRadiusMeters()));
assertThat(geometry, equalTo(LuceneGeometriesUtils.toLatLonCircle(circle)));
}
public void testXYCircle() {
Circle circle = ShapeTestUtils.randomCircle(randomBoolean());
XYGeometry[] geometries = LuceneGeometriesUtils.toXYGeometry(circle, t -> assertEquals(ShapeType.CIRCLE, t));
assertEquals(1, geometries.length);
assertXYCircle(circle, geometries[0]);
}
private void assertXYCircle(Circle circle, XYGeometry geometry) {
assertThat(geometry, instanceOf(org.apache.lucene.geo.XYCircle.class));
org.apache.lucene.geo.XYCircle xyCircle = (org.apache.lucene.geo.XYCircle) geometry;
assertThat(xyCircle.getX(), equalTo((float) circle.getX()));
assertThat(xyCircle.getY(), equalTo((float) circle.getY()));
assertThat(xyCircle.getRadius(), equalTo((float) circle.getRadiusMeters()));
assertThat(geometry, equalTo(LuceneGeometriesUtils.toXYCircle(circle)));
}
private MultiPolygon validRandomMultiPolygon(boolean hasLat) {
// make sure we don't generate a polygon that gets splitted across the dateline
return randomValueOtherThanMany(
multiPolygon -> GeometryNormalizer.needsNormalize(Orientation.CCW, multiPolygon),
() -> GeometryTestUtils.randomMultiPolygon(hasLat)
);
}
private Point quantize(Point point) {
return new Point(GeoUtils.quantizeLon(point.getLon()), GeoUtils.quantizeLat(point.getLat()));
}
private Line quantize(Line line) {
return new Line(
LuceneGeometriesUtils.LATLON_QUANTIZER.quantizeLons(line.getLons()),
LuceneGeometriesUtils.LATLON_QUANTIZER.quantizeLats(line.getLats())
);
}
private Polygon quantize(Polygon polygon) {
List<LinearRing> holes = new ArrayList<>(polygon.getNumberOfHoles());
for (int i = 0; i < polygon.getNumberOfHoles(); i++) {
holes.add(quantize(polygon.getHole(i)));
}
return new Polygon(quantize(polygon.getPolygon()), holes);
}
private LinearRing quantize(LinearRing linearRing) {
return new LinearRing(
LuceneGeometriesUtils.LATLON_QUANTIZER.quantizeLons(linearRing.getLons()),
LuceneGeometriesUtils.LATLON_QUANTIZER.quantizeLats(linearRing.getLats())
);
}
}
| LuceneGeometriesUtilsTests |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/model/PropertyMapping.java | {
"start": 3795,
"end": 4338
} | class ____ extends ModelElement {
private final String name;
private final String sourcePropertyName;
private final String sourceBeanName;
private final String targetWriteAccessorName;
private final ReadAccessor targetReadAccessorProvider;
private final Type targetType;
private final Assignment assignment;
private final Set<String> dependsOn;
private final Assignment defaultValueAssignment;
private final boolean constructorMapping;
@SuppressWarnings("unchecked")
private static | PropertyMapping |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/permission/ClusterPermission.java | {
"start": 8821,
"end": 10125
} | class ____ implements PermissionCheck {
private final Automaton automaton;
private final Predicate<String> actionPredicate;
public ActionBasedPermissionCheck(final Automaton automaton) {
this.automaton = automaton;
this.actionPredicate = Automatons.predicate(automaton);
}
@Override
public final boolean check(final String action, final TransportRequest request, final Authentication authentication) {
return actionPredicate.test(action) && extendedCheck(action, request, authentication);
}
protected abstract boolean extendedCheck(String action, TransportRequest request, Authentication authentication);
@Override
public final boolean implies(final PermissionCheck permissionCheck) {
if (permissionCheck instanceof ActionBasedPermissionCheck) {
return Automatons.subsetOf(((ActionBasedPermissionCheck) permissionCheck).automaton, this.automaton)
&& doImplies((ActionBasedPermissionCheck) permissionCheck);
}
return false;
}
protected abstract boolean doImplies(ActionBasedPermissionCheck permissionCheck);
}
// Automaton based permission check
private static | ActionBasedPermissionCheck |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/RequestEntity.java | {
"start": 6072,
"end": 14202
} | enum ____
*/
public @Nullable HttpMethod getMethod() {
return this.method;
}
/**
* Return the {@link URI} for the target HTTP endpoint.
* <p><strong>Note:</strong> This method raises
* {@link UnsupportedOperationException} if the {@code RequestEntity} was
* created with a URI template and variables rather than with a {@link URI}
* instance. This is because a URI cannot be created without further input
* on how to expand template and encode the URI. In such cases, the
* {@code URI} is prepared by the
* {@link org.springframework.web.client.RestTemplate} with the help of the
* {@link org.springframework.web.util.UriTemplateHandler} it is configured with.
*/
public URI getUrl() {
if (this.url == null) {
throw new UnsupportedOperationException(
"The RequestEntity was created with a URI template and variables, " +
"and there is not enough information on how to correctly expand and " +
"encode the URI template. This will be done by the RestTemplate instead " +
"with help from the UriTemplateHandler it is configured with.");
}
return this.url;
}
/**
* Return the type of the request's body.
* @return the request's body type, or {@code null} if not known
* @since 4.3
*/
public @Nullable Type getType() {
if (this.type == null) {
T body = getBody();
if (body != null) {
return body.getClass();
}
}
return this.type;
}
@Override
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (!super.equals(other)) {
return false;
}
return (other instanceof RequestEntity<?> otherEntity &&
ObjectUtils.nullSafeEquals(this.method, otherEntity.method) &&
ObjectUtils.nullSafeEquals(this.url, otherEntity.url));
}
@Override
public int hashCode() {
int hashCode = super.hashCode();
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.method);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.url);
return hashCode;
}
@Override
public String toString() {
return format(getMethod(), getUrl().toString(), getBody(), getHeaders());
}
static <T> String format(@Nullable HttpMethod httpMethod, String url, @Nullable T body, HttpHeaders headers) {
StringBuilder builder = new StringBuilder("<");
builder.append(httpMethod);
builder.append(' ');
builder.append(url);
builder.append(',');
if (body != null) {
builder.append(body);
builder.append(',');
}
builder.append(headers);
builder.append('>');
return builder.toString();
}
// Static builder methods
/**
* Create a builder with the given method and url.
* @param method the HTTP method (GET, POST, etc)
* @param url the URL
* @return the created builder
*/
public static BodyBuilder method(HttpMethod method, URI url) {
return new DefaultBodyBuilder(method, url);
}
/**
* Create a builder with the given HTTP method, URI template, and variables.
* @param method the HTTP method (GET, POST, etc)
* @param uriTemplate the uri template to use
* @param uriVariables variables to expand the URI template with
* @return the created builder
* @since 5.3
*/
public static BodyBuilder method(HttpMethod method, String uriTemplate, @Nullable Object... uriVariables) {
return new DefaultBodyBuilder(method, uriTemplate, uriVariables);
}
/**
* Create a builder with the given HTTP method, URI template, and variables.
* @param method the HTTP method (GET, POST, etc)
* @param uriTemplate the uri template to use
* @return the created builder
* @since 5.3
*/
public static BodyBuilder method(HttpMethod method, String uriTemplate, Map<String, ?> uriVariables) {
return new DefaultBodyBuilder(method, uriTemplate, uriVariables);
}
/**
* Create an HTTP GET builder with the given url.
* @param url the URL
* @return the created builder
*/
public static HeadersBuilder<?> get(URI url) {
return method(HttpMethod.GET, url);
}
/**
* Create an HTTP GET builder with the given string base uri template.
* @param uriTemplate the uri template to use
* @param uriVariables variables to expand the URI template with
* @return the created builder
* @since 5.3
*/
public static HeadersBuilder<?> get(String uriTemplate, @Nullable Object... uriVariables) {
return method(HttpMethod.GET, uriTemplate, uriVariables);
}
/**
* Create an HTTP HEAD builder with the given url.
* @param url the URL
* @return the created builder
*/
public static HeadersBuilder<?> head(URI url) {
return method(HttpMethod.HEAD, url);
}
/**
* Create an HTTP HEAD builder with the given string base uri template.
* @param uriTemplate the uri template to use
* @param uriVariables variables to expand the URI template with
* @return the created builder
* @since 5.3
*/
public static HeadersBuilder<?> head(String uriTemplate, @Nullable Object... uriVariables) {
return method(HttpMethod.HEAD, uriTemplate, uriVariables);
}
/**
* Create an HTTP POST builder with the given url.
* @param url the URL
* @return the created builder
*/
public static BodyBuilder post(URI url) {
return method(HttpMethod.POST, url);
}
/**
* Create an HTTP POST builder with the given string base uri template.
* @param uriTemplate the uri template to use
* @param uriVariables variables to expand the URI template with
* @return the created builder
* @since 5.3
*/
public static BodyBuilder post(String uriTemplate, @Nullable Object... uriVariables) {
return method(HttpMethod.POST, uriTemplate, uriVariables);
}
/**
* Create an HTTP PUT builder with the given url.
* @param url the URL
* @return the created builder
*/
public static BodyBuilder put(URI url) {
return method(HttpMethod.PUT, url);
}
/**
* Create an HTTP PUT builder with the given string base uri template.
* @param uriTemplate the uri template to use
* @param uriVariables variables to expand the URI template with
* @return the created builder
* @since 5.3
*/
public static BodyBuilder put(String uriTemplate, @Nullable Object... uriVariables) {
return method(HttpMethod.PUT, uriTemplate, uriVariables);
}
/**
* Create an HTTP PATCH builder with the given url.
* @param url the URL
* @return the created builder
*/
public static BodyBuilder patch(URI url) {
return method(HttpMethod.PATCH, url);
}
/**
* Create an HTTP PATCH builder with the given string base uri template.
* @param uriTemplate the uri template to use
* @param uriVariables variables to expand the URI template with
* @return the created builder
* @since 5.3
*/
public static BodyBuilder patch(String uriTemplate, @Nullable Object... uriVariables) {
return method(HttpMethod.PATCH, uriTemplate, uriVariables);
}
/**
* Create an HTTP DELETE builder with the given url.
* @param url the URL
* @return the created builder
*/
public static HeadersBuilder<?> delete(URI url) {
return method(HttpMethod.DELETE, url);
}
/**
* Create an HTTP DELETE builder with the given string base uri template.
* @param uriTemplate the uri template to use
* @param uriVariables variables to expand the URI template with
* @return the created builder
* @since 5.3
*/
public static HeadersBuilder<?> delete(String uriTemplate, @Nullable Object... uriVariables) {
return method(HttpMethod.DELETE, uriTemplate, uriVariables);
}
/**
* Creates an HTTP OPTIONS builder with the given url.
* @param url the URL
* @return the created builder
*/
public static HeadersBuilder<?> options(URI url) {
return method(HttpMethod.OPTIONS, url);
}
/**
* Creates an HTTP OPTIONS builder with the given string base uri template.
* @param uriTemplate the uri template to use
* @param uriVariables variables to expand the URI template with
* @return the created builder
* @since 5.3
*/
public static HeadersBuilder<?> options(String uriTemplate, @Nullable Object... uriVariables) {
return method(HttpMethod.OPTIONS, uriTemplate, uriVariables);
}
/**
* Defines a builder that adds headers to the request entity.
* @param <B> the builder subclass
*/
public | value |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/router/async/TestRouterAsyncMountTable.java | {
"start": 1561,
"end": 2794
} | class ____ extends TestRouterMountTable {
public static final Logger LOG = LoggerFactory.getLogger(TestRouterAsyncMountTable.class);
@BeforeAll
public static void globalSetUp() throws Exception {
startTime = Time.now();
// Build and start a federated cluster.
cluster = new StateStoreDFSCluster(false, 2);
Configuration conf = new RouterConfigBuilder()
.stateStore()
.admin()
.rpc()
.build();
conf.setInt(RBFConfigKeys.DFS_ROUTER_ADMIN_MAX_COMPONENT_LENGTH_KEY, 20);
conf.setBoolean(RBFConfigKeys.DFS_ROUTER_ASYNC_RPC_ENABLE_KEY, true);
cluster.addRouterOverrides(conf);
cluster.startCluster();
cluster.startRouters();
cluster.waitClusterUp();
// Get the end points.
nnContext0 = cluster.getNamenode("ns0", null);
nnContext1 = cluster.getNamenode("ns1", null);
nnFs0 = nnContext0.getFileSystem();
nnFs1 = nnContext1.getFileSystem();
routerContext = cluster.getRandomRouter();
routerFs = routerContext.getFileSystem();
Router router = routerContext.getRouter();
routerProtocol = routerContext.getClient().getNamenode();
mountTable = (MountTableResolver) router.getSubclusterResolver();
}
}
| TestRouterAsyncMountTable |
java | apache__flink | flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/MountSecretsDecoratorTest.java | {
"start": 1281,
"end": 3152
} | class ____ extends KubernetesJobManagerTestBase {
private static final String SECRET_NAME = "test";
private static final String SECRET_MOUNT_PATH = "/opt/flink/secret";
private MountSecretsDecorator mountSecretsDecorator;
@Override
protected void setupFlinkConfig() {
super.setupFlinkConfig();
this.flinkConfig.setString(
KubernetesConfigOptions.KUBERNETES_SECRETS.key(),
SECRET_NAME + ":" + SECRET_MOUNT_PATH);
}
@Override
protected void onSetup() throws Exception {
super.onSetup();
this.mountSecretsDecorator = new MountSecretsDecorator(kubernetesJobManagerParameters);
}
@Test
void testWhetherPodOrContainerIsDecorated() {
final FlinkPod resultFlinkPod = mountSecretsDecorator.decorateFlinkPod(baseFlinkPod);
assertThat(
VolumeTestUtils.podHasVolume(
baseFlinkPod.getPodWithoutMainContainer(), SECRET_NAME + "-volume"))
.isFalse();
assertThat(
VolumeTestUtils.podHasVolume(
resultFlinkPod.getPodWithoutMainContainer(),
SECRET_NAME + "-volume"))
.isTrue();
assertThat(
VolumeTestUtils.containerHasVolume(
baseFlinkPod.getMainContainer(),
SECRET_NAME + "-volume",
SECRET_MOUNT_PATH))
.isFalse();
assertThat(
VolumeTestUtils.containerHasVolume(
resultFlinkPod.getMainContainer(),
SECRET_NAME + "-volume",
SECRET_MOUNT_PATH))
.isTrue();
}
}
| MountSecretsDecoratorTest |
java | apache__flink | flink-core/src/main/java/org/apache/flink/core/memory/DataInputView.java | {
"start": 1186,
"end": 2834
} | interface ____ extends DataInput {
/**
* Skips {@code numBytes} bytes of memory. In contrast to the {@link #skipBytes(int)} method,
* this method always skips the desired number of bytes or throws an {@link
* java.io.EOFException}.
*
* @param numBytes The number of bytes to skip.
* @throws IOException Thrown, if any I/O related problem occurred such that the input could not
* be advanced to the desired position.
*/
void skipBytesToRead(int numBytes) throws IOException;
/**
* Reads up to {@code len} bytes of memory and stores it into {@code b} starting at offset
* {@code off}.
*
* <p>If <code>len</code> is zero, then no bytes are read and <code>0</code> is returned;
* otherwise, there is an attempt to read at least one byte. If there is no more data left, the
* value <code>-1</code> is returned; otherwise, at least one byte is read and stored into
* <code>b</code>.
*
* @param b byte array to store the data to
* @param off offset into byte array
* @param len byte length to read
* @return the number of actually read bytes of -1 if there is no more data left
* @throws IOException
*/
int read(byte[] b, int off, int len) throws IOException;
/**
* Tries to fill the given byte array {@code b}. Returns the actually number of read bytes or -1
* if there is no more data.
*
* @param b byte array to store the data to
* @return the number of read bytes or -1 if there is no more data left
* @throws IOException
*/
int read(byte[] b) throws IOException;
}
| DataInputView |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/error/ShouldBeAssignableTo_create_Test.java | {
"start": 1094,
"end": 1685
} | class ____ {
@Test
void should_create_error_message() {
// GIVEN
ErrorMessageFactory factory = shouldBeAssignableTo(List.class, ArrayList.class);
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n"
+ "Expecting%n"
+ " java.util.List%n"
+ "to be assignable to:%n"
+ " java.util.ArrayList"));
}
}
| ShouldBeAssignableTo_create_Test |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/MultipleParallelOrSequentialCallsTest.java | {
"start": 13031,
"end": 16926
} | class ____ {
public void basicCaseParallel(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().parallel();'?
list.stream().parallel();
}
public void basicCaseParallelNotFirst(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().parallel().map(m -> m);'?
list.stream().parallel().map(m -> m);
}
public void basicCollection(Collection<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().parallel();'?
list.stream().parallel();
}
public void parallelStream(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.parallelStream();'?
list.parallelStream();
}
public void basicCaseParallelThisInMethodArg(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'this.hello(list.stream().parallel());'?
this.hello(list.stream().parallel());
}
public void onlyOneError(List<String> list) {
this.hello(
// BUG: Diagnostic contains: Multiple calls
list.stream().parallel());
}
public void mapMethod(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'hello(list.stream().parallel().map(m ->
// this.hello(null)));'?
hello(list.stream().parallel().map(m -> this.hello(null)));
}
public void betweenMethods(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().parallel().map(m -> m.toString());'?
list.stream().parallel().map(m -> m.toString());
}
public void basicCaseParallelNotLast(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().parallel().map(m ->
// m.toString()).findFirst();'?
list.stream().parallel().map(m -> m.toString()).findFirst();
}
public void basicCaseSequential(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().sequential().map(m -> m.toString());'?
list.stream().sequential().map(m -> m.toString());
}
public void bothSequentialAndParallel(List<String> list) {
// this case is unlikely (wrong, even) but just checking that this works
// BUG: Diagnostic contains: Did you mean 'list.stream().sequential().parallel();'?
list.stream().sequential().parallel();
}
public void bothSequentialAndParallelMultiple(List<String> list) {
// this is even more messed up, this test is here to make sure the checker doesn't throw an
// exception
// BUG: Diagnostic contains: Multiple calls
list.stream().sequential().parallel().parallel();
}
public void parallelMultipleLines(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.stream().parallel()
list.stream().parallel().map(m -> m.toString());
}
public void multipleParallelCalls(List<String> list) {
// BUG: Diagnostic contains: Did you mean 'list.parallelStream();'?
list.parallelStream();
}
public String hello(Stream st) {
return "";
}
public void streamWithinAStream(List<String> list, List<String> list2) {
// BUG: Diagnostic contains: Did you mean
list.stream().parallel().flatMap(childDir -> list2.stream()).flatMap(a -> list2.stream());
}
public void streamWithinAStreamImmediatelyAfterOtherParallel(
List<String> list, List<String> list2) {
// BUG: Diagnostic contains: Did you mean
list.stream().parallel().map(m -> list2.stream().parallel());
}
public void parallelAndNestedStreams(List<String> list, List<String> list2) {
// BUG: Diagnostic contains: Did you mean
list.parallelStream()
.flatMap(childDir -> list2.stream())
.filter(m -> (new TestClass("test")).testClass())
.map(
a -> {
if (a == null) {
return a;
}
return null;
})
.filter(a -> a != null)
.flatMap(a -> list2.stream());
}
private | MultipleParallelOrSequentialCallsPositiveCases |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/MaxBytesRefAggregator.java | {
"start": 3794,
"end": 5270
} | class ____ implements AggregatorState {
private final BreakingBytesRefBuilder internalState;
private boolean seen;
private SingleState(CircuitBreaker breaker) {
this.internalState = new BreakingBytesRefBuilder(breaker, "max_bytes_ref_aggregator");
this.seen = false;
}
public void add(BytesRef value) {
if (seen == false || isBetter(value, internalState.bytesRefView())) {
seen = true;
internalState.grow(value.length);
internalState.setLength(value.length);
System.arraycopy(value.bytes, value.offset, internalState.bytes(), 0, value.length);
}
}
@Override
public void toIntermediate(Block[] blocks, int offset, DriverContext driverContext) {
blocks[offset] = driverContext.blockFactory().newConstantBytesRefBlockWith(internalState.bytesRefView(), 1);
blocks[offset + 1] = driverContext.blockFactory().newConstantBooleanBlockWith(seen, 1);
}
Block toBlock(DriverContext driverContext) {
if (seen == false) {
return driverContext.blockFactory().newConstantNullBlock(1);
}
return driverContext.blockFactory().newConstantBytesRefBlockWith(internalState.bytesRefView(), 1);
}
@Override
public void close() {
Releasables.close(internalState);
}
}
}
| SingleState |
java | grpc__grpc-java | core/src/main/java/io/grpc/internal/ExponentialBackoffPolicy.java | {
"start": 1118,
"end": 2911
} | class ____ implements BackoffPolicy.Provider {
@Override
public BackoffPolicy get() {
return new ExponentialBackoffPolicy();
}
}
private Random random = new Random();
private long initialBackoffNanos = TimeUnit.SECONDS.toNanos(1);
private long maxBackoffNanos = TimeUnit.MINUTES.toNanos(2);
private double multiplier = 1.6;
private double jitter = .2;
private long nextBackoffNanos = initialBackoffNanos;
@Override
public long nextBackoffNanos() {
long currentBackoffNanos = nextBackoffNanos;
nextBackoffNanos = Math.min((long) (currentBackoffNanos * multiplier), maxBackoffNanos);
return currentBackoffNanos
+ uniformRandom(-jitter * currentBackoffNanos, jitter * currentBackoffNanos);
}
private long uniformRandom(double low, double high) {
checkArgument(high >= low);
double mag = high - low;
return (long) (random.nextDouble() * mag + low);
}
/*
* No guice and no flags means we get to implement these setters for testing ourselves. Do not
* call these from non-test code.
*/
@VisibleForTesting
ExponentialBackoffPolicy setRandom(Random random) {
this.random = random;
return this;
}
@VisibleForTesting
ExponentialBackoffPolicy setInitialBackoffNanos(long initialBackoffNanos) {
this.initialBackoffNanos = initialBackoffNanos;
return this;
}
@VisibleForTesting
ExponentialBackoffPolicy setMaxBackoffNanos(long maxBackoffNanos) {
this.maxBackoffNanos = maxBackoffNanos;
return this;
}
@VisibleForTesting
ExponentialBackoffPolicy setMultiplier(double multiplier) {
this.multiplier = multiplier;
return this;
}
@VisibleForTesting
ExponentialBackoffPolicy setJitter(double jitter) {
this.jitter = jitter;
return this;
}
}
| Provider |
java | quarkusio__quarkus | tcks/microprofile-opentelemetry/src/test/java/io/quarkus/tck/opentelemetry/TestApplication.java | {
"start": 1864,
"end": 2000
} | class ____ {
public String hello() {
return "hello";
}
}
@ApplicationScoped
public static | HelloBean |
java | grpc__grpc-java | core/src/main/java/io/grpc/internal/ServerImpl.java | {
"start": 3056,
"end": 3516
} | class ____ {
* public static Server newServer(Executor executor, HandlerRegistry registry,
* String configuration) {
* return new ServerImpl(executor, registry, new TcpTransportServer(configuration));
* }
* }</code></pre>
*
* <p>Starting the server starts the underlying transport for servicing requests. Stopping the
* server stops servicing new requests and waits for all connections to terminate.
*/
public final | TcpTransportServerFactory |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/bean/issues/SingleMethodServiceImpl.java | {
"start": 859,
"end": 1044
} | class ____ extends SingleMethodAbstractService<String, String> {
@Override
public String doSomething(String foo) {
return "You said " + foo;
}
}
| SingleMethodServiceImpl |
java | playframework__playframework | documentation/manual/working/javaGuide/main/i18n/code/javaguide/i18n/MyService.java | {
"start": 564,
"end": 863
} | class ____ {
private final Langs langs;
@Inject
LangOps(Langs langs) {
this.langs = langs;
}
public void ops() {
Lang lang = langs.availables().get(0);
// #lang-to-locale
java.util.Locale locale = lang.toLocale();
// #lang-to-locale
}
}
// #current-lang-render
| LangOps |
java | google__guice | core/src/com/google/inject/internal/InternalFactoryToScopedProviderAdapter.java | {
"start": 4848,
"end": 7683
} | class ____<T> extends InternalFactoryToScopedProviderAdapter<T> {
private static final Object UNINITIALIZED_VALUE = new Object();
// Cache the values here so we can optimize the behavior of Provider instances.
// We do not use a lock but rather a volatile field to safely publish values. This means we
// might compute the value multiple times, but we rely on internal synchronization inside the
// singleton scope to ensure that we only compute the value once.
// See https://github.com/google/guice/issues/1802 for more details.
@LazyInit private volatile Object value = UNINITIALIZED_VALUE;
ForSingletonScope(Provider<? extends T> provider, Object source) {
super(provider, source);
}
@Override
public T get(InternalContext context, Dependency<?> dependency, boolean linked)
throws InternalProvisionException {
Object value = this.value;
if (value != UNINITIALIZED_VALUE) {
// safe because we only store values of T or UNINITIALIZED_VALUE
@SuppressWarnings("unchecked")
T typedValue = (T) value;
if (typedValue == null && !dependency.isNullable()) {
InternalProvisionException.onNullInjectedIntoNonNullableDependency(source, dependency);
}
return typedValue;
}
T t = super.get(context, dependency, linked);
if (!context.areCircularProxiesEnabled() || !BytecodeGen.isCircularProxy(t)) {
// Avoid caching circular proxies.
this.value = t;
}
return t;
}
@Override
MethodHandleResult makeHandle(LinkageContext context, boolean linked) {
// If it is somehow already initialized, we can return a constant handle.
Object value = this.value;
if (value != UNINITIALIZED_VALUE) {
return makeCachable(getHandleForConstant(source, value));
}
// Otherwise we bind to a callsite that will patch itself once it is initialized.
var result = super.makeHandle(context, linked);
checkState(result.cachability == MethodHandleResult.Cachability.ALWAYS);
return makeCachable(new SingletonCallSite(result.methodHandle, source).dynamicInvoker());
}
private static MethodHandle getHandleForConstant(Object source, Object value) {
var handle = InternalMethodHandles.constantFactoryGetHandle(value);
// Since this is a constant, we only need to null check if it is actually null.
if (value == null) {
handle = InternalMethodHandles.nullCheckResult(handle, source);
}
return handle;
}
/**
* A special callsite that allows us to take advantage of the singleton scope semantics.
*
* <p>After initialization we can patch the callsite with a constant, which should unlock some
* inlining opportunities.
*/
static final | ForSingletonScope |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/JacksonJsonView.java | {
"start": 2133,
"end": 6527
} | class ____ extends AbstractJacksonView {
/**
* Default content type: {@value}.
* <p>Overridable through {@link #setContentType(String)}.
*/
public static final String DEFAULT_CONTENT_TYPE = "application/json";
private @Nullable String jsonPrefix;
private @Nullable Set<String> modelKeys;
private boolean extractValueFromSingleKeyModel = false;
/**
* Construct a new instance with a {@link JsonMapper} customized with
* the {@link tools.jackson.databind.JacksonModule}s found by
* {@link MapperBuilder#findModules(ClassLoader)} and setting
* the content type to {@code application/json}.
*/
public JacksonJsonView() {
super(JsonMapper.builder(), DEFAULT_CONTENT_TYPE);
}
/**
* Construct a new instance using the provided {@link JsonMapper.Builder}
* customized with the {@link tools.jackson.databind.JacksonModule}s
* found by {@link MapperBuilder#findModules(ClassLoader)} and setting
* the content type to {@code application/json}.
* @see JsonMapper#builder()
*/
public JacksonJsonView(JsonMapper.Builder builder) {
super(builder, DEFAULT_CONTENT_TYPE);
}
/**
* Construct a new instance using the provided {@link JsonMapper}
* and setting the content type to {@value #DEFAULT_CONTENT_TYPE}.
* @see JsonMapper#builder()
*/
public JacksonJsonView(JsonMapper mapper) {
super(mapper, DEFAULT_CONTENT_TYPE);
}
/**
* Specify a custom prefix to use for this view's JSON output.
* <p>Default is none.
* @see #setPrefixJson
*/
public void setJsonPrefix(String jsonPrefix) {
this.jsonPrefix = jsonPrefix;
}
/**
* Indicates whether the JSON output by this view should be prefixed with <code>")]}', "</code>.
* <p>Default is {@code false}.
* <p>Prefixing the JSON string in this manner is used to help prevent JSON Hijacking.
* The prefix renders the string syntactically invalid as a script so that it cannot be hijacked.
* This prefix should be stripped before parsing the string as JSON.
* @see #setJsonPrefix
*/
public void setPrefixJson(boolean prefixJson) {
this.jsonPrefix = (prefixJson ? ")]}', " : null);
}
@Override
public void setModelKey(String modelKey) {
this.modelKeys = Collections.singleton(modelKey);
}
/**
* Set the attributes in the model that should be rendered by this view.
* <p>When set, all other model attributes will be ignored.
*/
public void setModelKeys(@Nullable Set<String> modelKeys) {
this.modelKeys = modelKeys;
}
/**
* Return the attributes in the model that should be rendered by this view.
*/
public final @Nullable Set<String> getModelKeys() {
return this.modelKeys;
}
/**
* Set whether to serialize models containing a single attribute as a map or
* whether to extract the single value from the model and serialize it directly.
* <p>The effect of setting this flag is similar to using
* {@code JacksonJsonHttpMessageConverter} with an {@code @ResponseBody}
* request-handling method.
* <p>Default is {@code false}.
*/
public void setExtractValueFromSingleKeyModel(boolean extractValueFromSingleKeyModel) {
this.extractValueFromSingleKeyModel = extractValueFromSingleKeyModel;
}
/**
* Filter out undesired attributes from the given model.
* <p>The return value can be either another {@link Map} or a single value object.
* <p>The default implementation removes {@link BindingResult} instances and entries
* not included in the {@link #setModelKeys modelKeys} property.
* @param model the model, as passed on to {@link #renderMergedOutputModel}
* @return the value to be rendered
*/
@Override
protected Object filterModel(Map<String, Object> model, HttpServletRequest request) {
Map<String, Object> result = CollectionUtils.newHashMap(model.size());
Set<String> modelKeys = (!CollectionUtils.isEmpty(this.modelKeys) ? this.modelKeys : model.keySet());
model.forEach((clazz, value) -> {
if (!(value instanceof BindingResult) && modelKeys.contains(clazz) &&
!clazz.equals(JSON_VIEW_HINT) &&
!clazz.equals(FILTER_PROVIDER_HINT)) {
result.put(clazz, value);
}
});
return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result);
}
@Override
protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
if (this.jsonPrefix != null) {
generator.writeRaw(this.jsonPrefix);
}
}
}
| JacksonJsonView |
java | google__auto | value/src/test/java/com/google/auto/value/processor/AutoBuilderCompilationTest.java | {
"start": 33692,
"end": 34695
} | interface ____ {",
" abstract Builder up(int x);",
" abstract Builder down(String x);",
" abstract Baz build();",
" }",
"}");
Compilation compilation =
javac().withProcessors(new AutoBuilderProcessor()).compile(javaFileObject);
assertThat(compilation).failed();
assertThat(compilation)
.hadErrorContaining(
"[AutoBuilderGetVsSet] Parameter type java.lang.String of setter method should be int"
+ " to match parameter \"down\" of Baz(int up, int down)")
.inFile(javaFileObject)
.onLineContaining("down(String x)");
}
@Test
public void setterWrongTypeEvenWithConversion() {
JavaFileObject javaFileObject =
JavaFileObjects.forSourceLines(
"foo.bar.Baz",
"package foo.bar;",
"",
"import com.google.auto.value.AutoBuilder;",
"import java.util.Optional;",
"",
" | Builder |
java | apache__camel | components/camel-csimple-joor/src/test/java/org/apache/camel/language/csimple/joor/OriginalSimpleOperatorTest.java | {
"start": 1217,
"end": 34917
} | class ____ extends LanguageTestSupport {
@BindToRegistry
private MyFileNameGenerator generator = new MyFileNameGenerator();
@Test
public void testValueWithSpace() {
exchange.getIn().setBody("Hello Big World");
assertPredicate("${in.body} == 'Hello Big World'", true);
}
@Test
public void testNullValue() {
exchange.getIn().setBody("Value");
assertPredicate("${in.body} != null", true);
assertPredicate("${body} == null", false);
exchange.getIn().setBody(null);
assertPredicate("${in.body} == null", true);
assertPredicate("${body} != null", false);
}
@Test
public void testEmptyValue() {
exchange.getIn().setBody("");
assertPredicate("${in.body} == null", false);
assertPredicate("${body} == null", false);
exchange.getIn().setBody("");
assertPredicate("${in.body} == ''", true);
assertPredicate("${body} == \"\"", true);
exchange.getIn().setBody(" ");
assertPredicate("${in.body} == ''", false);
assertPredicate("${body} == \"\"", false);
exchange.getIn().setBody("Value");
assertPredicate("${in.body} == ''", false);
assertPredicate("${body} == \"\"", false);
}
@Test
public void testAnd() {
assertPredicate("${in.header.foo} == 'abc' && ${in.header.bar} == 123", true);
assertPredicate("${in.header.foo} == 'abc' && ${in.header.bar} == 444", false);
assertPredicate("${in.header.foo} == 'def' && ${in.header.bar} == 123", false);
assertPredicate("${in.header.foo} == 'def' && ${in.header.bar} == 444", false);
assertPredicate("${in.header.foo} == 'abc' && ${in.header.bar} > 100", true);
assertPredicate("${in.header.foo} == 'abc' && ${in.header.bar} < 200", true);
}
@Test
public void testTwoAnd() {
exchange.getIn().setBody("Hello World");
assertPredicate("${in.header.foo} == 'abc' && ${in.header.bar} == 123 && ${body} == 'Hello World'", true);
assertPredicate("${in.header.foo} == 'abc' && ${in.header.bar} == 123 && ${body} == 'Bye World'", false);
}
@Test
public void testThreeAnd() {
exchange.getIn().setBody("Hello World");
assertPredicate(
"${in.header.foo} == 'abc' && ${in.header.bar} == 123 && ${body} == 'Hello World' && ${in.header.xx} == null",
true);
}
@Test
public void testTwoOr() {
exchange.getIn().setBody("Hello World");
assertPredicate("${in.header.foo} == 'abc' || ${in.header.bar} == 44 || ${body} == 'Bye World'", true);
assertPredicate("${in.header.foo} == 'xxx' || ${in.header.bar} == 44 || ${body} == 'Bye World'", false);
assertPredicate("${in.header.foo} == 'xxx' || ${in.header.bar} == 44 || ${body} == 'Hello World'", true);
assertPredicate("${in.header.foo} == 'xxx' || ${in.header.bar} == 123 || ${body} == 'Bye World'", true);
}
@Test
public void testThreeOr() {
exchange.getIn().setBody("Hello World");
assertPredicate(
"${in.header.foo} == 'xxx' || ${in.header.bar} == 44 || ${body} == 'Bye Moon' || ${body} contains 'World'",
true);
assertPredicate(
"${in.header.foo} == 'xxx' || ${in.header.bar} == 44 || ${body} == 'Bye Moon' || ${body} contains 'Moon'",
false);
assertPredicate(
"${in.header.foo} == 'abc' || ${in.header.bar} == 44 || ${body} == 'Bye Moon' || ${body} contains 'Moon'",
true);
assertPredicate(
"${in.header.foo} == 'xxx' || ${in.header.bar} == 123 || ${body} == 'Bye Moon' || ${body} contains 'Moon'",
true);
assertPredicate(
"${in.header.foo} == 'xxx' || ${in.header.bar} == 44 || ${body} == 'Hello World' || ${body} contains 'Moon'",
true);
}
@Test
public void testAndWithQuotation() {
assertPredicate("${in.header.foo} == 'abc' && ${in.header.bar} == '123'", true);
assertPredicate("${in.header.foo} == 'abc' && ${in.header.bar} == '444'", false);
assertPredicate("${in.header.foo} == 'def' && ${in.header.bar} == '123'", false);
assertPredicate("${in.header.foo} == 'def' && ${in.header.bar} == '444'", false);
assertPredicate("${in.header.foo} == 'abc' && ${in.header.bar} > '100'", true);
assertPredicate("${in.header.foo} == 'abc' && ${in.header.bar} < '200'", true);
}
@Test
public void testOr() {
assertPredicate("${in.header.foo} == 'abc' || ${in.header.bar} == 123", true);
assertPredicate("${in.header.foo} == 'abc' || ${in.header.bar} == 444", true);
assertPredicate("${in.header.foo} == 'def' || ${in.header.bar} == 123", true);
assertPredicate("${in.header.foo} == 'def' || ${in.header.bar} == 444", false);
assertPredicate("${in.header.foo} == 'abc' || ${in.header.bar} < 100", true);
assertPredicate("${in.header.foo} == 'abc' || ${in.header.bar} < 200", true);
assertPredicate("${in.header.foo} == 'def' || ${in.header.bar} < 200", true);
assertPredicate("${in.header.foo} == 'def' || ${in.header.bar} < 100", false);
}
@Test
public void testOrWithQuotation() {
assertPredicate("${in.header.foo} == 'abc' || ${in.header.bar} == '123'", true);
assertPredicate("${in.header.foo} == 'abc' || ${in.header.bar} == '444'", true);
assertPredicate("${in.header.foo} == 'def' || ${in.header.bar} == '123'", true);
assertPredicate("${in.header.foo} == 'def' || ${in.header.bar} == '444'", false);
assertPredicate("${in.header.foo} == 'abc' || ${in.header.bar} < '100'", true);
assertPredicate("${in.header.foo} == 'abc' || ${in.header.bar} < '200'", true);
assertPredicate("${in.header.foo} == 'def' || ${in.header.bar} < '200'", true);
assertPredicate("${in.header.foo} == 'def' || ${in.header.bar} < '100'", false);
}
@Test
public void testEqualOperator() {
// string to string comparison
assertPredicate("${in.header.foo} == 'abc'", true);
assertPredicate("${in.header.foo} == 'def'", false);
assertPredicate("${in.header.foo} == '1'", false);
// boolean to boolean comparison
exchange.getIn().setHeader("bool", true);
exchange.getIn().setHeader("booley", false);
assertPredicate("${in.header.bool} == true", true);
assertPredicate("${in.header.bool} == 'true'", true);
assertPredicate("${in.header.booley} == false", true);
assertPredicate("${in.header.booley} == 'false'", true);
// integer to string comparison
assertPredicate("${in.header.bar} == '123'", true);
assertPredicate("${in.header.bar} == 123", true);
assertPredicate("${in.header.bar} == '444'", false);
assertPredicate("${in.header.bar} == 444", false);
assertPredicate("${in.header.bar} == '1'", false);
// should not need type conversion
assertEquals(0, context.getTypeConverterRegistry().getStatistics().getAttemptCounter());
}
@Test
public void testEqualIgnoreOperator() {
// string to string comparison
assertPredicate("${in.header.foo} =~ 'abc'", true);
assertPredicate("${in.header.foo} =~ 'ABC'", true);
assertPredicate("${in.header.foo} =~ 'Abc'", true);
assertPredicate("${in.header.foo} =~ 'Def'", false);
assertPredicate("${in.header.foo} =~ '1'", false);
// integer to string comparison
assertPredicate("${in.header.bar} =~ '123'", true);
assertPredicate("${in.header.bar} =~ 123", true);
assertPredicate("${in.header.bar} =~ '444'", false);
assertPredicate("${in.header.bar} =~ 444", false);
assertPredicate("${in.header.bar} =~ '1'", false);
}
@Test
public void testNotEqualOperator() {
// string to string comparison
assertPredicate("${in.header.foo} != 'abc'", false);
assertPredicate("${in.header.foo} != 'def'", true);
assertPredicate("${in.header.foo} != '1'", true);
// integer to string comparison
assertPredicate("${in.header.bar} != '123'", false);
assertPredicate("${in.header.bar} != 123", false);
assertPredicate("${in.header.bar} != '444'", true);
assertPredicate("${in.header.bar} != 444", true);
assertPredicate("${in.header.bar} != '1'", true);
}
@Test
public void testNotEqualIgnoreOperator() {
// string to string comparison
assertPredicate("${in.header.foo} !=~ 'abc'", false);
assertPredicate("${in.header.foo} !=~ 'ABC'", false);
assertPredicate("${in.header.foo} !=~ 'Abc'", false);
assertPredicate("${in.header.foo} !=~ 'Def'", true);
assertPredicate("${in.header.foo} !=~ '1'", true);
// integer to string comparison
assertPredicate("${in.header.bar} !=~ '123'", false);
assertPredicate("${in.header.bar} !=~ 123", false);
assertPredicate("${in.header.bar} !=~ '444'", true);
assertPredicate("${in.header.bar} !=~ 444", true);
assertPredicate("${in.header.bar} !=~ '1'", true);
}
@Test
public void testFloatingNumber() {
// set a String value
exchange.getIn().setBody("0.02");
assertPredicate("${body} > 0", true);
assertPredicate("${body} < 0", false);
assertPredicate("${body} > 0.00", true);
assertPredicate("${body} < 0.00", false);
assertPredicate("${body} > 0.01", true);
assertPredicate("${body} < 0.01", false);
assertPredicate("${body} > 0.02", false);
assertPredicate("${body} < 0.02", false);
assertPredicate("${body} == 0.02", true);
}
@Test
public void testGreaterThanOperator() {
// string to string comparison
assertPredicate("${in.header.foo} > 'aaa'", true);
assertPredicate("${in.header.foo} > 'def'", false);
// integer to string comparison
assertPredicate("${in.header.bar} > '100'", true);
assertPredicate("${in.header.bar} > 100", true);
assertPredicate("${in.header.bar} > '123'", false);
assertPredicate("${in.header.bar} > 123", false);
assertPredicate("${in.header.bar} > '200'", false);
}
@Test
public void testGreaterThanStringToInt() {
// set a String value
exchange.getIn().setHeader("num", "70");
// string to int comparison
assertPredicate("${in.header.num} > 100", false);
assertPredicate("${in.header.num} > 100", false);
assertPredicate("${in.header.num} > 80", false);
assertPredicate("${in.header.num} > 800", false);
assertPredicate("${in.header.num} > 1", true);
assertPredicate("${in.header.num} > 8", true);
assertPredicate("${in.header.num} > 48", true);
assertPredicate("${in.header.num} > 69", true);
assertPredicate("${in.header.num} > 71", false);
assertPredicate("${in.header.num} > 88", false);
assertPredicate("${in.header.num} > 777", false);
}
@Test
public void testLessThanStringToInt() {
// set a String value
exchange.getIn().setHeader("num", "70");
// string to int comparison
assertPredicate("${in.header.num} < 100", true);
assertPredicate("${in.header.num} < 100", true);
assertPredicate("${in.header.num} < 80", true);
assertPredicate("${in.header.num} < 800", true);
assertPredicate("${in.header.num} < 1", false);
assertPredicate("${in.header.num} < 8", false);
assertPredicate("${in.header.num} < 48", false);
assertPredicate("${in.header.num} < 69", false);
assertPredicate("${in.header.num} < 71", true);
assertPredicate("${in.header.num} < 88", true);
assertPredicate("${in.header.num} < 777", true);
}
@Test
public void testGreaterThanOrEqualOperator() {
// string to string comparison
assertPredicate("${in.header.foo} >= 'aaa'", true);
assertPredicate("${in.header.foo} >= 'abc'", true);
assertPredicate("${in.header.foo} >= 'def'", false);
// integer to string comparison
assertPredicate("${in.header.bar} >= '100'", true);
assertPredicate("${in.header.bar} >= 100", true);
assertPredicate("${in.header.bar} >= '123'", true);
assertPredicate("${in.header.bar} >= 123", true);
assertPredicate("${in.header.bar} >= '200'", false);
}
@Test
public void testLessThanOperator() {
// string to string comparison
assertPredicate("${in.header.foo} < 'aaa'", false);
assertPredicate("${in.header.foo} < 'def'", true);
// integer to string comparison
assertPredicate("${in.header.bar} < '100'", false);
assertPredicate("${in.header.bar} < 100", false);
assertPredicate("${in.header.bar} < '123'", false);
assertPredicate("${in.header.bar} < 123", false);
assertPredicate("${in.header.bar} < '200'", true);
}
@Test
public void testAgainstNegativeValue() {
assertPredicate("${in.header.bar} == 123", true);
assertPredicate("${in.header.bar} == -123", false);
assertPredicate("${in.header.bar} =~ 123", true);
assertPredicate("${in.header.bar} =~ -123", false);
assertPredicate("${in.header.bar} > -123", true);
assertPredicate("${in.header.bar} >= -123", true);
assertPredicate("${in.header.bar} > 123", false);
assertPredicate("${in.header.bar} >= 123", true);
assertPredicate("${in.header.bar} < -123", false);
assertPredicate("${in.header.bar} <= -123", false);
assertPredicate("${in.header.bar} < 123", false);
assertPredicate("${in.header.bar} <= 123", true);
exchange.getIn().setHeader("strNum", "123");
assertPredicate("${in.header.strNum} contains '123'", true);
assertPredicate("${in.header.strNum} !contains '123'", false);
assertPredicate("${in.header.strNum} contains '-123'", false);
assertPredicate("${in.header.strNum} !contains '-123'", true);
assertPredicate("${in.header.strNum} ~~ '123'", true);
assertPredicate("${in.header.strNum} ~~ '-123'", false);
exchange.getIn().setHeader("num", -123);
assertPredicate("${in.header.num} == -123", true);
assertPredicate("${in.header.num} == 123", false);
assertPredicate("${in.header.num} =~ -123", true);
assertPredicate("${in.header.num} =~ 123", false);
assertPredicate("${in.header.num} > -123", false);
assertPredicate("${in.header.num} >= -123", true);
assertPredicate("${in.header.num} > 123", false);
assertPredicate("${in.header.num} >= 123", false);
assertPredicate("${in.header.num} < -123", false);
assertPredicate("${in.header.num} <= -123", true);
assertPredicate("${in.header.num} < 123", true);
assertPredicate("${in.header.num} <= 123", true);
exchange.getIn().setHeader("strNumNegative", "-123");
assertPredicate("${in.header.strNumNegative} contains '123'", true);
assertPredicate("${in.header.strNumNegative} !contains '123'", false);
assertPredicate("${in.header.strNumNegative} contains '-123'", true);
assertPredicate("${in.header.strNumNegative} !contains '-123'", false);
assertPredicate("${in.header.strNumNegative} ~~ '123'", true);
assertPredicate("${in.header.strNumNegative} ~~ '-123'", true);
}
@Test
public void testLessThanOrEqualOperator() {
// string to string comparison
assertPredicate("${in.header.foo} <= 'aaa'", false);
assertPredicate("${in.header.foo} <= 'abc'", true);
assertPredicate("${in.header.foo} <= 'def'", true);
// string to string
exchange.getIn().setHeader("dude", "555");
exchange.getIn().setHeader("dude2", "0099");
assertPredicate("${in.header.dude} <= ${in.header.dude}", true);
assertPredicate("${in.header.dude2} <= ${in.header.dude}", true);
// integer to string comparison
assertPredicate("${in.header.bar} <= '100'", false);
assertPredicate("${in.header.bar} <= 100", false);
assertPredicate("${in.header.bar} <= '123'", true);
assertPredicate("${in.header.bar} <= 123", true);
assertPredicate("${in.header.bar} <= '200'", true);
// should not need type conversion
assertEquals(0, context.getTypeConverterRegistry().getStatistics().getAttemptCounter());
}
@Test
public void testTypeCoerceNoConversionNeeded() {
// int to int comparison
exchange.getIn().setHeader("num", 70);
assertPredicate("${in.header.num} > 100", false);
assertPredicate("${in.header.num} < 100", true);
assertPredicate("${in.header.num} == 70", true);
assertPredicate("${in.header.num} != 70", false);
assertPredicate("${in.header.num} > 100", false);
assertPredicate("${in.header.num} > 80", false);
assertPredicate("${in.header.num} > 800", false);
assertPredicate("${in.header.num} < 800", true);
assertPredicate("${in.header.num} > 1", true);
assertPredicate("${in.header.num} > 8", true);
assertPredicate("${in.header.num} > 48", true);
assertPredicate("${in.header.num} > 69", true);
assertPredicate("${in.header.num} > 71", false);
assertPredicate("${in.header.num} < 71", true);
assertPredicate("${in.header.num} > 88", false);
assertPredicate("${in.header.num} > 777", false);
// String to int comparison
exchange.getIn().setHeader("num", "70");
assertPredicate("${in.header.num} > 100", false);
assertPredicate("${in.header.num} < 100", true);
assertPredicate("${in.header.num} == 70", true);
assertPredicate("${in.header.num} != 70", false);
assertPredicate("${in.header.num} > 100", false);
assertPredicate("${in.header.num} > 80", false);
assertPredicate("${in.header.num} > 800", false);
assertPredicate("${in.header.num} < 800", true);
assertPredicate("${in.header.num} > 1", true);
assertPredicate("${in.header.num} > 8", true);
assertPredicate("${in.header.num} > 48", true);
assertPredicate("${in.header.num} > 69", true);
assertPredicate("${in.header.num} > 71", false);
assertPredicate("${in.header.num} < 71", true);
assertPredicate("${in.header.num} > 88", false);
assertPredicate("${in.header.num} > 777", false);
// should not need type conversion
assertEquals(0, context.getTypeConverterRegistry().getStatistics().getAttemptCounter());
}
@Test
public void testIsNull() {
assertPredicate("${in.header.foo} == null", false);
assertPredicate("${in.header.none} == null", true);
}
@Test
public void testIsNotNull() {
assertPredicate("${in.header.foo} != null", true);
assertPredicate("${in.header.none} != null", false);
}
@Test
public void testRightOperatorIsSimpleLanguage() {
// operator on right side is also using ${ } placeholders
assertPredicate("${in.header.foo} == ${in.header.foo}", true);
assertPredicate("${in.header.foo} == ${in.header.bar}", false);
}
@Test
public void testRightOperatorIsBeanLanguage() {
// operator on right side is also using ${ } placeholders
assertPredicate("${in.header.foo} == ${bean:generator.generateFilename}", true);
assertPredicate("${in.header.bar} == ${bean:generator.generateId}", true);
assertPredicate("${in.header.bar} >= ${bean:generator.generateId}", true);
}
@Test
public void testContains() {
assertPredicate("${in.header.foo} contains 'a'", true);
assertPredicate("${in.header.foo} contains 'ab'", true);
assertPredicate("${in.header.foo} contains 'abc'", true);
assertPredicate("${in.header.foo} contains 'def'", false);
}
@Test
public void testContainsNumberInString() {
exchange.getMessage().setBody("The answer is 42 and is the answer to life the universe and everything");
assertPredicate("${body} contains '42'", true);
assertPredicate("${body} contains 42", true);
assertPredicate("${body} contains '77'", false);
assertPredicate("${body} contains 77", false);
}
@Test
public void testNotContains() {
assertPredicate("${in.header.foo} not contains 'a'", false);
assertPredicate("${in.header.foo} not contains 'ab'", false);
assertPredicate("${in.header.foo} not contains 'abc'", false);
assertPredicate("${in.header.foo} not contains 'def'", true);
assertPredicate("${in.header.foo} !contains 'a'", false);
assertPredicate("${in.header.foo} !contains 'ab'", false);
assertPredicate("${in.header.foo} !contains 'abc'", false);
assertPredicate("${in.header.foo} !contains 'def'", true);
}
@Test
public void testContainsIgnoreCase() {
assertPredicate("${in.header.foo} ~~ 'A'", true);
assertPredicate("${in.header.foo} ~~ 'Ab'", true);
assertPredicate("${in.header.foo} ~~ 'Abc'", true);
assertPredicate("${in.header.foo} ~~ 'defG'", false);
}
@Test
public void testNotContainsIgnoreCase() {
assertPredicate("${in.header.foo} !~~ 'A'", false);
assertPredicate("${in.header.foo} !~~ 'Ab'", false);
assertPredicate("${in.header.foo} !~~ 'Abc'", false);
assertPredicate("${in.header.foo} !~~ 'defG'", true);
}
@Test
public void testRegex() {
assertPredicate("${in.header.foo} regex '^a..$'", true);
assertPredicate("${in.header.foo} regex '^ab.$'", true);
assertPredicate("${in.header.foo} regex '^ab.$'", true);
assertPredicate("${in.header.foo} regex '^d.*$'", false);
assertPredicate("${in.header.bar} regex '^\\d{3}'", true);
assertPredicate("${in.header.bar} regex '^\\d{2}'", false);
}
@Test
public void testNotRegex() {
assertPredicate("${in.header.foo} not regex '^a..$'", false);
assertPredicate("${in.header.foo} not regex '^ab.$'", false);
assertPredicate("${in.header.foo} not regex '^ab.$'", false);
assertPredicate("${in.header.foo} not regex '^d.*$'", true);
assertPredicate("${in.header.bar} not regex '^\\d{3}'", false);
assertPredicate("${in.header.bar} not regex '^\\d{2}'", true);
}
@Test
public void testIn() {
// string to string
assertPredicate("${in.header.foo} in 'foo,abc,def'", true);
assertPredicate("${in.header.foo} in ${bean:generator.generateFilename}", true);
assertPredicate("${in.header.foo} in 'foo,abc,def'", true);
assertPredicate("${in.header.foo} in 'foo,def'", false);
// integer to string
assertPredicate("${in.header.bar} in '100,123,200'", true);
assertPredicate("${in.header.bar} in ${bean:generator.generateId}", true);
assertPredicate("${in.header.bar} in '100,200'", false);
}
@Test
public void testNotIn() {
// string to string
assertPredicate("${in.header.foo} not in 'foo,abc,def'", false);
assertPredicate("${in.header.foo} not in ${bean:generator.generateFilename}", false);
assertPredicate("${in.header.foo} not in 'foo,abc,def'", false);
assertPredicate("${in.header.foo} not in 'foo,def'", true);
assertPredicate("${in.header.foo} !in 'foo,abc,def'", false);
assertPredicate("${in.header.foo} !in ${bean:generator.generateFilename}", false);
assertPredicate("${in.header.foo} !in 'foo,abc,def'", false);
assertPredicate("${in.header.foo} !in 'foo,def'", true);
// integer to string
assertPredicate("${in.header.bar} not in '100,123,200'", false);
assertPredicate("${in.header.bar} not in ${bean:generator.generateId}", false);
assertPredicate("${in.header.bar} not in '100,200'", true);
assertPredicate("${in.header.bar} !in '100,123,200'", false);
assertPredicate("${in.header.bar} !in ${bean:generator.generateId}", false);
assertPredicate("${in.header.bar} !in '100,200'", true);
}
@Test
public void testIs() {
assertPredicate("${in.header.foo} is 'java.lang.String'", true);
assertPredicate("${in.header.foo} is 'java.lang.Integer'", false);
assertPredicate("${in.header.foo} is 'String'", true);
assertPredicate("${in.header.foo} is 'Integer'", false);
try {
assertPredicate("${in.header.foo} is com.mycompany.DoesNotExist", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(20, e.getIndex());
}
}
@Test
public void testIsNot() {
assertPredicate("${in.header.foo} not is 'java.lang.String'", false);
assertPredicate("${in.header.foo} not is 'java.lang.Integer'", true);
assertPredicate("${in.header.foo} !is 'java.lang.String'", false);
assertPredicate("${in.header.foo} !is 'java.lang.Integer'", true);
assertPredicate("${in.header.foo} not is 'String'", false);
assertPredicate("${in.header.foo} not is 'Integer'", true);
assertPredicate("${in.header.foo} !is 'String'", false);
assertPredicate("${in.header.foo} !is 'Integer'", true);
try {
assertPredicate("${in.header.foo} not is com.mycompany.DoesNotExist", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(24, e.getIndex());
}
try {
assertPredicate("${in.header.foo} !is com.mycompany.DoesNotExist", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(21, e.getIndex());
}
}
@Test
public void testRange() {
assertPredicate("${in.header.bar} range '100..200'", true);
assertPredicate("${in.header.bar} range '200..300'", false);
assertPredicate("${in.header.foo} range '200..300'", false);
assertPredicate("${bean:generator.generateId} range '123..130'", true);
assertPredicate("${bean:generator.generateId} range '120..123'", true);
assertPredicate("${bean:generator.generateId} range '120..122'", false);
assertPredicate("${bean:generator.generateId} range '124..130'", false);
try {
assertPredicate("${in.header.foo} range abc..200", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(23, e.getIndex());
}
try {
assertPredicate("${in.header.foo} range abc..", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(23, e.getIndex());
}
try {
assertPredicate("${in.header.foo} range 100.200", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(30, e.getIndex());
}
assertPredicate("${in.header.bar} range '100..200' && ${in.header.foo} == 'abc'", true);
assertPredicate("${in.header.bar} range '200..300' && ${in.header.foo} == 'abc'", false);
assertPredicate("${in.header.bar} range '200..300' || ${in.header.foo} == 'abc'", true);
assertPredicate("${in.header.bar} range '200..300' || ${in.header.foo} == 'def'", false);
}
@Test
public void testNotRange() {
assertPredicate("${in.header.bar} not range '100..200'", false);
assertPredicate("${in.header.bar} not range '200..300'", true);
assertPredicate("${in.header.bar} !range '100..200'", false);
assertPredicate("${in.header.bar} !range '200..300'", true);
assertPredicate("${in.header.foo} not range '200..300'", true);
assertPredicate("${bean:generator.generateId} not range '123..130'", false);
assertPredicate("${bean:generator.generateId} not range '120..123'", false);
assertPredicate("${bean:generator.generateId} not range '120..122'", true);
assertPredicate("${bean:generator.generateId} not range '124..130'", true);
assertPredicate("${in.header.foo} !range '200..300'", true);
assertPredicate("${bean:generator.generateId} !range '123..130'", false);
assertPredicate("${bean:generator.generateId} !range '120..123'", false);
assertPredicate("${bean:generator.generateId} !range '120..122'", true);
assertPredicate("${bean:generator.generateId} !range '124..130'", true);
try {
assertPredicate("${in.header.foo} not range abc..200", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(27, e.getIndex());
}
try {
assertPredicate("${in.header.foo} !range abc..200", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(24, e.getIndex());
}
try {
assertPredicate("${in.header.foo} not range abc..", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(27, e.getIndex());
}
try {
assertPredicate("${in.header.foo} !range abc..", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(24, e.getIndex());
}
try {
assertPredicate("${in.header.foo} not range 100.200", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(34, e.getIndex());
}
try {
assertPredicate("${in.header.foo} !range 100.200", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(31, e.getIndex());
}
}
@Test
public void testUnaryInc() {
assertExpression("${in.header.bar}++", 124);
assertExpression("+++++++++++++", "+++++++++++++");
assertExpression("Logging ++ start ++", "Logging ++ start ++");
assertExpression("Logging +++ start +++", "Logging +++ start +++");
assertExpression("++ start ++", "++ start ++");
assertExpression("+++ start +++", "+++ start +++");
assertPredicate("${in.header.bar}++ == 122", false);
assertPredicate("${in.header.bar}++ == 123", false);
assertPredicate("${in.header.bar}++ == 124", true);
}
@Test
public void testUnaryDec() {
assertExpression("${in.header.bar}--", 122);
assertExpression("-------------", "-------------");
assertExpression("Logging -- start --", "Logging -- start --");
assertExpression("Logging --- start ---", "Logging --- start ---");
assertExpression("-- start --", "-- start --");
assertExpression("--- start ---", "--- start ---");
assertPredicate("${in.header.bar}-- == 122", true);
assertPredicate("${in.header.bar}-- == 123", false);
assertPredicate("${in.header.bar}-- == 124", false);
}
@Test
public void testStartsWith() {
exchange.getIn().setBody("Hello there");
assertPredicate("${in.body} starts with 'Hello'", true);
assertPredicate("${in.body} starts with 'H'", true);
assertPredicate("${in.body} starts with 'Hello there'", true);
assertPredicate("${in.body} starts with 'Hello ther'", true);
assertPredicate("${in.body} starts with 'ello there'", false);
assertPredicate("${in.body} starts with 'Hi'", false);
assertPredicate("${in.body} startsWith 'Hello'", true);
assertPredicate("${in.body} startsWith 'H'", true);
assertPredicate("${in.body} startsWith 'Hello there'", true);
assertPredicate("${in.body} startsWith 'Hello ther'", true);
assertPredicate("${in.body} startsWith 'ello there'", false);
assertPredicate("${in.body} startsWith 'Hi'", false);
}
@Test
public void testEndsWith() {
exchange.getIn().setBody("Hello there");
assertPredicate("${in.body} ends with 'there'", true);
assertPredicate("${in.body} ends with 're'", true);
assertPredicate("${in.body} ends with ' there'", true);
assertPredicate("${in.body} ends with 'Hello there'", true);
assertPredicate("${in.body} ends with 'Hello ther'", false);
assertPredicate("${in.body} ends with 'Hi'", false);
assertPredicate("${in.body} endsWith 'there'", true);
assertPredicate("${in.body} endsWith 're'", true);
assertPredicate("${in.body} endsWith ' there'", true);
assertPredicate("${in.body} endsWith 'Hello there'", true);
assertPredicate("${in.body} endsWith 'Hello ther'", false);
assertPredicate("${in.body} endsWith 'Hi'", false);
}
@Override
protected String getLanguageName() {
return "csimple";
}
public | OriginalSimpleOperatorTest |
java | apache__camel | components/camel-avro-rpc/camel-avro-rpc-component/src/main/java/org/apache/camel/component/avro/AvroSpecificRequestor.java | {
"start": 1010,
"end": 1211
} | class ____ extends SpecificRequestor {
public AvroSpecificRequestor(Protocol protocol, Transceiver transceiver) throws IOException {
super(protocol, transceiver);
}
}
| AvroSpecificRequestor |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java | {
"start": 28470,
"end": 29075
} | class ____ {
private final Saml2AuthenticationTokenConverter authenticationConverter = mock(
Saml2AuthenticationTokenConverter.class);
@Bean
SecurityFilterChain app(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated())
.saml2Login(Customizer.withDefaults());
return http.build();
}
@Bean
Saml2AuthenticationTokenConverter authenticationConverter() {
return this.authenticationConverter;
}
}
@Configuration
@EnableWebSecurity
@Import(Saml2LoginConfigBeans.class)
static | CustomAuthenticationConverterBean |
java | micronaut-projects__micronaut-core | http/src/main/java/io/micronaut/http/annotation/ClientFilter.java | {
"start": 1407,
"end": 2379
} | interface ____ {
/**
* Pattern used to match all requests.
*/
String MATCH_ALL_PATTERN = Filter.MATCH_ALL_PATTERN;
/**
* @return The patterns this filter should match
*/
String[] value() default {};
/**
* @return The style of pattern this filter uses
*/
FilterPatternStyle patternStyle() default FilterPatternStyle.ANT;
/**
* Same as {@link #value()}.
*
* @return The patterns
*/
@AliasFor(member = "value")
String[] patterns() default {};
/**
* @return The methods to match. Defaults to all
*/
HttpMethod[] methods() default {};
/**
* The service identifiers this filter applies to.
*
* @return The service identifiers
*/
String[] serviceId() default {};
/**
* The service identifiers this filter does not apply to.
*
* @return The service identifiers
*/
String[] excludeServiceId() default {};
}
| ClientFilter |
java | quarkusio__quarkus | extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/NamedJKSKeyStoreWithAliasCredentialsProviderTest.java | {
"start": 1145,
"end": 2521
} | class ____ {
private static final String configuration = """
quarkus.tls.foo.key-store.jks.path=target/certs/test-credentials-provider-alias-keystore.jks
quarkus.tls.foo.key-store.jks.alias=my-alias
quarkus.tls.foo.key-store.credentials-provider.name=tls
""";
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addClass(MyCredentialProvider.class)
.add(new StringAsset(configuration), "application.properties"));
@Inject
TlsConfigurationRegistry certificates;
@Test
void test() throws KeyStoreException, CertificateParsingException {
TlsConfiguration def = certificates.get("foo").orElseThrow();
assertThat(def.getKeyStoreOptions()).isNotNull();
assertThat(def.getKeyStore()).isNotNull();
X509Certificate certificate = (X509Certificate) def.getKeyStore().getCertificate("my-alias");
assertThat(certificate).isNotNull();
assertThat(certificate.getSubjectAlternativeNames()).anySatisfy(l -> {
assertThat(l.get(0)).isEqualTo(2);
assertThat(l.get(1)).isEqualTo("dns:acme.org");
});
}
@ApplicationScoped
public static | NamedJKSKeyStoreWithAliasCredentialsProviderTest |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/TestRMAppAttemptTransitions.java | {
"start": 10486,
"end": 94857
} | class ____ implements
EventHandler<AMLauncherEvent> {
@Override
public void handle(AMLauncherEvent event) {
applicationMasterLauncher.handle(event);
}
}
private static int appId = 1;
private ApplicationSubmissionContext submissionContext = null;
private boolean unmanagedAM;
public static Collection<Object[]> getTestParameters() {
return Arrays.asList(new Object[][] {
{ Boolean.FALSE },
{ Boolean.TRUE }
});
}
private void initTestRMAppAttemptTransitions(boolean pIsSecurityEnabled)
throws Exception {
this.isSecurityEnabled = pIsSecurityEnabled;
setUp();
}
@SuppressWarnings("deprecation")
public void setUp() throws Exception {
AuthenticationMethod authMethod = AuthenticationMethod.SIMPLE;
if (isSecurityEnabled) {
authMethod = AuthenticationMethod.KERBEROS;
}
SecurityUtil.setAuthenticationMethod(authMethod, conf);
UserGroupInformation.setConfiguration(conf);
InlineDispatcher rmDispatcher = new InlineDispatcher();
ContainerAllocationExpirer containerAllocationExpirer =
mock(ContainerAllocationExpirer.class);
amLivelinessMonitor = mock(AMLivelinessMonitor.class);
amFinishingMonitor = mock(AMLivelinessMonitor.class);
writer = mock(RMApplicationHistoryWriter.class);
MasterKeyData masterKeyData = amRMTokenManager.createNewMasterKey();
when(amRMTokenManager.getMasterKey()).thenReturn(masterKeyData);
rmContext =
new RMContextImpl(rmDispatcher,
containerAllocationExpirer, amLivelinessMonitor, amFinishingMonitor,
null, amRMTokenManager,
new RMContainerTokenSecretManager(conf),
nmTokenManager,
clientToAMTokenManager);
store = mock(RMStateStore.class);
((RMContextImpl) rmContext).setStateStore(store);
publisher = mock(SystemMetricsPublisher.class);
rmContext.setSystemMetricsPublisher(publisher);
rmContext.setRMApplicationHistoryWriter(writer);
scheduler = mock(YarnScheduler.class);
masterService = mock(ApplicationMasterService.class);
applicationMasterLauncher = mock(ApplicationMasterLauncher.class);
rmDispatcher.register(RMAppAttemptEventType.class,
new TestApplicationAttemptEventDispatcher());
rmDispatcher.register(RMAppEventType.class,
new TestApplicationEventDispatcher());
rmDispatcher.register(SchedulerEventType.class,
new TestSchedulerEventDispatcher());
rmDispatcher.register(AMLauncherEventType.class,
new TestAMLauncherEventDispatcher());
rmnodeEventHandler = mock(RMNodeImpl.class);
rmDispatcher.register(RMNodeEventType.class, rmnodeEventHandler);
rmDispatcher.init(conf);
rmDispatcher.start();
ApplicationId applicationId = MockApps.newAppID(appId++);
ApplicationAttemptId applicationAttemptId =
ApplicationAttemptId.newInstance(applicationId, 0);
resourceScheduler = mock(ResourceScheduler.class);
ApplicationResourceUsageReport appResUsgRpt =
mock(ApplicationResourceUsageReport.class);
when(appResUsgRpt.getMemorySeconds()).thenReturn(0L);
when(appResUsgRpt.getVcoreSeconds()).thenReturn(0L);
when(resourceScheduler
.getAppResourceUsageReport(any()))
.thenReturn(appResUsgRpt);
spyRMContext = spy(rmContext);
Mockito.doReturn(resourceScheduler).when(spyRMContext).getScheduler();
final String user = MockApps.newUserName();
final String queue = MockApps.newQueue();
submissionContext = mock(ApplicationSubmissionContext.class);
when(submissionContext.getQueue()).thenReturn(queue);
Resource resource = Resources.createResource(1536);
ContainerLaunchContext amContainerSpec =
BuilderUtils.newContainerLaunchContext(null, null,
null, null, null, null);
when(submissionContext.getAMContainerSpec()).thenReturn(amContainerSpec);
when(submissionContext.getResource()).thenReturn(resource);
unmanagedAM = false;
application = mock(RMAppImpl.class);
applicationAttempt =
new RMAppAttemptImpl(applicationAttemptId, spyRMContext, scheduler,
masterService, submissionContext, new Configuration(),
Collections.singletonList(BuilderUtils.newResourceRequest(
RMAppAttemptImpl.AM_CONTAINER_PRIORITY, ResourceRequest.ANY,
submissionContext.getResource(), 1)), application) {
@Override
protected void onInvalidTranstion(
RMAppAttemptEventType rmAppAttemptEventType,
RMAppAttemptState state) {
assertTrue(false, "RMAppAttemptImpl can't handle "
+ rmAppAttemptEventType + " at state " + state);
}
};
when(application.getCurrentAppAttempt()).thenReturn(applicationAttempt);
when(application.getApplicationId()).thenReturn(applicationId);
spyRMContext.getRMApps().put(application.getApplicationId(), application);
testAppAttemptNewState();
}
@AfterEach
public void tearDown() throws Exception {
((AsyncDispatcher)this.spyRMContext.getDispatcher()).stop();
}
private String getProxyUrl(RMAppAttempt appAttempt) {
String url = rmContext.getAppProxyUrl(conf,
appAttempt.getAppAttemptId().getApplicationId());
assertNotEquals("N/A", url);
return url;
}
/**
* {@link RMAppAttemptState#NEW}
*/
private void testAppAttemptNewState() {
assertEquals(RMAppAttemptState.NEW,
applicationAttempt.getAppAttemptState());
assertEquals(0, applicationAttempt.getDiagnostics().length());
assertEquals(0,applicationAttempt.getJustFinishedContainers().size());
assertNull(applicationAttempt.getMasterContainer());
assertEquals(0.0, (double)applicationAttempt.getProgress(), 0.0001);
assertEquals(0, application.getRanNodes().size());
assertNull(applicationAttempt.getFinalApplicationStatus());
assertNotNull(applicationAttempt.getTrackingUrl());
assertFalse("N/A".equals(applicationAttempt.getTrackingUrl()));
}
/**
* {@link RMAppAttemptState#SUBMITTED}
*/
private void testAppAttemptSubmittedState() {
assertEquals(RMAppAttemptState.SUBMITTED,
applicationAttempt.getAppAttemptState());
assertEquals(0, applicationAttempt.getDiagnostics().length());
assertEquals(0,applicationAttempt.getJustFinishedContainers().size());
assertNull(applicationAttempt.getMasterContainer());
assertEquals(0.0, (double)applicationAttempt.getProgress(), 0.0001);
assertEquals(0, application.getRanNodes().size());
assertNull(applicationAttempt.getFinalApplicationStatus());
if (UserGroupInformation.isSecurityEnabled()) {
verify(clientToAMTokenManager).createMasterKey(
applicationAttempt.getAppAttemptId());
// can't create ClientToken as at this time ClientTokenMasterKey has
// not been registered in the SecretManager
assertNull(applicationAttempt.createClientToken("some client"));
}
assertNull(applicationAttempt.createClientToken(null));
// Check events
verify(masterService).
registerAppAttempt(applicationAttempt.getAppAttemptId());
verify(scheduler).handle(any(AppAttemptAddedSchedulerEvent.class));
}
/**
* {@link RMAppAttemptState#SUBMITTED} -> {@link RMAppAttemptState#FAILED}
*/
private void testAppAttemptSubmittedToFailedState(String diagnostics) {
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
assertEquals(diagnostics, applicationAttempt.getDiagnostics());
assertEquals(0,applicationAttempt.getJustFinishedContainers().size());
assertNull(applicationAttempt.getMasterContainer());
assertEquals(0.0, (double)applicationAttempt.getProgress(), 0.0001);
assertEquals(0, application.getRanNodes().size());
assertNull(applicationAttempt.getFinalApplicationStatus());
// Check events
verify(masterService).
unregisterAttempt(applicationAttempt.getAppAttemptId());
// ATTEMPT_FAILED should be notified to app if app attempt is submitted to
// failed state.
ArgumentMatcher<RMAppEvent> matcher =
event -> event.getType() == RMAppEventType.ATTEMPT_FAILED;
verify(application).handle(argThat(matcher));
verifyTokenCount(applicationAttempt.getAppAttemptId(), 1);
verifyApplicationAttemptFinished(RMAppAttemptState.FAILED);
}
/**
* {@link RMAppAttemptState#KILLED}
*/
private void testAppAttemptKilledState(Container amContainer,
String diagnostics) {
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.KILLED,
applicationAttempt.getAppAttemptState());
assertEquals(diagnostics, applicationAttempt.getDiagnostics());
assertEquals(0,applicationAttempt.getJustFinishedContainers().size());
assertEquals(amContainer, applicationAttempt.getMasterContainer());
assertEquals(0.0, (double)applicationAttempt.getProgress(), 0.0001);
assertEquals(0, application.getRanNodes().size());
assertNull(applicationAttempt.getFinalApplicationStatus());
verifyTokenCount(applicationAttempt.getAppAttemptId(), 1);
verifyAttemptFinalStateSaved();
assertFalse(transferStateFromPreviousAttempt);
verifyApplicationAttemptFinished(RMAppAttemptState.KILLED);
}
/**
* {@link RMAppAttemptState#LAUNCHED}
*/
private void testAppAttemptRecoveredState() {
assertEquals(RMAppAttemptState.LAUNCHED,
applicationAttempt.getAppAttemptState());
}
/**
* {@link RMAppAttemptState#SCHEDULED}
*/
@SuppressWarnings("unchecked")
private void testAppAttemptScheduledState() {
RMAppAttemptState expectedState;
int expectedAllocateCount;
if(unmanagedAM) {
expectedState = RMAppAttemptState.LAUNCHED;
expectedAllocateCount = 0;
} else {
expectedState = RMAppAttemptState.SCHEDULED;
expectedAllocateCount = 1;
}
assertEquals(expectedState, applicationAttempt.getAppAttemptState());
verify(scheduler, times(expectedAllocateCount)).allocate(
any(ApplicationAttemptId.class), any(List.class), eq(null), any(List.class),
any(List.class), any(List.class), any(ContainerUpdates.class));
assertEquals(0,applicationAttempt.getJustFinishedContainers().size());
assertNull(applicationAttempt.getMasterContainer());
assertEquals(0.0, (double)applicationAttempt.getProgress(), 0.0001);
assertEquals(0, application.getRanNodes().size());
assertNull(applicationAttempt.getFinalApplicationStatus());
}
/**
* {@link RMAppAttemptState#ALLOCATED}
*/
@SuppressWarnings("unchecked")
private void testAppAttemptAllocatedState(Container amContainer) {
assertEquals(RMAppAttemptState.ALLOCATED,
applicationAttempt.getAppAttemptState());
assertEquals(amContainer, applicationAttempt.getMasterContainer());
// Check events
verify(applicationMasterLauncher).handle(any(AMLauncherEvent.class));
verify(scheduler, times(2)).allocate(any(ApplicationAttemptId.class),
any(List.class), any(), any(List.class), any(), any(),
any(ContainerUpdates.class));
verify(nmTokenManager).clearNodeSetForAttempt(
applicationAttempt.getAppAttemptId());
}
/**
* {@link RMAppAttemptState#FAILED}
*/
private void testAppAttemptFailedState(Container container,
String diagnostics) {
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
assertEquals(diagnostics, applicationAttempt.getDiagnostics());
assertEquals(0,applicationAttempt.getJustFinishedContainers().size());
assertEquals(container, applicationAttempt.getMasterContainer());
assertEquals(0.0, (double)applicationAttempt.getProgress(), 0.0001);
assertEquals(0, application.getRanNodes().size());
// Check events
verify(application, times(1)).handle(any(RMAppFailedAttemptEvent.class));
verifyTokenCount(applicationAttempt.getAppAttemptId(), 1);
verifyAttemptFinalStateSaved();
verifyApplicationAttemptFinished(RMAppAttemptState.FAILED);
}
private void testAppAttemptLaunchedState(Container container,
RMAppAttemptState state) {
assertEquals(state, applicationAttempt.getAppAttemptState());
assertEquals(container, applicationAttempt.getMasterContainer());
if (UserGroupInformation.isSecurityEnabled()) {
// ClientTokenMasterKey has been registered in SecretManager, it's able to
// create ClientToken now
assertNotNull(applicationAttempt.createClientToken("some client"));
}
// TODO - need to add more checks relevant to this state
}
/**
* {@link RMAppAttemptState#RUNNING}
*/
private void testAppAttemptRunningState(Container container,
String host, int rpcPort, String trackingUrl, boolean unmanagedAM) {
assertEquals(RMAppAttemptState.RUNNING,
applicationAttempt.getAppAttemptState());
assertEquals(container, applicationAttempt.getMasterContainer());
assertEquals(host, applicationAttempt.getHost());
assertEquals(rpcPort, applicationAttempt.getRpcPort());
verifyUrl(trackingUrl, applicationAttempt.getOriginalTrackingUrl());
if (unmanagedAM) {
verifyUrl(trackingUrl, applicationAttempt.getTrackingUrl());
} else {
assertEquals(getProxyUrl(applicationAttempt),
applicationAttempt.getTrackingUrl());
}
// TODO - need to add more checks relevant to this state
}
/**
* {@link RMAppAttemptState#FINISHING}
*/
private void testAppAttemptFinishingState(Container container,
FinalApplicationStatus finalStatus,
String trackingUrl,
String diagnostics) {
assertEquals(RMAppAttemptState.FINISHING,
applicationAttempt.getAppAttemptState());
assertEquals(diagnostics, applicationAttempt.getDiagnostics());
verifyUrl(trackingUrl, applicationAttempt.getOriginalTrackingUrl());
assertEquals(getProxyUrl(applicationAttempt),
applicationAttempt.getTrackingUrl());
assertEquals(container, applicationAttempt.getMasterContainer());
assertEquals(finalStatus, applicationAttempt.getFinalApplicationStatus());
verifyTokenCount(applicationAttempt.getAppAttemptId(), 0);
verifyAttemptFinalStateSaved();
}
/**
* {@link RMAppAttemptState#FINISHED}
*/
private void testAppAttemptFinishedState(Container container,
FinalApplicationStatus finalStatus,
String trackingUrl,
String diagnostics,
int finishedContainerCount, boolean unmanagedAM) {
assertEquals(RMAppAttemptState.FINISHED,
applicationAttempt.getAppAttemptState());
assertEquals(diagnostics, applicationAttempt.getDiagnostics());
verifyUrl(trackingUrl, applicationAttempt.getOriginalTrackingUrl());
if (unmanagedAM) {
verifyUrl(trackingUrl, applicationAttempt.getTrackingUrl());
} else {
assertEquals(getProxyUrl(applicationAttempt),
applicationAttempt.getTrackingUrl());
}
verifyAttemptFinalStateSaved();
assertEquals(finishedContainerCount, applicationAttempt
.getJustFinishedContainers().size());
assertEquals(0, getFinishedContainersSentToAM(applicationAttempt)
.size());
assertEquals(container, applicationAttempt.getMasterContainer());
assertEquals(finalStatus, applicationAttempt.getFinalApplicationStatus());
verifyTokenCount(applicationAttempt.getAppAttemptId(), 1);
assertFalse(transferStateFromPreviousAttempt);
verifyApplicationAttemptFinished(RMAppAttemptState.FINISHED);
}
private void submitApplicationAttempt() {
ApplicationAttemptId appAttemptId = applicationAttempt.getAppAttemptId();
applicationAttempt.handle(
new RMAppAttemptEvent(appAttemptId, RMAppAttemptEventType.START));
testAppAttemptSubmittedState();
}
private void scheduleApplicationAttempt() {
submitApplicationAttempt();
applicationAttempt.handle(
new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.ATTEMPT_ADDED));
if(unmanagedAM){
assertEquals(RMAppAttemptState.LAUNCHED_UNMANAGED_SAVING,
applicationAttempt.getAppAttemptState());
applicationAttempt.handle(
new RMAppAttemptEvent(applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.ATTEMPT_NEW_SAVED));
}
testAppAttemptScheduledState();
}
@SuppressWarnings("unchecked")
private Container allocateApplicationAttempt() {
scheduleApplicationAttempt();
// Mock the allocation of AM container
Container container = mock(Container.class);
Resource resource = Resources.createResource(2048);
when(container.getId()).thenReturn(
BuilderUtils.newContainerId(applicationAttempt.getAppAttemptId(), 1));
when(container.getResource()).thenReturn(resource);
Allocation allocation = mock(Allocation.class);
when(allocation.getContainers()).
thenReturn(Collections.singletonList(container));
when(scheduler.allocate(any(ApplicationAttemptId.class), any(List.class),
any(), any(List.class), any(), any(),
any(ContainerUpdates.class))).
thenReturn(allocation);
RMContainer rmContainer = mock(RMContainerImpl.class);
when(scheduler.getRMContainer(container.getId())).
thenReturn(rmContainer);
when(container.getNodeId()).thenReturn(
BuilderUtils.newNodeId("localhost", 0));
applicationAttempt.handle(
new RMAppAttemptEvent(applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.CONTAINER_ALLOCATED));
assertEquals(RMAppAttemptState.ALLOCATED_SAVING,
applicationAttempt.getAppAttemptState());
if (UserGroupInformation.isSecurityEnabled()) {
// Before SAVED state, can't create ClientToken as at this time
// ClientTokenMasterKey has not been registered in the SecretManager
assertNull(applicationAttempt.createClientToken("some client"));
}
applicationAttempt.handle(
new RMAppAttemptEvent(applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.ATTEMPT_NEW_SAVED));
if (UserGroupInformation.isSecurityEnabled()) {
// Before SAVED state, can't create ClientToken as at this time
// ClientTokenMasterKey has not been registered in the SecretManager
assertNotNull(applicationAttempt.createClientToken("some client"));
}
testAppAttemptAllocatedState(container);
return container;
}
private void launchApplicationAttempt(Container container) {
launchApplicationAttempt(container, RMAppAttemptState.LAUNCHED);
}
private void launchApplicationAttempt(Container container,
RMAppAttemptState state) {
applicationAttempt.handle(
new RMAppAttemptEvent(applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.LAUNCHED));
testAppAttemptLaunchedState(container, state);
}
private void runApplicationAttempt(Container container,
String host,
int rpcPort,
String trackingUrl, boolean unmanagedAM) {
applicationAttempt.handle(
new RMAppAttemptRegistrationEvent(
applicationAttempt.getAppAttemptId(),
host, rpcPort, trackingUrl));
testAppAttemptRunningState(container, host, rpcPort, trackingUrl,
unmanagedAM);
}
private void unregisterApplicationAttempt(Container container,
FinalApplicationStatus finalStatus, String trackingUrl,
String diagnostics) {
applicationAttempt.handle(
new RMAppAttemptUnregistrationEvent(
applicationAttempt.getAppAttemptId(),
trackingUrl, finalStatus, diagnostics));
sendAttemptUpdateSavedEvent(applicationAttempt);
testAppAttemptFinishingState(container, finalStatus,
trackingUrl, diagnostics);
}
private void testUnmanagedAMSuccess(String url) {
unmanagedAM = true;
when(submissionContext.getUnmanagedAM()).thenReturn(true);
// submit AM and check it goes to LAUNCHED state
scheduleApplicationAttempt();
testAppAttemptLaunchedState(null, RMAppAttemptState.LAUNCHED);
verify(amLivelinessMonitor, times(1)).register(
applicationAttempt.getAppAttemptId());
// launch AM
runApplicationAttempt(null, "host", 8042, url, true);
// complete a container
Container container = mock(Container.class);
when(container.getNodeId()).thenReturn(NodeId.newInstance("host", 1234));
application.handle(new RMAppRunningOnNodeEvent(application.getApplicationId(),
container.getNodeId()));
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), mock(ContainerStatus.class),
container.getNodeId()));
// complete AM
String diagnostics = "Successful";
FinalApplicationStatus finalStatus = FinalApplicationStatus.SUCCEEDED;
applicationAttempt.handle(new RMAppAttemptUnregistrationEvent(
applicationAttempt.getAppAttemptId(), url, finalStatus,
diagnostics));
sendAttemptUpdateSavedEvent(applicationAttempt);
testAppAttemptFinishedState(null, finalStatus, url, diagnostics, 1,
true);
assertFalse(transferStateFromPreviousAttempt);
}
private void sendAttemptUpdateSavedEvent(RMAppAttempt applicationAttempt) {
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
applicationAttempt.handle(
new RMAppAttemptEvent(applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.ATTEMPT_UPDATE_SAVED));
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testUsageReport(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
// scheduler has info on running apps
ApplicationAttemptId attemptId = applicationAttempt.getAppAttemptId();
ApplicationResourceUsageReport appResUsgRpt =
mock(ApplicationResourceUsageReport.class);
when(appResUsgRpt.getMemorySeconds()).thenReturn(123456L);
when(appResUsgRpt.getVcoreSeconds()).thenReturn(55544L);
when(scheduler.getAppResourceUsageReport(any(ApplicationAttemptId.class)))
.thenReturn(appResUsgRpt);
// start and finish the attempt
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
applicationAttempt.handle(new RMAppAttemptUnregistrationEvent(attemptId,
"", FinalApplicationStatus.SUCCEEDED, ""));
// expect usage stats to come from the scheduler report
ApplicationResourceUsageReport report =
applicationAttempt.getApplicationResourceUsageReport();
assertEquals(123456L, report.getMemorySeconds());
assertEquals(55544L, report.getVcoreSeconds());
// finish app attempt and remove it from scheduler
when(appResUsgRpt.getMemorySeconds()).thenReturn(223456L);
when(appResUsgRpt.getVcoreSeconds()).thenReturn(75544L);
sendAttemptUpdateSavedEvent(applicationAttempt);
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
attemptId,
ContainerStatus.newInstance(
amContainer.getId(), ContainerState.COMPLETE, "", 0), anyNodeId));
when(scheduler.getSchedulerAppInfo(eq(attemptId))).thenReturn(null);
report = applicationAttempt.getApplicationResourceUsageReport();
assertEquals(223456, report.getMemorySeconds());
assertEquals(75544, report.getVcoreSeconds());
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testUnmanagedAMUnexpectedRegistration(boolean pIsSecurityEnabled)
throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
unmanagedAM = true;
when(submissionContext.getUnmanagedAM()).thenReturn(true);
// submit AM and check it goes to SUBMITTED state
submitApplicationAttempt();
assertEquals(RMAppAttemptState.SUBMITTED,
applicationAttempt.getAppAttemptState());
// launch AM and verify attempt failed
applicationAttempt.handle(new RMAppAttemptRegistrationEvent(
applicationAttempt.getAppAttemptId(), "host", 8042, "oldtrackingurl"));
assertEquals(YarnApplicationAttemptState.SUBMITTED,
applicationAttempt.createApplicationAttemptState());
testAppAttemptSubmittedToFailedState(
"Unmanaged AM must register after AM attempt reaches LAUNCHED state.");
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testUnmanagedAMContainersCleanup(boolean pIsSecurityEnabled)
throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
unmanagedAM = true;
when(submissionContext.getUnmanagedAM()).thenReturn(true);
when(submissionContext.getKeepContainersAcrossApplicationAttempts())
.thenReturn(true);
// submit AM and check it goes to SUBMITTED state
submitApplicationAttempt();
// launch AM and verify attempt failed
applicationAttempt.handle(new RMAppAttemptRegistrationEvent(
applicationAttempt.getAppAttemptId(), "host", 8042, "oldtrackingurl"));
assertEquals(YarnApplicationAttemptState.SUBMITTED,
applicationAttempt.createApplicationAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
assertFalse(transferStateFromPreviousAttempt);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testNewToKilled(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
applicationAttempt.handle(
new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.KILL));
assertEquals(YarnApplicationAttemptState.NEW,
applicationAttempt.createApplicationAttemptState());
testAppAttemptKilledState(null, EMPTY_DIAGNOSTICS);
verifyTokenCount(applicationAttempt.getAppAttemptId(), 1);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testNewToRecovered(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
applicationAttempt.handle(
new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.RECOVER));
testAppAttemptRecoveredState();
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testSubmittedToKilled(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
submitApplicationAttempt();
applicationAttempt.handle(
new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.KILL));
assertEquals(YarnApplicationAttemptState.SUBMITTED,
applicationAttempt.createApplicationAttemptState());
testAppAttemptKilledState(null, EMPTY_DIAGNOSTICS);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testScheduledToKilled(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
scheduleApplicationAttempt();
applicationAttempt.handle(
new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.KILL));
assertEquals(YarnApplicationAttemptState.SCHEDULED,
applicationAttempt.createApplicationAttemptState());
testAppAttemptKilledState(null, EMPTY_DIAGNOSTICS);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testAMCrashAtScheduled(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
// This is to test sending CONTAINER_FINISHED event at SCHEDULED state.
// Verify the state transition is correct.
scheduleApplicationAttempt();
ContainerStatus cs =
SchedulerUtils.createAbnormalContainerStatus(
BuilderUtils.newContainerId(
applicationAttempt.getAppAttemptId(), 1),
SchedulerUtils.LOST_CONTAINER);
// send CONTAINER_FINISHED event at SCHEDULED state,
// The state should be FINAL_SAVING with previous state SCHEDULED
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), cs, anyNodeId));
// createApplicationAttemptState will return previous state (SCHEDULED),
// if the current state is FINAL_SAVING.
assertEquals(YarnApplicationAttemptState.SCHEDULED,
applicationAttempt.createApplicationAttemptState());
// send ATTEMPT_UPDATE_SAVED event,
// verify the state is changed to state FAILED.
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
verifyApplicationAttemptFinished(RMAppAttemptState.FAILED);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testAllocatedToKilled(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
applicationAttempt.handle(
new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.KILL));
assertEquals(YarnApplicationAttemptState.ALLOCATED,
applicationAttempt.createApplicationAttemptState());
testAppAttemptKilledState(amContainer, EMPTY_DIAGNOSTICS);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testAllocatedToFailed(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
String diagnostics = "Launch Failed";
applicationAttempt.handle(
new RMAppAttemptEvent(applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.LAUNCH_FAILED, diagnostics));
assertEquals(YarnApplicationAttemptState.ALLOCATED,
applicationAttempt.createApplicationAttemptState());
testAppAttemptFailedState(amContainer, diagnostics);
}
@ParameterizedTest
@MethodSource("getTestParameters")
@Timeout(value = 10)
public void testAllocatedToRunning(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
// Register attempt event arrives before launched attempt event
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
launchApplicationAttempt(amContainer, RMAppAttemptState.RUNNING);
}
@ParameterizedTest
@MethodSource("getTestParameters")
@Timeout(value = 10)
public void testCreateAppAttemptReport(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
RMAppAttemptState[] attemptStates = RMAppAttemptState.values();
applicationAttempt.handle(new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(), RMAppAttemptEventType.KILL));
// ALL RMAppAttemptState TO BE CHECK
RMAppAttempt attempt = spy(applicationAttempt);
for (RMAppAttemptState rmAppAttemptState : attemptStates) {
when(attempt.getState()).thenReturn(rmAppAttemptState);
attempt.createApplicationAttemptReport();
}
}
@Timeout(value = 10)
@ParameterizedTest
@MethodSource("getTestParameters")
public void testLaunchedAtFinalSaving(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
// ALLOCATED->FINAL_SAVING
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.KILL));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
// verify for both launched and launch_failed transitions in final_saving
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.LAUNCHED));
applicationAttempt.handle(
new RMAppAttemptEvent(applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.LAUNCH_FAILED, "Launch Failed"));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
testAppAttemptKilledState(amContainer, EMPTY_DIAGNOSTICS);
// verify for both launched and launch_failed transitions in killed
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.LAUNCHED));
applicationAttempt.handle(new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.LAUNCH_FAILED, "Launch Failed"));
assertEquals(RMAppAttemptState.KILLED,
applicationAttempt.getAppAttemptState());
}
@Timeout(value = 10)
@ParameterizedTest
@MethodSource("getTestParameters")
public void testAttemptAddedAtFinalSaving(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
submitApplicationAttempt();
// SUBMITTED->FINAL_SAVING
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.KILL));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.ATTEMPT_ADDED));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
}
@Timeout(value = 10)
@ParameterizedTest
@MethodSource("getTestParameters")
public void testAttemptRegisteredAtFailed(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
//send CONTAINER_FINISHED event
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), BuilderUtils.newContainerStatus(
amContainer.getId(), ContainerState.COMPLETE, "", 0,
amContainer.getResource()), anyNodeId));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
//send REGISTERED event
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.REGISTERED));
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testAttemptLaunchFailedAtFailed(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
//send CONTAINER_FINISHED event
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), BuilderUtils.newContainerStatus(
amContainer.getId(), ContainerState.COMPLETE, "", 0,
amContainer.getResource()), anyNodeId));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
//send LAUNCH_FAILED event
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.LAUNCH_FAILED));
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testAMCrashAtAllocated(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
String containerDiagMsg = "some error";
int exitCode = 123;
ContainerStatus cs =
BuilderUtils.newContainerStatus(amContainer.getId(),
ContainerState.COMPLETE, containerDiagMsg, exitCode,
amContainer.getResource());
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), cs, anyNodeId));
assertEquals(YarnApplicationAttemptState.ALLOCATED,
applicationAttempt.createApplicationAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
verifyTokenCount(applicationAttempt.getAppAttemptId(), 1);
verifyApplicationAttemptFinished(RMAppAttemptState.FAILED);
boolean shouldCheckURL = (applicationAttempt.getTrackingUrl() != null);
verifyAMCrashAtAllocatedDiagnosticInfo(applicationAttempt.getDiagnostics(),
exitCode, shouldCheckURL);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testRunningToFailed(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
String containerDiagMsg = "some error";
int exitCode = 123;
ContainerStatus cs = BuilderUtils.newContainerStatus(amContainer.getId(),
ContainerState.COMPLETE, containerDiagMsg, exitCode,
amContainer.getResource());
ApplicationAttemptId appAttemptId = applicationAttempt.getAppAttemptId();
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
appAttemptId, cs, anyNodeId));
// ignored ContainerFinished and Expire at FinalSaving if we were supposed
// to Failed state.
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), BuilderUtils.newContainerStatus(
amContainer.getId(), ContainerState.COMPLETE, "", 0,
amContainer.getResource()), anyNodeId));
applicationAttempt.handle(new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(), RMAppAttemptEventType.EXPIRE));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
assertEquals(YarnApplicationAttemptState.RUNNING,
applicationAttempt.createApplicationAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
assertEquals(0, applicationAttempt.getJustFinishedContainers().size());
assertEquals(amContainer, applicationAttempt.getMasterContainer());
assertEquals(0, application.getRanNodes().size());
String rmAppPageUrl = pjoin(RM_WEBAPP_ADDR, "cluster", "app",
applicationAttempt.getAppAttemptId().getApplicationId());
assertEquals(rmAppPageUrl, applicationAttempt.getOriginalTrackingUrl());
assertEquals(rmAppPageUrl, applicationAttempt.getTrackingUrl());
verifyAMHostAndPortInvalidated();
verifyApplicationAttemptFinished(RMAppAttemptState.FAILED);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testRunningToKilled(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
applicationAttempt.handle(
new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.KILL));
// ignored ContainerFinished and Expire at FinalSaving if we were supposed
// to Killed state.
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), BuilderUtils.newContainerStatus(
amContainer.getId(), ContainerState.COMPLETE, "", 0,
amContainer.getResource()), anyNodeId));
applicationAttempt.handle(new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(), RMAppAttemptEventType.EXPIRE));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
assertEquals(YarnApplicationAttemptState.RUNNING,
applicationAttempt.createApplicationAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.KILLED,
applicationAttempt.getAppAttemptState());
assertEquals(0, applicationAttempt.getJustFinishedContainers().size());
assertEquals(amContainer, applicationAttempt.getMasterContainer());
assertEquals(0, application.getRanNodes().size());
String rmAppPageUrl = pjoin(RM_WEBAPP_ADDR, "cluster", "app",
applicationAttempt.getAppAttemptId().getApplicationId());
assertEquals(rmAppPageUrl, applicationAttempt.getOriginalTrackingUrl());
assertEquals(rmAppPageUrl, applicationAttempt.getTrackingUrl());
verifyTokenCount(applicationAttempt.getAppAttemptId(), 1);
verifyAMHostAndPortInvalidated();
verifyApplicationAttemptFinished(RMAppAttemptState.KILLED);
}
@Timeout(value = 10)
@ParameterizedTest
@MethodSource("getTestParameters")
public void testLaunchedExpire(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
applicationAttempt.handle(new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(), RMAppAttemptEventType.EXPIRE));
assertEquals(YarnApplicationAttemptState.LAUNCHED,
applicationAttempt.createApplicationAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
assertTrue(applicationAttempt.getDiagnostics().contains("timed out"),
"expire diagnostics missing");
String rmAppPageUrl = pjoin(RM_WEBAPP_ADDR, "cluster", "app",
applicationAttempt.getAppAttemptId().getApplicationId());
assertEquals(rmAppPageUrl, applicationAttempt.getOriginalTrackingUrl());
assertEquals(rmAppPageUrl, applicationAttempt.getTrackingUrl());
verifyTokenCount(applicationAttempt.getAppAttemptId(), 1);
verifyApplicationAttemptFinished(RMAppAttemptState.FAILED);
}
@SuppressWarnings("unchecked")
@Timeout(value = 10)
@ParameterizedTest
@MethodSource("getTestParameters")
public void testLaunchedFailWhileAHSEnabled(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Configuration myConf = new Configuration(conf);
myConf.setBoolean(YarnConfiguration.APPLICATION_HISTORY_ENABLED, true);
ApplicationId applicationId = MockApps.newAppID(appId);
ApplicationAttemptId applicationAttemptId =
ApplicationAttemptId.newInstance(applicationId, 2);
RMAppAttempt myApplicationAttempt =
new RMAppAttemptImpl(applicationAttempt.getAppAttemptId(),
spyRMContext, scheduler,masterService,
submissionContext, myConf,
Collections.singletonList(BuilderUtils.newResourceRequest(
RMAppAttemptImpl.AM_CONTAINER_PRIORITY, ResourceRequest.ANY,
submissionContext.getResource(), 1)), application);
//submit, schedule and allocate app attempt
myApplicationAttempt.handle(
new RMAppAttemptEvent(myApplicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.START));
myApplicationAttempt.handle(
new RMAppAttemptEvent(
myApplicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.ATTEMPT_ADDED));
Container amContainer = mock(Container.class);
Resource resource = Resources.createResource(2048);
when(amContainer.getId()).thenReturn(
BuilderUtils.newContainerId(myApplicationAttempt.getAppAttemptId(), 1));
when(amContainer.getResource()).thenReturn(resource);
Allocation allocation = mock(Allocation.class);
when(allocation.getContainers()).
thenReturn(Collections.singletonList(amContainer));
when(scheduler.allocate(any(ApplicationAttemptId.class), any(List.class),
any(), any(List.class), any(), any(),
any(ContainerUpdates.class)))
.thenReturn(allocation);
RMContainer rmContainer = mock(RMContainerImpl.class);
when(scheduler.getRMContainer(amContainer.getId())).thenReturn(rmContainer);
myApplicationAttempt.handle(
new RMAppAttemptEvent(myApplicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.CONTAINER_ALLOCATED));
assertEquals(RMAppAttemptState.ALLOCATED_SAVING,
myApplicationAttempt.getAppAttemptState());
myApplicationAttempt.handle(
new RMAppAttemptEvent(myApplicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.ATTEMPT_NEW_SAVED));
// launch app attempt
myApplicationAttempt.handle(
new RMAppAttemptEvent(myApplicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.LAUNCHED));
assertEquals(YarnApplicationAttemptState.LAUNCHED,
myApplicationAttempt.createApplicationAttemptState());
//fail container right after launched
NodeId anyNodeId = NodeId.newInstance("host", 1234);
myApplicationAttempt.handle(
new RMAppAttemptContainerFinishedEvent(
myApplicationAttempt.getAppAttemptId(),
BuilderUtils.newContainerStatus(amContainer.getId(),
ContainerState.COMPLETE, "", 0,
amContainer.getResource()), anyNodeId));
sendAttemptUpdateSavedEvent(myApplicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
myApplicationAttempt.getAppAttemptState());
String rmAppPageUrl = pjoin(AHS_WEBAPP_ADDR, "applicationhistory", "app",
myApplicationAttempt.getAppAttemptId().getApplicationId());
assertEquals(rmAppPageUrl, myApplicationAttempt.getOriginalTrackingUrl());
assertEquals(rmAppPageUrl, myApplicationAttempt.getTrackingUrl());
}
@Timeout(value = 20)
@ParameterizedTest
@MethodSource("getTestParameters")
public void testRunningExpire(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
applicationAttempt.handle(new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(), RMAppAttemptEventType.EXPIRE));
assertEquals(YarnApplicationAttemptState.RUNNING,
applicationAttempt.createApplicationAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
assertTrue(applicationAttempt.getDiagnostics().contains("timed out"),
"expire diagnostics missing");
String rmAppPageUrl = pjoin(RM_WEBAPP_ADDR, "cluster", "app",
applicationAttempt.getAppAttemptId().getApplicationId());
assertEquals(rmAppPageUrl, applicationAttempt.getOriginalTrackingUrl());
assertEquals(rmAppPageUrl, applicationAttempt.getTrackingUrl());
verifyTokenCount(applicationAttempt.getAppAttemptId(), 1);
verifyAMHostAndPortInvalidated();
verifyApplicationAttemptFinished(RMAppAttemptState.FAILED);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testUnregisterToKilledFinishing(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
unregisterApplicationAttempt(amContainer,
FinalApplicationStatus.KILLED, "newtrackingurl",
"Killed by user");
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testTrackingUrlUnmanagedAM(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
testUnmanagedAMSuccess("oldTrackingUrl");
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testEmptyTrackingUrlUnmanagedAM(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
testUnmanagedAMSuccess("");
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testNullTrackingUrlUnmanagedAM(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
testUnmanagedAMSuccess(null);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testManagedAMWithTrackingUrl(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
testTrackingUrlManagedAM("theTrackingUrl");
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testManagedAMWithEmptyTrackingUrl(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
testTrackingUrlManagedAM("");
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testManagedAMWithNullTrackingUrl(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
testTrackingUrlManagedAM(null);
}
private void testTrackingUrlManagedAM(String url) {
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, url, false);
unregisterApplicationAttempt(amContainer,
FinalApplicationStatus.SUCCEEDED, url, "Successful");
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testUnregisterToSuccessfulFinishing(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
unregisterApplicationAttempt(amContainer,
FinalApplicationStatus.SUCCEEDED, "mytrackingurl", "Successful");
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testFinishingKill(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
FinalApplicationStatus finalStatus = FinalApplicationStatus.FAILED;
String trackingUrl = "newtrackingurl";
String diagnostics = "Job failed";
unregisterApplicationAttempt(amContainer, finalStatus, trackingUrl,
diagnostics);
applicationAttempt.handle(
new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.KILL));
testAppAttemptFinishingState(amContainer, finalStatus, trackingUrl,
diagnostics);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testFinishingExpire(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
FinalApplicationStatus finalStatus = FinalApplicationStatus.SUCCEEDED;
String trackingUrl = "mytrackingurl";
String diagnostics = "Successful";
unregisterApplicationAttempt(amContainer, finalStatus, trackingUrl,
diagnostics);
applicationAttempt.handle(
new RMAppAttemptEvent(
applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.EXPIRE));
testAppAttemptFinishedState(amContainer, finalStatus, trackingUrl,
diagnostics, 0, false);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testFinishingToFinishing(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
FinalApplicationStatus finalStatus = FinalApplicationStatus.SUCCEEDED;
String trackingUrl = "mytrackingurl";
String diagnostics = "Successful";
unregisterApplicationAttempt(amContainer, finalStatus, trackingUrl,
diagnostics);
// container must be AM container to move from FINISHING to FINISHED
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(
new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(),
BuilderUtils.newContainerStatus(
BuilderUtils.newContainerId(
applicationAttempt.getAppAttemptId(), 42),
ContainerState.COMPLETE, "", 0,
amContainer.getResource()), anyNodeId));
testAppAttemptFinishingState(amContainer, finalStatus, trackingUrl,
diagnostics);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testSuccessfulFinishingToFinished(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
FinalApplicationStatus finalStatus = FinalApplicationStatus.SUCCEEDED;
String trackingUrl = "mytrackingurl";
String diagnostics = "Successful";
unregisterApplicationAttempt(amContainer, finalStatus, trackingUrl,
diagnostics);
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(
new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(),
BuilderUtils.newContainerStatus(amContainer.getId(),
ContainerState.COMPLETE, "", 0,
amContainer.getResource()), anyNodeId));
testAppAttemptFinishedState(amContainer, finalStatus, trackingUrl,
diagnostics, 0, false);
}
// While attempt is at FINAL_SAVING, Contaienr_Finished event may come before
// Attempt_Saved event, we stay on FINAL_SAVING on Container_Finished event
// and then directly jump from FINAL_SAVING to FINISHED state on Attempt_Saved
// event
@ParameterizedTest
@MethodSource("getTestParameters")
public void testFinalSavingToFinishedWithContainerFinished(boolean pIsSecurityEnabled)
throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
FinalApplicationStatus finalStatus = FinalApplicationStatus.SUCCEEDED;
String trackingUrl = "mytrackingurl";
String diagnostics = "Successful";
applicationAttempt.handle(new RMAppAttemptUnregistrationEvent(
applicationAttempt.getAppAttemptId(), trackingUrl, finalStatus,
diagnostics));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
assertEquals(YarnApplicationAttemptState.RUNNING,
applicationAttempt.createApplicationAttemptState());
// Container_finished event comes before Attempt_Saved event.
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), BuilderUtils.newContainerStatus(
amContainer.getId(), ContainerState.COMPLETE, "", 0,
amContainer.getResource()), anyNodeId));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
// send attempt_saved
sendAttemptUpdateSavedEvent(applicationAttempt);
testAppAttemptFinishedState(amContainer, finalStatus, trackingUrl,
diagnostics, 0, false);
}
// While attempt is at FINAL_SAVING, Expire event may come before
// Attempt_Saved event, we stay on FINAL_SAVING on Expire event and then
// directly jump from FINAL_SAVING to FINISHED state on Attempt_Saved event.
@ParameterizedTest
@MethodSource("getTestParameters")
public void testFinalSavingToFinishedWithExpire(boolean pIsSecurityEnabled)
throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
FinalApplicationStatus finalStatus = FinalApplicationStatus.SUCCEEDED;
String trackingUrl = "mytrackingurl";
String diagnostics = "Successssseeeful";
applicationAttempt.handle(new RMAppAttemptUnregistrationEvent(
applicationAttempt.getAppAttemptId(), trackingUrl, finalStatus,
diagnostics));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
assertEquals(YarnApplicationAttemptState.RUNNING,
applicationAttempt.createApplicationAttemptState());
// Expire event comes before Attempt_saved event.
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.EXPIRE));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
// send attempt_saved
sendAttemptUpdateSavedEvent(applicationAttempt);
testAppAttemptFinishedState(amContainer, finalStatus, trackingUrl,
diagnostics, 0, false);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testFinishedContainer(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
// Complete one container
ContainerId containerId1 = BuilderUtils.newContainerId(applicationAttempt
.getAppAttemptId(), 2);
Container container1 = mock(Container.class);
ContainerStatus containerStatus1 = mock(ContainerStatus.class);
when(container1.getId()).thenReturn(
containerId1);
when(containerStatus1.getContainerId()).thenReturn(containerId1);
when(container1.getNodeId()).thenReturn(NodeId.newInstance("host", 1234));
application.handle(new RMAppRunningOnNodeEvent(application
.getApplicationId(),
container1.getNodeId()));
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), containerStatus1,
container1.getNodeId()));
ArgumentCaptor<RMNodeFinishedContainersPulledByAMEvent> captor =
ArgumentCaptor.forClass(RMNodeFinishedContainersPulledByAMEvent.class);
// Verify justFinishedContainers
assertEquals(1, applicationAttempt.getJustFinishedContainers()
.size());
assertEquals(container1.getId(), applicationAttempt
.getJustFinishedContainers().get(0).getContainerId());
assertEquals(0, getFinishedContainersSentToAM(applicationAttempt)
.size());
// Verify finishedContainersSentToAM gets container after pull
List<ContainerStatus> containerStatuses = applicationAttempt
.pullJustFinishedContainers();
assertEquals(1, containerStatuses.size());
Mockito.verify(rmnodeEventHandler, never()).handle(Mockito
.any(RMNodeEvent.class));
assertTrue(applicationAttempt.getJustFinishedContainers().isEmpty());
assertEquals(1, getFinishedContainersSentToAM(applicationAttempt)
.size());
// Verify container is acked to NM via the RMNodeEvent after second pull
containerStatuses = applicationAttempt.pullJustFinishedContainers();
assertEquals(0, containerStatuses.size());
Mockito.verify(rmnodeEventHandler).handle(captor.capture());
assertEquals(container1.getId(), captor.getValue().getContainers()
.get(0));
assertTrue(applicationAttempt.getJustFinishedContainers().isEmpty());
assertEquals(0, getFinishedContainersSentToAM(applicationAttempt)
.size());
// verify if no containers to acknowledge to NM then event should not be
// triggered. Number of times event invoked is 1 i.e on second pull
containerStatuses = applicationAttempt.pullJustFinishedContainers();
assertEquals(0, containerStatuses.size());
Mockito.verify(rmnodeEventHandler, times(1))
.handle(Mockito.any(RMNodeEvent.class));
}
/**
* Check a completed container that is not yet pulled by AM heartbeat,
* is ACKed to NM for cleanup when the AM container exits.
*/
@ParameterizedTest
@MethodSource("getTestParameters")
public void testFinishedContainerNotBeingPulledByAMHeartbeat(
boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
application.handle(new RMAppRunningOnNodeEvent(application
.getApplicationId(), amContainer.getNodeId()));
// Complete a non-AM container
ContainerId containerId1 = BuilderUtils.newContainerId(applicationAttempt
.getAppAttemptId(), 2);
Container container1 = mock(Container.class);
ContainerStatus containerStatus1 = mock(ContainerStatus.class);
when(container1.getId()).thenReturn(
containerId1);
when(containerStatus1.getContainerId()).thenReturn(containerId1);
when(container1.getNodeId()).thenReturn(NodeId.newInstance("host", 1234));
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), containerStatus1,
container1.getNodeId()));
// Verify justFinishedContainers
ArgumentCaptor<RMNodeFinishedContainersPulledByAMEvent> captor =
ArgumentCaptor.forClass(RMNodeFinishedContainersPulledByAMEvent.class);
assertEquals(1, applicationAttempt.getJustFinishedContainers()
.size());
assertEquals(container1.getId(), applicationAttempt
.getJustFinishedContainers().get(0).getContainerId());
assertTrue(
getFinishedContainersSentToAM(applicationAttempt).isEmpty());
// finish AM container to emulate AM exit event
containerStatus1 = mock(ContainerStatus.class);
ContainerId amContainerId = amContainer.getId();
when(containerStatus1.getContainerId()).thenReturn(amContainerId);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), containerStatus1,
amContainer.getNodeId()));
Mockito.verify(rmnodeEventHandler, times(2)).handle(captor.capture());
List<RMNodeFinishedContainersPulledByAMEvent> containerPulledEvents =
captor.getAllValues();
// Verify AM container is acked to NM via the RMNodeEvent immediately
assertEquals(amContainer.getId(),
containerPulledEvents.get(0).getContainers().get(0));
// Verify the non-AM container is acked to NM via the RMNodeEvent
assertEquals(container1.getId(),
containerPulledEvents.get(1).getContainers().get(0));
assertTrue(applicationAttempt.getJustFinishedContainers().isEmpty(),
"No container shall be added to justFinishedContainers" +
" as soon as AM container exits");
assertTrue(
getFinishedContainersSentToAM(applicationAttempt).isEmpty());
}
/**
* Check a completed container is ACKed to NM for cleanup after the AM
* container has exited.
*/
@ParameterizedTest
@MethodSource("getTestParameters")
public void testFinishedContainerAfterAMExit(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
// finish AM container to emulate AM exit event
ContainerStatus containerStatus1 = mock(ContainerStatus.class);
ContainerId amContainerId = amContainer.getId();
when(containerStatus1.getContainerId()).thenReturn(amContainerId);
application.handle(new RMAppRunningOnNodeEvent(application
.getApplicationId(),
amContainer.getNodeId()));
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), containerStatus1,
amContainer.getNodeId()));
// Verify AM container is acked to NM via the RMNodeEvent immediately
ArgumentCaptor<RMNodeFinishedContainersPulledByAMEvent> captor =
ArgumentCaptor.forClass(RMNodeFinishedContainersPulledByAMEvent.class);
Mockito.verify(rmnodeEventHandler).handle(captor.capture());
assertEquals(amContainer.getId(),
captor.getValue().getContainers().get(0));
// Complete a non-AM container
ContainerId containerId1 = BuilderUtils.newContainerId(applicationAttempt
.getAppAttemptId(), 2);
Container container1 = mock(Container.class);
containerStatus1 = mock(ContainerStatus.class);
when(container1.getId()).thenReturn(containerId1);
when(containerStatus1.getContainerId()).thenReturn(containerId1);
when(container1.getNodeId()).thenReturn(NodeId.newInstance("host", 1234));
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), containerStatus1,
container1.getNodeId()));
// Verify container is acked to NM via the RMNodeEvent immediately
captor = ArgumentCaptor.forClass(
RMNodeFinishedContainersPulledByAMEvent.class);
Mockito.verify(rmnodeEventHandler, times(2)).handle(captor.capture());
assertEquals(container1.getId(),
captor.getAllValues().get(1).getContainers().get(0));
assertTrue(applicationAttempt.getJustFinishedContainers().isEmpty(),
"No container shall be added to justFinishedContainers" +
" after AM container exited");
assertTrue(getFinishedContainersSentToAM(applicationAttempt).isEmpty());
}
private static List<ContainerStatus> getFinishedContainersSentToAM(
RMAppAttempt applicationAttempt) {
List<ContainerStatus> containers = new ArrayList<ContainerStatus>();
for (List<ContainerStatus> containerStatuses: applicationAttempt
.getFinishedContainersSentToAMReference().values()) {
containers.addAll(containerStatuses);
}
return containers;
}
// this is to test user can get client tokens only after the client token
// master key is saved in the state store and also registered in
// ClientTokenSecretManager
@ParameterizedTest
@MethodSource("getTestParameters")
public void testGetClientToken(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
assumeTrue(isSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
// before attempt is launched, can not get ClientToken
Token<ClientToAMTokenIdentifier> token =
applicationAttempt.createClientToken(null);
assertNull(token);
launchApplicationAttempt(amContainer);
// after attempt is launched , can get ClientToken
token = applicationAttempt.createClientToken(null);
assertNull(token);
token = applicationAttempt.createClientToken("clientuser");
assertNotNull(token);
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.KILL));
assertEquals(YarnApplicationAttemptState.LAUNCHED,
applicationAttempt.createApplicationAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
// after attempt is killed, can not get Client Token
token = applicationAttempt.createClientToken(null);
assertNull(token);
token = applicationAttempt.createClientToken("clientuser");
assertNull(token);
}
// this is to test master key is saved in the secret manager only after
// attempt is launched and in secure-mode
@ParameterizedTest
@MethodSource("getTestParameters")
public void testApplicationAttemptMasterKey(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
ApplicationAttemptId appid = applicationAttempt.getAppAttemptId();
boolean isMasterKeyExisted = clientToAMTokenManager.hasMasterKey(appid);
if (isSecurityEnabled) {
assertTrue(isMasterKeyExisted);
assertNotNull(clientToAMTokenManager.getMasterKey(appid));
} else {
assertFalse(isMasterKeyExisted);
}
launchApplicationAttempt(amContainer);
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.KILL));
assertEquals(YarnApplicationAttemptState.LAUNCHED,
applicationAttempt.createApplicationAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
// after attempt is killed, can not get MasterKey
isMasterKeyExisted = clientToAMTokenManager.hasMasterKey(appid);
assertFalse(isMasterKeyExisted);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testFailedToFailed(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
// create a failed attempt.
when(submissionContext.getKeepContainersAcrossApplicationAttempts())
.thenReturn(true);
when(application.getMaxAppAttempts()).thenReturn(2);
when(application.getNumFailedAppAttempts()).thenReturn(1);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
ContainerStatus cs1 =
ContainerStatus.newInstance(amContainer.getId(),
ContainerState.COMPLETE, "some error", 123);
ApplicationAttemptId appAttemptId = applicationAttempt.getAppAttemptId();
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
appAttemptId, cs1, anyNodeId));
assertEquals(YarnApplicationAttemptState.RUNNING,
applicationAttempt.createApplicationAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
// should not kill containers when attempt fails.
assertTrue(transferStateFromPreviousAttempt);
verifyApplicationAttemptFinished(RMAppAttemptState.FAILED);
// failed attempt captured the container finished event.
assertEquals(0, applicationAttempt.getJustFinishedContainers().size());
ContainerStatus cs2 =
ContainerStatus.newInstance(ContainerId.newContainerId(appAttemptId, 2),
ContainerState.COMPLETE, "", 0);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
appAttemptId, cs2, anyNodeId));
assertEquals(1, applicationAttempt.getJustFinishedContainers().size());
boolean found = false;
for (ContainerStatus containerStatus:applicationAttempt
.getJustFinishedContainers()) {
if (cs2.getContainerId().equals(containerStatus.getContainerId())) {
found = true;
}
}
assertTrue(found);
}
@ParameterizedTest
@MethodSource("getTestParameters")
public void testContainerRemovedBeforeAllocate(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
scheduleApplicationAttempt();
// Mock the allocation of AM container
Container container = mock(Container.class);
Resource resource = Resources.createResource(2048);
when(container.getId()).thenReturn(
BuilderUtils.newContainerId(applicationAttempt.getAppAttemptId(), 1));
when(container.getResource()).thenReturn(resource);
Allocation allocation = mock(Allocation.class);
when(allocation.getContainers()).
thenReturn(Collections.singletonList(container));
when(scheduler.allocate(any(ApplicationAttemptId.class), any(List.class),
any(), any(), any(), any(),
any(ContainerUpdates.class))).
thenReturn(allocation);
//container removed, so return null
when(scheduler.getRMContainer(container.getId())).
thenReturn(null);
applicationAttempt.handle(
new RMAppAttemptEvent(applicationAttempt.getAppAttemptId(),
RMAppAttemptEventType.CONTAINER_ALLOCATED));
assertEquals(RMAppAttemptState.SCHEDULED,
applicationAttempt.getAppAttemptState());
}
@SuppressWarnings("deprecation")
@ParameterizedTest
@MethodSource("getTestParameters")
public void testContainersCleanupForLastAttempt(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
// create a failed attempt.
applicationAttempt =
new RMAppAttemptImpl(applicationAttempt.getAppAttemptId(), spyRMContext,
scheduler, masterService, submissionContext, new Configuration(),
Collections.singletonList(BuilderUtils.newResourceRequest(
RMAppAttemptImpl.AM_CONTAINER_PRIORITY, ResourceRequest.ANY,
submissionContext.getResource(), 1)), application);
when(submissionContext.getKeepContainersAcrossApplicationAttempts())
.thenReturn(true);
when(submissionContext.getMaxAppAttempts()).thenReturn(1);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
ContainerStatus cs1 =
ContainerStatus.newInstance(amContainer.getId(),
ContainerState.COMPLETE, "some error", 123);
ApplicationAttemptId appAttemptId = applicationAttempt.getAppAttemptId();
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
appAttemptId, cs1, anyNodeId));
assertEquals(YarnApplicationAttemptState.RUNNING,
applicationAttempt.createApplicationAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
assertFalse(transferStateFromPreviousAttempt);
verifyApplicationAttemptFinished(RMAppAttemptState.FAILED);
}
@SuppressWarnings("unchecked")
@ParameterizedTest
@MethodSource("getTestParameters")
public void testScheduleTransitionReplaceAMContainerRequestWithDefaults(
boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
YarnScheduler mockScheduler = mock(YarnScheduler.class);
when(mockScheduler.allocate(any(ApplicationAttemptId.class),
any(List.class), any(List.class), any(List.class), any(List.class), any(List.class),
any(ContainerUpdates.class)))
.thenAnswer(new Answer<Allocation>() {
@SuppressWarnings("rawtypes")
@Override
public Allocation answer(InvocationOnMock invocation)
throws Throwable {
ResourceRequest rr =
(ResourceRequest) ((List) invocation.getArguments()[1]).get(0);
// capacity shouldn't changed
assertEquals(Resource.newInstance(3333, 1), rr.getCapability());
assertEquals("label-expression", rr.getNodeLabelExpression());
// priority, #container, relax-locality will be changed
assertEquals(RMAppAttemptImpl.AM_CONTAINER_PRIORITY, rr.getPriority());
assertEquals(1, rr.getNumContainers());
assertEquals(ResourceRequest.ANY, rr.getResourceName());
// just return an empty allocation
List l = new ArrayList();
Set s = new HashSet();
return new Allocation(l, Resources.none(), s, s, l);
}
});
// create an attempt.
applicationAttempt =
new RMAppAttemptImpl(applicationAttempt.getAppAttemptId(),
spyRMContext, scheduler, masterService, submissionContext,
new Configuration(), Collections.singletonList(
ResourceRequest.newInstance(Priority.UNDEFINED, "host1",
Resource.newInstance(3333, 1), 3,
false, "label-expression")), application);
new RMAppAttemptImpl.ScheduleTransition().transition(
(RMAppAttemptImpl) applicationAttempt, null);
}
@Timeout(value = 30)
@ParameterizedTest
@MethodSource("getTestParameters")
public void testNewToFailed(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.FAIL, FAILED_DIAGNOSTICS));
assertEquals(YarnApplicationAttemptState.NEW,
applicationAttempt.createApplicationAttemptState());
testAppAttemptFailedState(null, FAILED_DIAGNOSTICS);
verifyTokenCount(applicationAttempt.getAppAttemptId(), 1);
}
@Timeout(value = 30)
@ParameterizedTest
@MethodSource("getTestParameters")
public void testSubmittedToFailed(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
submitApplicationAttempt();
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.FAIL, FAILED_DIAGNOSTICS));
assertEquals(YarnApplicationAttemptState.SUBMITTED,
applicationAttempt.createApplicationAttemptState());
testAppAttemptFailedState(null, FAILED_DIAGNOSTICS);
}
@Timeout(value = 30)
@ParameterizedTest
@MethodSource("getTestParameters")
public void testScheduledToFailed(boolean pIsSecurityEnabled) throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
scheduleApplicationAttempt();
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.FAIL, FAILED_DIAGNOSTICS));
assertEquals(YarnApplicationAttemptState.SCHEDULED,
applicationAttempt.createApplicationAttemptState());
testAppAttemptFailedState(null, FAILED_DIAGNOSTICS);
}
@Timeout(value = 30)
@ParameterizedTest
@MethodSource("getTestParameters")
public void testAllocatedToFailedUserTriggeredFailEvent(boolean pIsSecurityEnabled)
throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
assertEquals(YarnApplicationAttemptState.ALLOCATED,
applicationAttempt.createApplicationAttemptState());
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.FAIL, FAILED_DIAGNOSTICS));
testAppAttemptFailedState(amContainer, FAILED_DIAGNOSTICS);
}
@Timeout(value = 30)
@ParameterizedTest
@MethodSource("getTestParameters")
public void testRunningToFailedUserTriggeredFailEvent(boolean pIsSecurityEnabled)
throws Exception {
initTestRMAppAttemptTransitions(pIsSecurityEnabled);
Container amContainer = allocateApplicationAttempt();
launchApplicationAttempt(amContainer);
runApplicationAttempt(amContainer, "host", 8042, "oldtrackingurl", false);
applicationAttempt.handle(new RMAppAttemptEvent(applicationAttempt
.getAppAttemptId(), RMAppAttemptEventType.FAIL, FAILED_DIAGNOSTICS));
assertEquals(RMAppAttemptState.FINAL_SAVING,
applicationAttempt.getAppAttemptState());
sendAttemptUpdateSavedEvent(applicationAttempt);
assertEquals(RMAppAttemptState.FAILED,
applicationAttempt.getAppAttemptState());
NodeId anyNodeId = NodeId.newInstance("host", 1234);
applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
applicationAttempt.getAppAttemptId(), BuilderUtils.newContainerStatus(
amContainer.getId(), ContainerState.COMPLETE, "", 0,
amContainer.getResource()), anyNodeId));
assertEquals(1, applicationAttempt.getJustFinishedContainers().size());
assertEquals(amContainer, applicationAttempt.getMasterContainer());
assertEquals(0, application.getRanNodes().size());
String rmAppPageUrl =
pjoin(RM_WEBAPP_ADDR, "cluster", "app", applicationAttempt
.getAppAttemptId().getApplicationId());
assertEquals(rmAppPageUrl, applicationAttempt.getOriginalTrackingUrl());
assertEquals(rmAppPageUrl, applicationAttempt.getTrackingUrl());
verifyAMHostAndPortInvalidated();
verifyApplicationAttemptFinished(RMAppAttemptState.FAILED);
}
private void verifyAMCrashAtAllocatedDiagnosticInfo(String diagnostics,
int exitCode, boolean shouldCheckURL) {
assertTrue(diagnostics.contains("logs"),
"Diagnostic information does not point the logs to the users");
assertTrue(diagnostics.contains(applicationAttempt.getAppAttemptId().toString()),
"Diagnostic information does not contain application attempt id");
assertTrue(diagnostics.contains("exitCode: " + exitCode),
"Diagnostic information does not contain application exit code");
if (shouldCheckURL) {
assertTrue(diagnostics.contains(applicationAttempt.getTrackingUrl()),
"Diagnostic information does not contain application proxy URL");
}
}
private void verifyTokenCount(ApplicationAttemptId appAttemptId, int count) {
verify(amRMTokenManager, times(count)).applicationMasterFinished(appAttemptId);
if (UserGroupInformation.isSecurityEnabled()) {
verify(clientToAMTokenManager, times(count)).unRegisterApplication(appAttemptId);
if (count > 0) {
assertNull(applicationAttempt.createClientToken("client"));
}
}
}
private void verifyUrl(String url1, String url2) {
if (url1 == null || url1.trim().isEmpty()) {
assertEquals("N/A", url2);
} else {
assertEquals(url1, url2);
}
}
private void verifyAttemptFinalStateSaved() {
verify(store, times(1)).updateApplicationAttemptState(
any(ApplicationAttemptStateData.class));
}
private void verifyAMHostAndPortInvalidated() {
assertEquals("N/A", applicationAttempt.getHost());
assertEquals(-1, applicationAttempt.getRpcPort());
}
private void verifyApplicationAttemptFinished(RMAppAttemptState state) {
ArgumentCaptor<RMAppAttemptState> finalState =
ArgumentCaptor.forClass(RMAppAttemptState.class);
verify(writer).applicationAttemptFinished(
any(RMAppAttempt.class), finalState.capture());
assertEquals(state, finalState.getValue());
finalState =
ArgumentCaptor.forClass(RMAppAttemptState.class);
verify(publisher).appAttemptFinished(any(RMAppAttempt.class), finalState.capture(),
any(RMApp.class), anyLong());
assertEquals(state, finalState.getValue());
}
}
| TestAMLauncherEventDispatcher |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java | {
"start": 1482,
"end": 2012
} | class ____ {
@Test
void happyPath() throws Exception {
testFilterInvocation(null);
}
@Test
void withException() throws Exception {
testFilterInvocation(new ServletException());
}
private void testFilterInvocation(final ServletException sex) throws Exception {
final MockHttpServletRequest req = new MockHttpServletRequest();
req.setAttribute("myAttr", "myValue");
final MockHttpServletResponse resp = new MockHttpServletResponse();
// Expect one invocation by the filter being tested
| RequestContextFilterTests |
java | elastic__elasticsearch | x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/action/TransportPutSamlServiceProviderAction.java | {
"start": 1450,
"end": 7484
} | class ____ extends HandledTransportAction<
PutSamlServiceProviderRequest,
PutSamlServiceProviderResponse> {
private static final Logger logger = LogManager.getLogger(TransportPutSamlServiceProviderAction.class);
private final SamlServiceProviderIndex index;
private final SamlIdentityProvider identityProvider;
private final Clock clock;
@Inject
public TransportPutSamlServiceProviderAction(
TransportService transportService,
ActionFilters actionFilters,
SamlServiceProviderIndex index,
SamlIdentityProvider identityProvider
) {
this(transportService, actionFilters, index, identityProvider, Clock.systemUTC());
}
TransportPutSamlServiceProviderAction(
TransportService transportService,
ActionFilters actionFilters,
SamlServiceProviderIndex index,
SamlIdentityProvider identityProvider,
Clock clock
) {
super(
PutSamlServiceProviderAction.NAME,
transportService,
actionFilters,
PutSamlServiceProviderRequest::new,
EsExecutors.DIRECT_EXECUTOR_SERVICE
);
this.index = index;
this.identityProvider = identityProvider;
this.clock = clock;
}
@Override
protected void doExecute(
Task task,
final PutSamlServiceProviderRequest request,
final ActionListener<PutSamlServiceProviderResponse> listener
) {
final SamlServiceProviderDocument document = request.getDocument();
if (document.docId != null) {
listener.onFailure(new IllegalArgumentException("request document must not have an id [" + document.docId + "]"));
return;
}
if (document.nameIdFormat != null && identityProvider.getAllowedNameIdFormats().contains(document.nameIdFormat) == false) {
listener.onFailure(new IllegalArgumentException("NameID format [" + document.nameIdFormat + "] is not supported."));
return;
}
logger.trace("Searching for existing ServiceProvider with id [{}] for [{}]", document.entityId, request);
index.findByEntityId(document.entityId, listener.delegateFailureAndWrap((delegate, matchingDocuments) -> {
if (matchingDocuments.isEmpty()) {
// derive a document id from the entity id so that don't accidentally create duplicate entities due to a race condition
document.docId = deriveDocumentId(document);
// force a create in case there are concurrent requests. This way, if two nodes/threads are trying to create the SP at
// the same time, one will fail. That's not ideal, but it's better than having 1 silently overwrite the other.
logger.trace("No existing ServiceProvider for EntityID=[{}], writing new doc [{}]", document.entityId, document.docId);
writeDocument(document, DocWriteRequest.OpType.CREATE, request.getRefreshPolicy(), delegate);
} else if (matchingDocuments.size() == 1) {
final SamlServiceProviderDocument existingDoc = Iterables.get(matchingDocuments, 0).getDocument();
assert existingDoc.docId != null : "Loaded document with no doc id";
assert existingDoc.entityId.equals(document.entityId) : "Loaded document with non-matching entity-id";
document.setDocId(existingDoc.docId);
document.setCreated(existingDoc.created);
logger.trace("Found existing ServiceProvider for EntityID=[{}], writing to doc [{}]", document.entityId, document.docId);
writeDocument(document, DocWriteRequest.OpType.INDEX, request.getRefreshPolicy(), delegate);
} else {
logger.warn(
"Found multiple existing service providers in [{}] with entity id [{}] - [{}]",
index,
document.entityId,
matchingDocuments.stream().map(d -> d.getDocument().docId).collect(Collectors.joining(","))
);
delegate.onFailure(
new IllegalStateException("Multiple service providers already exist with entity id [" + document.entityId + "]")
);
}
}));
}
private void writeDocument(
SamlServiceProviderDocument document,
DocWriteRequest.OpType opType,
WriteRequest.RefreshPolicy refreshPolicy,
ActionListener<PutSamlServiceProviderResponse> listener
) {
final Instant now = clock.instant();
if (document.created == null || opType == DocWriteRequest.OpType.CREATE) {
document.created = now;
}
document.lastModified = now;
final ValidationException validationException = document.validate();
if (validationException != null) {
listener.onFailure(validationException);
return;
}
logger.debug("[{}] service provider [{}] in document [{}] of [{}]", opType, document.entityId, document.docId, index);
index.writeDocument(
document,
opType,
refreshPolicy,
listener.delegateFailureAndWrap(
(l, response) -> l.onResponse(
new PutSamlServiceProviderResponse(
response.getId(),
response.getResult() == DocWriteResponse.Result.CREATED,
response.getSeqNo(),
response.getPrimaryTerm(),
document.entityId,
document.enabled
)
)
)
);
}
private static String deriveDocumentId(SamlServiceProviderDocument document) {
final byte[] sha256 = MessageDigests.sha256().digest(document.entityId.getBytes(StandardCharsets.UTF_8));
return Strings.BASE_64_NO_PADDING_URL_ENCODER.encodeToString(sha256);
}
}
| TransportPutSamlServiceProviderAction |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Order.java | {
"start": 371,
"end": 429
} | class ____ {
@Id
@GeneratedValue
public Integer id;
}
| Order |
java | apache__rocketmq | example/src/main/java/org/apache/rocketmq/example/benchmark/TransactionProducer.java | {
"start": 14459,
"end": 14693
} | class ____ implements TransactionListener {
private StatsBenchmarkTProducer statBenchmark;
private TxSendConfig sendConfig;
private final LRUMap<Long, Integer> cache = new LRUMap<>(200000);
private | TransactionListenerImpl |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/PluginHelper.java | {
"start": 8780,
"end": 9039
} | class ____
*/
public static PackageScanClassResolver getPackageScanClassResolver(CamelContext camelContext) {
return getPackageScanClassResolver(camelContext.getCamelContextExtension());
}
/**
* Returns the package scanning | resolver |
java | quarkusio__quarkus | integration-tests/micrometer-prometheus/src/test/java/io/quarkus/it/micrometer/prometheus/PrometheusMetricsRegistryTest.java | {
"start": 773,
"end": 19137
} | class ____ {
@Test
@Order(1)
void testRegistryInjection() {
when().get("/message").then().statusCode(200)
.body(containsString("io.micrometer.core.instrument.composite.CompositeMeterRegistry"));
}
@Test
@Order(2)
void testUnknownUrl() {
when().get("/message/notfound").then().statusCode(404);
}
@Test
@Order(3)
void testServerError() {
when().get("/message/fail").then().statusCode(500);
}
@Test
@Order(4)
void testPathParameter() {
given().header("foo", "bar").when().get("/message/item/123").then().statusCode(200);
}
@Test
@Order(5)
void testMultipleParameters() {
when().get("/message/match/123/1").then().statusCode(200);
when().get("/message/match/1/123").then().statusCode(200);
when().get("/message/match/baloney").then().statusCode(200);
}
@Test
@Order(6)
void testPanacheCalls() {
when().get("/fruit/create").then().statusCode(204);
when().get("/fruit/all").then().statusCode(204);
}
@Test
@Order(7)
void testPrimeEndpointCalls() {
when().get("/prime/7").then().statusCode(200)
.body(containsString("is prime"));
}
@Test
@Order(8)
void testAllTheThings() {
when().get("/all-the-things").then().statusCode(200)
.body(containsString("OK"));
}
@Test
@Order(9)
void testTemplatedPathOnClass() {
when().get("/template/path/anything").then().statusCode(200)
.body(containsString("Received: anything"));
}
@Test
@Order(10)
void testSecuredEndpoint() {
when().get("/secured/item/123").then().statusCode(401);
given().auth().preemptive().basic("foo", "bar").when().get("/secured/item/321").then().statusCode(401);
given().auth().preemptive().basic("scott", "reader").when().get("/secured/item/123").then().statusCode(200);
given().auth().preemptive().basic("stuart", "writer").when().get("/secured/item/321").then().statusCode(200);
}
@Test
@Order(11)
void testTemplatedPathOnSubResource() {
when().get("/root/r1/sub/s2").then().statusCode(200)
.body(containsString("r1:s2"));
}
@Test
@Order(20)
void testPrometheusScrapeEndpointTextPlain() {
RestAssured.given().header("Accept", TextFormat.CONTENT_TYPE_004)
.when().get("/q/metrics")
.then().statusCode(200)
// Prometheus body has ALL THE THINGS in no particular order
.body(containsString("registry=\"prometheus\""))
.body(containsString("env=\"test\""))
.body(containsString("http_server_requests"))
.body(containsString("status=\"404\""))
.body(containsString("uri=\"NOT_FOUND\""))
.body(containsString("outcome=\"CLIENT_ERROR\""))
.body(containsString("status=\"500\""))
.body(containsString("uri=\"/message/fail\""))
.body(containsString("outcome=\"SERVER_ERROR\""))
.body(containsString("status=\"200\""))
.body(containsString("uri=\"/message\""))
.body(containsString("uri=\"/message/item/{id}\""))
.body(containsString("status=\"200\",uri=\"/message/item/{id}\""))
.body(containsString("uri=\"/secured/item/{id}\""))
.body(containsString("status=\"200\",uri=\"/secured/item/{id}\""))
.body(containsString("status=\"401\",uri=\"/secured/item/{id}\""))
.body(containsString("outcome=\"SUCCESS\""))
.body(containsString("dummy="))
.body(containsString("foo=\"bar\""))
.body(containsString("foo_response=\"value\""))
.body(containsString("uri=\"/message/match/{id}/{sub}\""))
.body(containsString("uri=\"/message/match/{other}\""))
.body(containsString(
"http_server_requests_seconds_count{dummy=\"val-anything\",env=\"test\",env2=\"test\",foo=\"UNSET\",foo_response=\"UNSET\",method=\"GET\",outcome=\"SUCCESS\",registry=\"prometheus\",status=\"200\",uri=\"/template/path/{value}\""))
.body(containsString(
"http_server_requests_seconds_count{dummy=\"value\",env=\"test\",env2=\"test\",foo=\"UNSET\",foo_response=\"UNSET\",method=\"GET\",outcome=\"SUCCESS\",registry=\"prometheus\",status=\"200\",uri=\"/root/{rootParam}/sub/{subParam}\""))
// Verify Hibernate Metrics
.body(containsString(
"hibernate_sessions_open_total{entityManagerFactory=\"<default>\",env=\"test\",env2=\"test\",registry=\"prometheus\",} 2.0"))
.body(containsString(
"hibernate_sessions_closed_total{entityManagerFactory=\"<default>\",env=\"test\",env2=\"test\",registry=\"prometheus\",} 2.0"))
.body(containsString(
"hibernate_connections_obtained_total{entityManagerFactory=\"<default>\",env=\"test\",env2=\"test\",registry=\"prometheus\",}"))
.body(containsString(
"hibernate_entities_inserts_total{entityManagerFactory=\"<default>\",env=\"test\",env2=\"test\",registry=\"prometheus\",} 3.0"))
.body(containsString(
"hibernate_flushes_total{entityManagerFactory=\"<default>\",env=\"test\",env2=\"test\",registry=\"prometheus\",} 1.0"))
// Annotated counters
.body(not(containsString("metric_none")))
.body(containsString(
"metric_all_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"none\",extra=\"tag\",fail=\"false\",method=\"countAllInvocations\",registry=\"prometheus\",result=\"success\",} 1.0"))
.body(containsString(
"metric_all_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"NullPointerException\",extra=\"tag\",fail=\"true\",method=\"countAllInvocations\",registry=\"prometheus\",result=\"failure\",} 1.0"))
.body(containsString(
"method_counted_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"NullPointerException\",fail=\"prefix true\",method=\"emptyMetricName\",registry=\"prometheus\",result=\"failure\",} 1.0"))
.body(containsString(
"method_counted_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"none\",fail=\"prefix false\",method=\"emptyMetricName\",registry=\"prometheus\",result=\"success\",} 1.0"))
.body(not(containsString("async_none")))
.body(containsString(
"async_all_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",do_fail_call=\"true\",env=\"test\",env2=\"test\",exception=\"NullPointerException\",extra=\"tag\",method=\"countAllAsyncInvocations\",registry=\"prometheus\",result=\"failure\",} 1.0"))
.body(containsString(
"async_all_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",do_fail_call=\"false\",env=\"test\",env2=\"test\",exception=\"none\",extra=\"tag\",method=\"countAllAsyncInvocations\",registry=\"prometheus\",result=\"success\",} 1.0"))
.body(containsString(
"method_counted_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"NullPointerException\",fail=\"42\",method=\"emptyAsyncMetricName\",registry=\"prometheus\",result=\"failure\",} 1.0"))
.body(containsString(
"method_counted_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"none\",fail=\"42\",method=\"emptyAsyncMetricName\",registry=\"prometheus\",result=\"success\",} 1.0"))
// Annotated Timers
.body(containsString(
"call_seconds_count{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"NullPointerException\",extra=\"tag\",method=\"call\",registry=\"prometheus\",} 1.0"))
.body(containsString(
"call_seconds_count{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"none\",extra=\"tag\",method=\"call\",registry=\"prometheus\",}"))
.body(containsString(
"async_call_seconds_count{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"NullPointerException\",extra=\"tag\",method=\"asyncCall\",registry=\"prometheus\",} 1.0"))
.body(containsString(
"async_call_seconds_count{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"none\",extra=\"tag\",method=\"asyncCall\",registry=\"prometheus\",} 1.0"))
.body(containsString(
"longCall_seconds_active_count{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",extra=\"tag\",method=\"longCall\",registry=\"prometheus\",}"))
.body(containsString(
"async_longCall_seconds_duration_sum{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",extra=\"tag\",method=\"longAsyncCall\",registry=\"prometheus\",} 0.0"))
// Configured median, 95th percentile and histogram buckets
.body(containsString(
"prime_number_test_seconds{env=\"test\",env2=\"test\",registry=\"prometheus\",quantile=\"0.5\",}"))
.body(containsString(
"prime_number_test_seconds{env=\"test\",env2=\"test\",registry=\"prometheus\",quantile=\"0.95\",}"))
.body(containsString(
"prime_number_test_seconds_bucket{env=\"test\",env2=\"test\",registry=\"prometheus\",le=\"0.001\",}"))
// this was defined by a tag to a non-matching registry, and should not be found
.body(not(containsString("class-should-not-match")))
// should not find this ignored uri
.body(not(containsString("uri=\"/fruit/create\"")));
}
@Test
@Order(20)
void testPrometheusScrapeEndpointOpenMetrics() {
RestAssured.given().header("Accept", TextFormat.CONTENT_TYPE_OPENMETRICS_100)
.when().get("/q/metrics")
.then().statusCode(200)
// Prometheus body has ALL THE THINGS in no particular order
.body(containsString("registry=\"prometheus\""))
.body(containsString("env=\"test\""))
.body(containsString("http_server_requests"))
.body(containsString("status=\"404\""))
.body(containsString("uri=\"NOT_FOUND\""))
.body(containsString("outcome=\"CLIENT_ERROR\""))
.body(containsString("status=\"500\""))
.body(containsString("uri=\"/message/fail\""))
.body(containsString("outcome=\"SERVER_ERROR\""))
.body(containsString("status=\"200\""))
.body(containsString("uri=\"/message\""))
.body(containsString("uri=\"/message/item/{id}\""))
.body(containsString("outcome=\"SUCCESS\""))
.body(containsString("uri=\"/message/match/{id}/{sub}\""))
.body(containsString("uri=\"/message/match/{other}\""))
.body(containsString(
"http_server_requests_seconds_count{dummy=\"val-anything\",env=\"test\",env2=\"test\",foo=\"UNSET\",foo_response=\"UNSET\",method=\"GET\",outcome=\"SUCCESS\",registry=\"prometheus\",status=\"200\",uri=\"/template/path/{value}\""))
// Verify Hibernate Metrics
.body(containsString(
"hibernate_sessions_open_total{entityManagerFactory=\"<default>\",env=\"test\",env2=\"test\",registry=\"prometheus\"} 2.0"))
.body(containsString(
"hibernate_sessions_closed_total{entityManagerFactory=\"<default>\",env=\"test\",env2=\"test\",registry=\"prometheus\"} 2.0"))
.body(containsString(
"hibernate_connections_obtained_total{entityManagerFactory=\"<default>\",env=\"test\",env2=\"test\",registry=\"prometheus\"}"))
.body(containsString(
"hibernate_entities_inserts_total{entityManagerFactory=\"<default>\",env=\"test\",env2=\"test\",registry=\"prometheus\"} 3.0"))
.body(containsString(
"hibernate_flushes_total{entityManagerFactory=\"<default>\",env=\"test\",env2=\"test\",registry=\"prometheus\"} 1.0"))
// Annotated counters
.body(not(containsString("metric_none")))
.body(containsString(
"metric_all_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"none\",extra=\"tag\",fail=\"false\",method=\"countAllInvocations\",registry=\"prometheus\",result=\"success\"} 1.0 # {span_id="))
.body(containsString(
"metric_all_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"NullPointerException\",extra=\"tag\",fail=\"true\",method=\"countAllInvocations\",registry=\"prometheus\",result=\"failure\"} 1.0"))
.body(containsString(
"method_counted_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"NullPointerException\",fail=\"prefix true\",method=\"emptyMetricName\",registry=\"prometheus\",result=\"failure\"} 1.0 # {span_id="))
.body(containsString(
"method_counted_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"none\",fail=\"prefix false\",method=\"emptyMetricName\",registry=\"prometheus\",result=\"success\"} 1.0"))
.body(not(containsString("async_none")))
.body(containsString(
"async_all_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",do_fail_call=\"true\",env=\"test\",env2=\"test\",exception=\"NullPointerException\",extra=\"tag\",method=\"countAllAsyncInvocations\",registry=\"prometheus\",result=\"failure\"} 1.0"))
.body(containsString(
"async_all_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",do_fail_call=\"false\",env=\"test\",env2=\"test\",exception=\"none\",extra=\"tag\",method=\"countAllAsyncInvocations\",registry=\"prometheus\",result=\"success\"} 1.0"))
.body(containsString(
"method_counted_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"NullPointerException\",fail=\"42\",method=\"emptyAsyncMetricName\",registry=\"prometheus\",result=\"failure\"} 1.0"))
.body(containsString(
"method_counted_total{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"none\",fail=\"42\",method=\"emptyAsyncMetricName\",registry=\"prometheus\",result=\"success\"} 1.0"))
// Annotated Timers
.body(containsString(
"call_seconds_count{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"NullPointerException\",extra=\"tag\",method=\"call\",registry=\"prometheus\"} 1.0"))
.body(containsString(
"call_seconds_count{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"none\",extra=\"tag\",method=\"call\",registry=\"prometheus\"}"))
.body(containsString(
"async_call_seconds_count{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"NullPointerException\",extra=\"tag\",method=\"asyncCall\",registry=\"prometheus\"} 1.0"))
.body(containsString(
"async_call_seconds_count{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",exception=\"none\",extra=\"tag\",method=\"asyncCall\",registry=\"prometheus\"} 1.0"))
.body(containsString(
"longCall_seconds_active_count{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",extra=\"tag\",method=\"longCall\",registry=\"prometheus\"}"))
.body(containsString(
"async_longCall_seconds_duration_sum{class=\"io.quarkus.it.micrometer.prometheus.AnnotatedResource\",env=\"test\",env2=\"test\",extra=\"tag\",method=\"longAsyncCall\",registry=\"prometheus\"} 0.0"))
// Configured median, 95th percentile and histogram buckets
.body(containsString(
"prime_number_test_seconds{env=\"test\",env2=\"test\",registry=\"prometheus\",quantile=\"0.5\"}"))
.body(containsString(
"prime_number_test_seconds{env=\"test\",env2=\"test\",registry=\"prometheus\",quantile=\"0.95\"}"))
.body(containsString(
"prime_number_test_seconds_bucket{env=\"test\",env2=\"test\",registry=\"prometheus\",le=\"0.001\"}"))
// this was defined by a tag to a non-matching registry, and should not be found
.body(not(containsString("class-should-not-match")))
// should not find this ignored uri
.body(not(containsString("uri=\"/fruit/create\"")));
}
}
| PrometheusMetricsRegistryTest |
java | elastic__elasticsearch | modules/reindex/src/main/java/org/elasticsearch/reindex/TransportDeleteByQueryAction.java | {
"start": 1467,
"end": 3886
} | class ____ extends HandledTransportAction<DeleteByQueryRequest, BulkByScrollResponse> {
private final ThreadPool threadPool;
private final Client client;
private final ScriptService scriptService;
private final ClusterService clusterService;
private final DeleteByQueryMetrics deleteByQueryMetrics;
@Inject
public TransportDeleteByQueryAction(
ThreadPool threadPool,
ActionFilters actionFilters,
Client client,
TransportService transportService,
ScriptService scriptService,
ClusterService clusterService,
@Nullable DeleteByQueryMetrics deleteByQueryMetrics
) {
super(DeleteByQueryAction.NAME, transportService, actionFilters, DeleteByQueryRequest::new, EsExecutors.DIRECT_EXECUTOR_SERVICE);
this.threadPool = threadPool;
this.client = client;
this.scriptService = scriptService;
this.clusterService = clusterService;
this.deleteByQueryMetrics = deleteByQueryMetrics;
}
@Override
public void doExecute(Task task, DeleteByQueryRequest request, ActionListener<BulkByScrollResponse> listener) {
BulkByScrollTask bulkByScrollTask = (BulkByScrollTask) task;
long startTime = System.nanoTime();
BulkByScrollParallelizationHelper.startSlicedAction(
request,
bulkByScrollTask,
DeleteByQueryAction.INSTANCE,
listener,
client,
clusterService.localNode(),
() -> {
ParentTaskAssigningClient assigningClient = new ParentTaskAssigningClient(
client,
clusterService.localNode(),
bulkByScrollTask
);
new AsyncDeleteByQueryAction(
bulkByScrollTask,
logger,
assigningClient,
threadPool,
request,
scriptService,
ActionListener.runAfter(listener, () -> {
long elapsedTime = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
if (deleteByQueryMetrics != null) {
deleteByQueryMetrics.recordTookTime(elapsedTime);
}
})
).start();
}
);
}
}
| TransportDeleteByQueryAction |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/junit4/rules/AutowiredRuleSpr15927Tests.java | {
"start": 1237,
"end": 2140
} | class ____ {
@ClassRule
public static final SpringClassRule springClassRule = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
@Rule
public AutowiredTestRule autowiredTestRule;
@Test
public void test() {
assertThat(autowiredTestRule).as("TestRule should have been @Autowired").isNotNull();
// Rationale for the following assertion:
//
// The field value for the custom rule is null when JUnit sees it. JUnit then
// ignores the null value, and at a later point in time Spring injects the rule
// from the ApplicationContext and overrides the null field value. But that's too
// late: JUnit never sees the rule supplied by Spring via dependency injection.
assertThat(autowiredTestRule.applied).as("@Autowired TestRule should NOT have been applied").isFalse();
}
@Configuration
static | AutowiredRuleSpr15927Tests |
java | apache__camel | components/camel-grpc/src/main/java/org/apache/camel/component/grpc/server/GrpcRequestDelegationStreamObserver.java | {
"start": 1079,
"end": 2610
} | class ____ extends GrpcRequestAbstractStreamObserver {
public GrpcRequestDelegationStreamObserver(GrpcEndpoint endpoint, GrpcConsumer consumer,
StreamObserver<Object> responseObserver, Map<String, Object> headers) {
super(endpoint, consumer, responseObserver, headers);
if (!endpoint.getConfiguration().isRouteControlledStreamObserver()) {
throw new IllegalStateException(
"DELEGATION consumer strategy must be used with enabled routeControlledStreamObserver");
}
}
@Override
public void onNext(Object request) {
var exchange = endpoint.createExchange();
exchange.getIn().setBody(request);
exchange.getIn().setHeaders(headers);
exchange.setProperty(GrpcConstants.GRPC_RESPONSE_OBSERVER, responseObserver);
consumer.process(exchange, doneSync -> {
});
}
@Override
public void onError(Throwable throwable) {
var exchange = endpoint.createExchange();
exchange.getIn().setHeaders(headers);
exchange.setProperty(GrpcConstants.GRPC_RESPONSE_OBSERVER, responseObserver);
consumer.onError(exchange, throwable);
}
@Override
public void onCompleted() {
var exchange = endpoint.createExchange();
exchange.getIn().setHeaders(headers);
exchange.setProperty(GrpcConstants.GRPC_RESPONSE_OBSERVER, responseObserver);
consumer.onCompleted(exchange);
}
}
| GrpcRequestDelegationStreamObserver |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleSubscribeOn.java | {
"start": 869,
"end": 1490
} | class ____<T> extends Single<T> {
final SingleSource<? extends T> source;
final Scheduler scheduler;
public SingleSubscribeOn(SingleSource<? extends T> source, Scheduler scheduler) {
this.source = source;
this.scheduler = scheduler;
}
@Override
protected void subscribeActual(final SingleObserver<? super T> observer) {
final SubscribeOnObserver<T> parent = new SubscribeOnObserver<>(observer, source);
observer.onSubscribe(parent);
Disposable f = scheduler.scheduleDirect(parent);
parent.task.replace(f);
}
static final | SingleSubscribeOn |
java | google__dagger | hilt-core/main/java/dagger/hilt/InstallIn.java | {
"start": 871,
"end": 1279
} | class ____ be included in when
* Hilt generates the components. This may only be used with classes annotated with
* {@literal @}{@link dagger.Module} or {@literal @}{@link dagger.hilt.EntryPoint}.
*
* <p>Example usage for installing a module in the generated {@code ApplicationComponent}:
*
* <pre><code>
* {@literal @}Module
* {@literal @}InstallIn(SingletonComponent.class)
* public final | should |
java | spring-projects__spring-boot | core/spring-boot-test/src/test/java/org/springframework/boot/test/json/Jackson2TesterTests.java | {
"start": 3040,
"end": 3440
} | class ____ extends InitFieldsBaseClass {
public org.springframework.boot.test.json.@Nullable Jackson2Tester<List<ExampleObject>> test;
public org.springframework.boot.test.json.Jackson2Tester<ExampleObject> testSet = new org.springframework.boot.test.json.Jackson2Tester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class), new ObjectMapper());
}
}
| InitFieldsTestClass |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/annotation/FunctionHint.java | {
"start": 2573,
"end": 2945
} | class ____ extends ScalarFunction { ... }
*
* // accepts (INT, STRING...) and returns BOOLEAN,
* // the arguments have names
* @FunctionHint(
* arguments = {
* @ArgumentHint(type = @DataTypeHint("INT"), name = "in1"),
* @ArgumentHint(type = @DataTypeHint("STRING"), name = "in2")
* },
* isVarArgs = true,
* output = @DataTypeHint("BOOLEAN")
* )
* | X |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/results/ResultBuilderEntityValued.java | {
"start": 477,
"end": 700
} | interface ____ extends ResultBuilder {
@Override
EntityResult buildResult(
JdbcValuesMetadata jdbcResultsMetadata,
int resultPosition,
DomainResultCreationState domainResultCreationState);
}
| ResultBuilderEntityValued |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestFileAppend.java | {
"start": 2909,
"end": 2996
} | class ____ the building blocks that are needed to
* support HDFS appends.
*/
public | tests |
java | elastic__elasticsearch | x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/rest/RestPauseAutoFollowPatternAction.java | {
"start": 894,
"end": 1561
} | class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(POST, "/_ccr/auto_follow/{name}/pause"));
}
@Override
public String getName() {
return "ccr_pause_auto_follow_pattern_action";
}
@Override
protected RestChannelConsumer prepareRequest(final RestRequest restRequest, final NodeClient client) {
final var request = new Request(getMasterNodeTimeout(restRequest), TimeValue.THIRTY_SECONDS, restRequest.param("name"), false);
return channel -> client.execute(INSTANCE, request, new RestToXContentListener<>(channel));
}
}
| RestPauseAutoFollowPatternAction |
java | elastic__elasticsearch | modules/transport-netty4/src/internalClusterTest/java/org/elasticsearch/http/netty4/Netty4IncrementalRequestHandlingIT.java | {
"start": 33931,
"end": 36423
} | class ____ implements AutoCloseable {
private final String contextName;
private final HttpServerTransport httpServerTransport;
private final HandlersByOpaqueId handlersByOpaqueId;
private final Bootstrap bootstrap;
private final Channel channel;
private final BlockingDeque<FullHttpResponse> responseQueue;
ClientContext(
String contextName,
HttpServerTransport httpServerTransport,
HandlersByOpaqueId handlersByOpaqueId,
Bootstrap bootstrap,
Channel channel,
BlockingDeque<FullHttpResponse> responseQueue
) {
this.contextName = contextName;
this.httpServerTransport = httpServerTransport;
this.handlersByOpaqueId = handlersByOpaqueId;
this.bootstrap = bootstrap;
this.channel = channel;
this.responseQueue = responseQueue;
}
String newOpaqueId() {
return contextName + "-" + idGenerator.getAsLong();
}
@Override
public void close() {
safeGet(channel.close());
safeGet(bootstrap.config().group().shutdownGracefully(0, 0, TimeUnit.SECONDS));
assertThat(responseQueue, empty());
handlersByOpaqueId.removeHandlers(contextName);
}
FullHttpResponse getNextResponse() {
try {
var response = responseQueue.poll(SAFE_AWAIT_TIMEOUT.seconds(), TimeUnit.SECONDS);
assertNotNull("queue is empty", response);
return response;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AssertionError(e);
}
}
ServerRequestHandler awaitRestChannelAccepted(String opaqueId) {
var handler = safeAwait(handlersByOpaqueId.getHandlerFor(opaqueId));
safeAwait(handler.channelAccepted);
return handler;
}
long transportStatsRequestBytesSize() {
var bytes = 0L;
for (final var clientStats : httpServerTransport.stats().clientStats()) {
bytes += clientStats.requestSizeBytes();
}
return bytes;
}
Channel channel() {
return channel;
}
}
/** A streaming request handler which allows tests to consume exactly the data (bytes or chunks) they expect. */
static | ClientContext |
java | grpc__grpc-java | benchmarks/src/jmh/java/io/grpc/benchmarks/netty/StreamingPingPongsPerSecondBenchmark.java | {
"start": 1406,
"end": 2060
} | class ____ extends AbstractBenchmark {
private static final Logger logger =
Logger.getLogger(StreamingPingPongsPerSecondBenchmark.class.getName());
@Param({"1", "2", "4", "8"})
public int channelCount = 1;
@Param({"1", "10", "100", "1000"})
public int maxConcurrentStreams = 1;
private static AtomicLong callCounter;
private AtomicBoolean completed;
private AtomicBoolean record;
private CountDownLatch latch;
/**
* Use an AuxCounter so we can measure that calls as they occur without consuming CPU
* in the benchmark method.
*/
@AuxCounters
@State(Scope.Thread)
public static | StreamingPingPongsPerSecondBenchmark |
java | spring-projects__spring-framework | integration-tests/src/test/java/org/springframework/context/annotation/scope/ClassPathBeanDefinitionScannerScopeIntegrationTests.java | {
"start": 12080,
"end": 12179
} | interface ____ {
}
@Component
@RequestScope(proxyMode = DEFAULT)
static | AnotherScopeTestInterface |
java | alibaba__nacos | api/src/test/java/com/alibaba/nacos/api/config/remote/response/BasedConfigResponseTest.java | {
"start": 902,
"end": 1561
} | class ____ extends BasedConfigRequestTest {
protected String requestId;
@Override
public void testSerialize() throws JsonProcessingException {
}
@Override
public void testDeserialize() throws JsonProcessingException {
}
public abstract void testSerializeSuccessResponse() throws JsonProcessingException;
public abstract void testSerializeFailResponse() throws JsonProcessingException;
protected String injectResponseUuId(Response response) {
String uuid = UUID.randomUUID().toString();
response.setRequestId(uuid);
return uuid;
}
}
| BasedConfigResponseTest |
java | apache__spark | common/network-shuffle/src/test/java/org/apache/spark/network/shuffle/TestShuffleDataContext.java | {
"start": 1520,
"end": 5268
} | class ____ {
private static final Logger logger = LoggerFactory.getLogger(TestShuffleDataContext.class);
public final String[] localDirs;
public final int subDirsPerLocalDir;
public TestShuffleDataContext(int numLocalDirs, int subDirsPerLocalDir) {
this.localDirs = new String[numLocalDirs];
this.subDirsPerLocalDir = subDirsPerLocalDir;
}
public void create() throws IOException {
String root = System.getProperty("java.io.tmpdir");
for (int i = 0; i < localDirs.length; i ++) {
localDirs[i] = JavaUtils.createDirectory(root, "spark").getAbsolutePath();
for (int p = 0; p < subDirsPerLocalDir; p ++) {
Files.createDirectories(new File(localDirs[i], String.format("%02x", p)).toPath());
}
}
}
public void cleanup() {
for (String localDir : localDirs) {
try {
JavaUtils.deleteRecursively(new File(localDir));
} catch (Exception e) {
logger.warn("Unable to cleanup localDir = " + localDir, e);
}
}
}
/** Creates reducer blocks in a sort-based data format within our local dirs. */
public String insertSortShuffleData(int shuffleId, int mapId, byte[][] blocks)
throws IOException {
String blockId = "shuffle_" + shuffleId + "_" + mapId + "_0";
OutputStream dataStream = null;
DataOutputStream indexStream = null;
boolean suppressExceptionsDuringClose = true;
try {
dataStream = new FileOutputStream(new File(
ExecutorDiskUtils.getFilePath(localDirs, subDirsPerLocalDir, blockId + ".data")));
indexStream = new DataOutputStream(new FileOutputStream(new File(
ExecutorDiskUtils.getFilePath(localDirs, subDirsPerLocalDir, blockId + ".index"))));
long offset = 0;
indexStream.writeLong(offset);
for (byte[] block : blocks) {
offset += block.length;
dataStream.write(block);
indexStream.writeLong(offset);
}
suppressExceptionsDuringClose = false;
} finally {
Closeables.close(dataStream, suppressExceptionsDuringClose);
Closeables.close(indexStream, suppressExceptionsDuringClose);
}
return blockId;
}
/** Creates spill file(s) within the local dirs. */
public void insertSpillData() throws IOException {
String filename = "temp_local_uuid";
insertFile(filename);
}
public void insertBroadcastData() throws IOException {
String filename = "broadcast_12_uuid";
insertFile(filename);
}
public void insertTempShuffleData() throws IOException {
String filename = "temp_shuffle_uuid";
insertFile(filename);
}
public void insertCachedRddData(int rddId, int splitId, byte[] block) throws IOException {
String blockId = "rdd_" + rddId + "_" + splitId;
insertFile(blockId, block);
}
private void insertFile(String filename) throws IOException {
insertFile(filename, new byte[] { 42 });
}
private void insertFile(String filename, byte[] block) throws IOException {
OutputStream dataStream = null;
File file = new File(ExecutorDiskUtils.getFilePath(localDirs, subDirsPerLocalDir, filename));
Assertions.assertFalse(file.exists(), "this test file has been already generated");
try {
dataStream = new FileOutputStream(
new File(ExecutorDiskUtils.getFilePath(localDirs, subDirsPerLocalDir, filename)));
dataStream.write(block);
} finally {
Closeables.close(dataStream, false);
}
}
/**
* Creates an ExecutorShuffleInfo object based on the given shuffle manager which targets this
* context's directories.
*/
public ExecutorShuffleInfo createExecutorInfo(String shuffleManager) {
return new ExecutorShuffleInfo(localDirs, subDirsPerLocalDir, shuffleManager);
}
}
| TestShuffleDataContext |
java | netty__netty | testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketSpdyEchoTest.java | {
"start": 9210,
"end": 10670
} | class ____ extends SimpleChannelInboundHandler<ByteBuf> {
private final boolean autoRead;
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
final ByteBuf frames;
volatile int counter;
SpdyEchoTestClientHandler(ByteBuf frames, boolean autoRead) {
this.frames = frames;
this.autoRead = autoRead;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
if (!autoRead) {
ctx.read();
}
}
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
byte[] actual = new byte[in.readableBytes()];
in.readBytes(actual);
int lastIdx = counter;
for (int i = 0; i < actual.length; i ++) {
assertEquals(frames.getByte(ignoredBytes + i + lastIdx), actual[i]);
}
counter += actual.length;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (exception.compareAndSet(null, cause)) {
ctx.close();
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
if (!autoRead) {
ctx.read();
}
}
}
}
| SpdyEchoTestClientHandler |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/annotatewith/AnnotateBeanMappingMethodMapper.java | {
"start": 303,
"end": 436
} | interface ____ {
@AnnotateWith(CustomMethodOnlyAnnotation.class)
Target map(Source source);
| AnnotateBeanMappingMethodMapper |
java | quarkusio__quarkus | integration-tests/jackson/src/test/java/io/quarkus/it/jackson/model/ModelWithBuilderTest.java | {
"start": 185,
"end": 1785
} | class ____ {
// -------------------------------------------------------------------------
// Test cases
// -------------------------------------------------------------------------
@Test
public void testBuilderMinimal() {
// prepare
ModelWithBuilder.Builder builder = new ModelWithBuilder.Builder("id1");
// execute
ModelWithBuilder data = builder.build();
// verify
assertThat(data.getVersion()).isEqualTo(1);
assertThat(data.getId()).isEqualTo("id1");
assertThat(data.getValue()).isEqualTo("");
}
@Test
public void testBuilder() {
// prepare
ModelWithBuilder.Builder builder = new ModelWithBuilder.Builder("id2")
.withVersion(2)
.withValue("value");
// execute
ModelWithBuilder data = builder.build();
// verify
assertThat(data.getVersion()).isEqualTo(2);
assertThat(data.getId()).isEqualTo("id2");
assertThat(data.getValue()).isEqualTo("value");
}
@Test
public void testBuilderCloneConstructor() {
// prepare
ModelWithBuilder original = new ModelWithBuilder.Builder("id1")
.withVersion(3)
.withValue("val")
.build();
// execute
ModelWithBuilder clone = new ModelWithBuilder.Builder(original).build();
// verify
assertThat(clone.getVersion()).isEqualTo(3);
assertThat(clone.getId()).isEqualTo("id1");
assertThat(clone.getValue()).isEqualTo("val");
}
}
| ModelWithBuilderTest |
java | spring-projects__spring-boot | build-plugin/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java | {
"start": 1124,
"end": 1434
} | class ____ {
GradleBuild gradleBuild;
@TestTemplate
void mavenPublish() {
assertThat(this.gradleBuild.script(Examples.DIR + "publishing/maven-publish")
.build("publishingConfiguration")
.getOutput()).contains("MavenPublication").contains("https://repo.example.com");
}
}
| PublishingDocumentationTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.