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
|
alibaba__nacos
|
persistence/src/main/java/com/alibaba/nacos/persistence/repository/PaginationHelper.java
|
{
"start": 1010,
"end": 2242
}
|
interface ____<E> {
Page<E> fetchPage(final String sqlCountRows, final String sqlFetchRows, final Object[] args, final int pageNo,
final int pageSize, final RowMapper<E> rowMapper);
Page<E> fetchPage(final String sqlCountRows, final String sqlFetchRows, final Object[] args, final int pageNo,
final int pageSize, final Long lastMaxId, final RowMapper<E> rowMapper);
Page<E> fetchPageLimit(final String sqlCountRows, final String sqlFetchRows, final Object[] args, final int pageNo,
final int pageSize, final RowMapper<E> rowMapper);
Page<E> fetchPageLimit(final String sqlCountRows, final Object[] args1, final String sqlFetchRows,
final Object[] args2, final int pageNo, final int pageSize, final RowMapper<E> rowMapper);
Page<E> fetchPageLimit(final String sqlFetchRows, final Object[] args, final int pageNo, final int pageSize,
final RowMapper<E> rowMapper);
Page<E> fetchPageLimit(final MapperResult countMapperResult, final MapperResult mapperResult, final int pageNo,
final int pageSize, final RowMapper<E> rowMapper);
void updateLimit(final String sql, final Object[] args);
}
|
PaginationHelper
|
java
|
spring-projects__spring-boot
|
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java
|
{
"start": 1454,
"end": 6499
}
|
class ____ {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, ProjectInfoAutoConfiguration.class));
@Test
void gitPropertiesUnavailableIfResourceNotAvailable() {
this.contextRunner.run((context) -> assertThat(context.getBeansOfType(GitProperties.class)).isEmpty());
}
@Test
void gitPropertiesWithNoData() {
this.contextRunner
.withPropertyValues("spring.info.git.location="
+ "classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties")
.run((context) -> {
GitProperties gitProperties = context.getBean(GitProperties.class);
assertThat(gitProperties.getBranch()).isNull();
});
}
@Test
void gitPropertiesFallbackWithGitPropertiesBean() {
this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class)
.withPropertyValues(
"spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties")
.run((context) -> {
GitProperties gitProperties = context.getBean(GitProperties.class);
assertThat(gitProperties).isSameAs(context.getBean("customGitProperties"));
});
}
@Test
void gitPropertiesUsesUtf8ByDefault() {
this.contextRunner
.withPropertyValues(
"spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties")
.run((context) -> {
GitProperties gitProperties = context.getBean(GitProperties.class);
assertThat(gitProperties.get("commit.charset")).isEqualTo("test™");
});
}
@Test
void gitPropertiesEncodingCanBeConfigured() {
this.contextRunner
.withPropertyValues("spring.info.git.encoding=US-ASCII",
"spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties")
.run((context) -> {
GitProperties gitProperties = context.getBean(GitProperties.class);
assertThat(gitProperties.get("commit.charset")).isNotEqualTo("test™");
});
}
@Test
@WithResource(name = "META-INF/build-info.properties", content = """
build.group=com.example
build.artifact=demo
build.name=Demo Project
build.version=0.0.1-SNAPSHOT
build.time=2016-03-04T14:16:05.000Z
""")
void buildPropertiesDefaultLocation() {
this.contextRunner.run((context) -> {
BuildProperties buildProperties = context.getBean(BuildProperties.class);
assertThat(buildProperties.getGroup()).isEqualTo("com.example");
assertThat(buildProperties.getArtifact()).isEqualTo("demo");
assertThat(buildProperties.getName()).isEqualTo("Demo Project");
assertThat(buildProperties.getVersion()).isEqualTo("0.0.1-SNAPSHOT");
Instant time = buildProperties.getTime();
assertThat(time).isNotNull();
assertThat(time.toEpochMilli()).isEqualTo(1457100965000L);
});
}
@Test
void buildPropertiesCustomLocation() {
this.contextRunner
.withPropertyValues("spring.info.build.location="
+ "classpath:/org/springframework/boot/autoconfigure/info/build-info.properties")
.run((context) -> {
BuildProperties buildProperties = context.getBean(BuildProperties.class);
assertThat(buildProperties.getGroup()).isEqualTo("com.example.acme");
assertThat(buildProperties.getArtifact()).isEqualTo("acme");
assertThat(buildProperties.getName()).isEqualTo("acme");
assertThat(buildProperties.getVersion()).isEqualTo("1.0.1-SNAPSHOT");
Instant time = buildProperties.getTime();
assertThat(time).isNotNull();
assertThat(time.toEpochMilli()).isEqualTo(1457088120000L);
});
}
@Test
void buildPropertiesCustomInvalidLocation() {
this.contextRunner.withPropertyValues("spring.info.build.location=classpath:/org/acme/no-build-info.properties")
.run((context) -> assertThat(context.getBeansOfType(BuildProperties.class)).isEmpty());
}
@Test
void buildPropertiesFallbackWithBuildInfoBean() {
this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class).run((context) -> {
BuildProperties buildProperties = context.getBean(BuildProperties.class);
assertThat(buildProperties).isSameAs(context.getBean("customBuildProperties"));
});
}
@Test
void buildPropertiesUsesUtf8ByDefault() {
this.contextRunner.withPropertyValues(
"spring.info.build.location=classpath:/org/springframework/boot/autoconfigure/info/build-info.properties")
.run((context) -> {
BuildProperties buildProperties = context.getBean(BuildProperties.class);
assertThat(buildProperties.get("charset")).isEqualTo("test™");
});
}
@Test
void buildPropertiesEncodingCanBeConfigured() {
this.contextRunner.withPropertyValues("spring.info.build.encoding=US-ASCII",
"spring.info.build.location=classpath:/org/springframework/boot/autoconfigure/info/build-info.properties")
.run((context) -> {
BuildProperties buildProperties = context.getBean(BuildProperties.class);
assertThat(buildProperties.get("charset")).isNotEqualTo("test™");
});
}
@Configuration(proxyBeanMethods = false)
static
|
ProjectInfoAutoConfigurationTests
|
java
|
apache__flink
|
flink-core-api/src/main/java/org/apache/flink/api/java/tuple/Tuple9.java
|
{
"start": 1890,
"end": 2445
}
|
class ____ extends Tuple9", then don't use
* instances of Foo in a DataStream<Tuple9> / DataSet<Tuple9>, but declare it as
* DataStream<Foo> / DataSet<Foo>.)
* </ul>
*
* @see Tuple
* @param <T0> The type of field 0
* @param <T1> The type of field 1
* @param <T2> The type of field 2
* @param <T3> The type of field 3
* @param <T4> The type of field 4
* @param <T5> The type of field 5
* @param <T6> The type of field 6
* @param <T7> The type of field 7
* @param <T8> The type of field 8
*/
@Public
public
|
Foo
|
java
|
google__dagger
|
dagger-grpc-server-processor/main/java/dagger/grpc/server/processor/GrpcServiceModel.java
|
{
"start": 4451,
"end": 7601
}
|
class ____ by {@link GrpcService#grpcClass()}. */
protected final TypeElement grpcClass() {
AnnotationValue argument =
getAnnotationValue(grpcServiceAnnotation(), GRPC_SERVICE_PARAMETER_NAME);
return GET_TYPE_ELEMENT_FROM_VALUE.visit(argument, argument);
}
/**
* Returns the annotation spec for the {@code @Generated} annotation to add to any
* type generated by this processor.
*/
protected final Optional<AnnotationSpec> generatedAnnotation() {
return generatedAnnotationSpec(
elements,
sourceVersion,
GrpcService.class,
String.format(
"@%s annotation on %s",
GrpcService.class.getCanonicalName(), serviceImplementationClassName));
}
/**
* Returns the annotation spec for a {@link ForGrpcService} annotation whose value is the
* gRPC-generated service class.
*/
protected final AnnotationSpec forGrpcService() {
return AnnotationSpec.builder(ForGrpcService.class)
.addMember("value", "$T.class", grpcClass())
.build();
}
protected final String subcomponentServiceDefinitionMethodName() {
return UPPER_CAMEL.to(LOWER_CAMEL, simpleServiceName()) + "ServiceDefinition";
}
private String simpleServiceName() {
return grpcClass().getSimpleName().toString().replaceFirst("Grpc$", "");
}
private TypeElement serviceImplBase(TypeMirror service) {
ClassName serviceClassName = ClassName.get(MoreTypes.asTypeElement(service));
ClassName serviceImplBaseName = serviceClassName.nestedClass(simpleServiceName() + "ImplBase");
return elements.getTypeElement(serviceImplBaseName.toString());
}
private boolean validateGrpcClass(TypeMirror type, AnnotationValue value) {
TypeElement serviceImplBase = serviceImplBase(type);
if (serviceImplBase == null || !types.isSubtype(serviceImplBase.asType(), bindableService())) {
messager.printMessage(
Kind.ERROR,
String.format("%s is not a gRPC service class", type),
serviceImplementation,
grpcServiceAnnotation(),
value);
return false;
}
if (!(types.isSubtype(serviceImplementation.asType(), serviceImplBase.asType()))) {
messager.printMessage(
Kind.ERROR,
String.format(
"%s must extend %s", serviceImplementation, serviceImplBase.getQualifiedName()),
serviceImplementation,
grpcServiceAnnotation(),
value);
return false;
}
return true;
}
private TypeMirror bindableService() {
return elements.getTypeElement(IoGrpc.BINDABLE_SERVICE.toString()).asType();
}
static final AnnotationValueVisitor<TypeElement, AnnotationValue> GET_TYPE_ELEMENT_FROM_VALUE =
new SimpleAnnotationValueVisitor7<TypeElement, AnnotationValue>() {
@Override
public TypeElement visitType(TypeMirror t, AnnotationValue p) {
return MoreTypes.asTypeElement(t);
}
@Override
protected TypeElement defaultAction(Object o, AnnotationValue p) {
throw new IllegalArgumentException("Expected " + p + " to be a class");
}
};
}
|
declared
|
java
|
spring-projects__spring-security
|
config/src/main/java/org/springframework/security/config/annotation/web/reactive/EnableWebFluxSecurity.java
|
{
"start": 1977,
"end": 3052
}
|
class ____ {
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* .authorizeExchange()
* .anyExchange().authenticated()
* .and()
* .httpBasic().and()
* .formLogin();
* return http.build();
* }
*
* @Bean
* public MapReactiveUserDetailsService userDetailsService() {
* UserDetails user = User.withDefaultPasswordEncoder()
* .username("user")
* .password("password")
* .roles("USER")
* .build();
* return new MapReactiveUserDetailsService(user);
* }
* }
* </pre>
*
* @author Rob Winch
* @since 5.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import({ ServerHttpSecurityConfiguration.class, WebFluxSecurityConfiguration.class,
ReactiveOAuth2ClientImportSelector.class, ReactiveObservationImportSelector.class })
public @
|
MyExplicitSecurityConfiguration
|
java
|
apache__logging-log4j2
|
log4j-core/src/main/java/org/apache/logging/log4j/core/filter/CompositeFilter.java
|
{
"start": 1902,
"end": 21464
}
|
class ____ extends AbstractLifeCycle implements Iterable<Filter>, Filter {
private final Filter[] filters;
private CompositeFilter(final Filter[] filters) {
this.filters = filters == null ? Filter.EMPTY_ARRAY : filters;
}
public CompositeFilter addFilter(final Filter filter) {
if (filter == null) {
// null does nothing
return this;
}
if (filter instanceof CompositeFilter) {
final CompositeFilter compositeFilter = (CompositeFilter) filter;
final Filter[] copy = Arrays.copyOf(this.filters, this.filters.length + compositeFilter.size());
System.arraycopy(compositeFilter.filters, 0, copy, this.filters.length, compositeFilter.filters.length);
return new CompositeFilter(copy);
}
final Filter[] copy = Arrays.copyOf(this.filters, this.filters.length + 1);
copy[this.filters.length] = filter;
return new CompositeFilter(copy);
}
public CompositeFilter removeFilter(final Filter filter) {
if (filter == null) {
// null does nothing
return this;
}
// This is not a great implementation but simpler than copying Apache Commons
// Lang ArrayUtils.removeElement() and associated bits (MutableInt),
// which is OK since removing a filter should not be on the critical path.
final List<Filter> filterList = new ArrayList<>(Arrays.asList(this.filters));
if (filter instanceof CompositeFilter) {
for (final Filter currentFilter : ((CompositeFilter) filter).filters) {
filterList.remove(currentFilter);
}
} else {
filterList.remove(filter);
}
return new CompositeFilter(filterList.toArray(Filter.EMPTY_ARRAY));
}
@Override
public Iterator<Filter> iterator() {
return new ObjectArrayIterator<>(filters);
}
/**
* Gets a new list over the internal filter array.
*
* @return a new list over the internal filter array
* @deprecated Use {@link #getFiltersArray()}
*/
@Deprecated
public List<Filter> getFilters() {
return Arrays.asList(filters);
}
public Filter[] getFiltersArray() {
return filters;
}
/**
* Returns whether this composite contains any filters.
*
* @return whether this composite contains any filters.
*/
public boolean isEmpty() {
return this.filters.length == 0;
}
public int size() {
return filters.length;
}
@Override
public void start() {
this.setStarting();
for (final Filter filter : filters) {
filter.start();
}
this.setStarted();
}
@Override
public boolean stop(final long timeout, final TimeUnit timeUnit) {
this.setStopping();
for (final Filter filter : filters) {
if (filter instanceof LifeCycle2) {
((LifeCycle2) filter).stop(timeout, timeUnit);
} else {
filter.stop();
}
}
setStopped();
return true;
}
/**
* Returns the result that should be returned when the filter does not match the event.
*
* @return the Result that should be returned when the filter does not match the event.
*/
@Override
public Result getOnMismatch() {
return Result.NEUTRAL;
}
/**
* Returns the result that should be returned when the filter matches the event.
*
* @return the Result that should be returned when the filter matches the event.
*/
@Override
public Result getOnMatch() {
return Result.NEUTRAL;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* String text to filter on.
* @param params
* An array of parameters or null.
* @return the Result.
*/
@Override
public Result filter(
final Logger logger, final Level level, final Marker marker, final String msg, final Object... params) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, params);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* String text to filter on.
* @param p0 the message parameters
* @return the Result.
*/
@Override
public Result filter(
final Logger logger, final Level level, final Marker marker, final String msg, final Object p0) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, p0);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* String text to filter on.
* @param p0 the message parameters
* @param p1 the message parameters
* @return the Result.
*/
@Override
public Result filter(
final Logger logger,
final Level level,
final Marker marker,
final String msg,
final Object p0,
final Object p1) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, p0, p1);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* String text to filter on.
* @param p0 the message parameters
* @param p1 the message parameters
* @param p2 the message parameters
* @return the Result.
*/
@Override
public Result filter(
final Logger logger,
final Level level,
final Marker marker,
final String msg,
final Object p0,
final Object p1,
final Object p2) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, p0, p1, p2);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* String text to filter on.
* @param p0 the message parameters
* @param p1 the message parameters
* @param p2 the message parameters
* @param p3 the message parameters
* @return the Result.
*/
@Override
public Result filter(
final Logger logger,
final Level level,
final Marker marker,
final String msg,
final Object p0,
final Object p1,
final Object p2,
final Object p3) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, p0, p1, p2, p3);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* String text to filter on.
* @param p0 the message parameters
* @param p1 the message parameters
* @param p2 the message parameters
* @param p3 the message parameters
* @param p4 the message parameters
* @return the Result.
*/
@Override
public Result filter(
final Logger logger,
final Level level,
final Marker marker,
final String msg,
final Object p0,
final Object p1,
final Object p2,
final Object p3,
final Object p4) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, p0, p1, p2, p3, p4);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* String text to filter on.
* @param p0 the message parameters
* @param p1 the message parameters
* @param p2 the message parameters
* @param p3 the message parameters
* @param p4 the message parameters
* @param p5 the message parameters
* @return the Result.
*/
@Override
public Result filter(
final Logger logger,
final Level level,
final Marker marker,
final String msg,
final Object p0,
final Object p1,
final Object p2,
final Object p3,
final Object p4,
final Object p5) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, p0, p1, p2, p3, p4, p5);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* String text to filter on.
* @param p0 the message parameters
* @param p1 the message parameters
* @param p2 the message parameters
* @param p3 the message parameters
* @param p4 the message parameters
* @param p5 the message parameters
* @param p6 the message parameters
* @return the Result.
*/
@Override
public Result filter(
final Logger logger,
final Level level,
final Marker marker,
final String msg,
final Object p0,
final Object p1,
final Object p2,
final Object p3,
final Object p4,
final Object p5,
final Object p6) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, p0, p1, p2, p3, p4, p5, p6);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* String text to filter on.
* @param p0 the message parameters
* @param p1 the message parameters
* @param p2 the message parameters
* @param p3 the message parameters
* @param p4 the message parameters
* @param p5 the message parameters
* @param p6 the message parameters
* @param p7 the message parameters
* @return the Result.
*/
@Override
public Result filter(
final Logger logger,
final Level level,
final Marker marker,
final String msg,
final Object p0,
final Object p1,
final Object p2,
final Object p3,
final Object p4,
final Object p5,
final Object p6,
final Object p7) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, p0, p1, p2, p3, p4, p5, p6, p7);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* String text to filter on.
* @param p0 the message parameters
* @param p1 the message parameters
* @param p2 the message parameters
* @param p3 the message parameters
* @param p4 the message parameters
* @param p5 the message parameters
* @param p6 the message parameters
* @param p7 the message parameters
* @param p8 the message parameters
* @return the Result.
*/
@Override
public Result filter(
final Logger logger,
final Level level,
final Marker marker,
final String msg,
final Object p0,
final Object p1,
final Object p2,
final Object p3,
final Object p4,
final Object p5,
final Object p6,
final Object p7,
final Object p8) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, p0, p1, p2, p3, p4, p5, p6, p7, p8);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* String text to filter on.
* @param p0 the message parameters
* @param p1 the message parameters
* @param p2 the message parameters
* @param p3 the message parameters
* @param p4 the message parameters
* @param p5 the message parameters
* @param p6 the message parameters
* @param p7 the message parameters
* @param p8 the message parameters
* @param p9 the message parameters
* @return the Result.
*/
@Override
public Result filter(
final Logger logger,
final Level level,
final Marker marker,
final String msg,
final Object p0,
final Object p1,
final Object p2,
final Object p3,
final Object p4,
final Object p5,
final Object p6,
final Object p7,
final Object p8,
final Object p9) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* Any Object.
* @param t
* A Throwable or null.
* @return the Result.
*/
@Override
public Result filter(
final Logger logger, final Level level, final Marker marker, final Object msg, final Throwable t) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, t);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param logger
* The Logger.
* @param level
* The event logging Level.
* @param marker
* The Marker for the event or null.
* @param msg
* The Message
* @param t
* A Throwable or null.
* @return the Result.
*/
@Override
public Result filter(
final Logger logger, final Level level, final Marker marker, final Message msg, final Throwable t) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(logger, level, marker, msg, t);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
/**
* Filter an event.
*
* @param event
* The Event to filter on.
* @return the Result.
*/
@Override
public Result filter(final LogEvent event) {
Result result = Result.NEUTRAL;
for (int i = 0; i < filters.length; i++) {
result = filters[i].filter(event);
if (result == Result.ACCEPT || result == Result.DENY) {
return result;
}
}
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < filters.length; i++) {
if (sb.length() == 0) {
sb.append('{');
} else {
sb.append(", ");
}
sb.append(filters[i].toString());
}
if (sb.length() > 0) {
sb.append('}');
}
return sb.toString();
}
/**
* Creates a CompositeFilter.
*
* @param filters
* An array of Filters to call.
* @return The CompositeFilter.
*/
@PluginFactory
public static CompositeFilter createFilters(@PluginElement("Filters") final Filter... filters) {
return new CompositeFilter(filters);
}
}
|
CompositeFilter
|
java
|
elastic__elasticsearch
|
qa/packaging/src/test/java/org/elasticsearch/packaging/test/PackagesSecurityAutoConfigurationTests.java
|
{
"start": 2531,
"end": 19563
}
|
class ____ extends PackagingTestCase {
private static final String AUTOCONFIG_DIRNAME = "certs";
@BeforeClass
public static void filterDistros() {
assumeTrue("rpm or deb", distribution.isPackage());
}
public void test10SecurityAutoConfiguredOnPackageInstall() throws Exception {
assertRemoved(distribution());
installation = installPackage(sh, distribution(), successfulAutoConfiguration());
assertInstalled(distribution());
verifyPackageInstallation(installation, distribution(), sh);
verifySecurityAutoConfigured(installation);
assertNotNull(installation.getElasticPassword());
}
public void test20SecurityNotAutoConfiguredOnReInstallation() throws Exception {
// we are testing force upgrading in the current version
// In such a case, security remains configured from the initial installation, we don't run it again.
byte[] transportKeystore = Files.readAllBytes(installation.config(AUTOCONFIG_DIRNAME).resolve("transport.p12"));
installation = Packages.forceUpgradePackage(sh, distribution);
assertInstalled(distribution);
verifyPackageInstallation(installation, distribution, sh);
verifySecurityAutoConfigured(installation);
// Since we did not auto-configure the second time, the keystore should be the one we generated the first time, above
assertThat(transportKeystore, equalTo(Files.readAllBytes(installation.config(AUTOCONFIG_DIRNAME).resolve("transport.p12"))));
}
public void test30SecurityNotAutoConfiguredWhenExistingDataDir() throws Exception {
// This is a contrived example for packages where in a new installation, there is an
// existing data directory but the rest of the package tracked config files were removed
final Path dataPath = installation.data;
cleanup();
Files.createDirectory(dataPath);
append(dataPath.resolve("foo"), "some data");
installation = installPackage(sh, distribution(), existingSecurityConfiguration());
verifySecurityNotAutoConfigured(installation);
}
public void test40SecurityNotAutoConfiguredWhenExistingKeystoreUnknownPassword() throws Exception {
// This is a contrived example for packages where in a new installation, there is an
// existing elasticsearch.keystore file within $ES_PATH_CONF and it's password-protected
final Installation.Executables bin = installation.executables();
bin.keystoreTool.run("passwd", "some_password\nsome_password\n");
final Path tempDir = createTempDir("existing-keystore-config");
final Path confPath = installation.config;
Files.copy(
confPath.resolve("elasticsearch.keystore"),
tempDir.resolve("elasticsearch.keystore"),
StandardCopyOption.COPY_ATTRIBUTES
);
cleanup();
Files.createDirectory(confPath);
Files.copy(
tempDir.resolve("elasticsearch.keystore"),
confPath.resolve("elasticsearch.keystore"),
StandardCopyOption.COPY_ATTRIBUTES
);
installation = installPackage(sh, distribution(), errorOutput());
List<String> configLines = Files.readAllLines(installation.config("elasticsearch.yml"));
assertThat(configLines, not(hasItem("# have been automatically generated in order to configure Security. #")));
}
public void test50ReconfigureAndEnroll() throws Exception {
cleanup();
assertRemoved(distribution());
installation = installPackage(sh, distribution(), successfulAutoConfiguration());
assertInstalled(distribution());
verifyPackageInstallation(installation, distribution(), sh);
verifySecurityAutoConfigured(installation);
assertNotNull(installation.getElasticPassword());
// We cannot run two packaged installations simultaneously here so that we can test that the second node enrolls successfully
// We trigger with an invalid enrollment token, to verify that we removed the existing auto-configuration
Shell.Result result = installation.executables().nodeReconfigureTool.run("--enrollment-token thisisinvalid", "y", true);
assertThat(result.exitCode(), equalTo(ExitCodes.DATA_ERROR)); // invalid enrollment token
verifySecurityNotAutoConfigured(installation);
}
public void test60ReconfigureWithoutEnrollmentToken() throws Exception {
cleanup();
assertRemoved(distribution());
installation = installPackage(sh, distribution(), successfulAutoConfiguration());
assertInstalled(distribution());
verifyPackageInstallation(installation, distribution(), sh);
verifySecurityAutoConfigured(installation);
assertNotNull(installation.getElasticPassword());
Shell.Result result = installation.executables().nodeReconfigureTool.run("", null, true);
assertThat(result.exitCode(), equalTo(ExitCodes.USAGE)); // missing enrollment token
// we fail on command invocation so we don't even try to remove autoconfiguration
verifySecurityAutoConfigured(installation);
}
// The following could very well be unit tests but the way we delete files doesn't play well with jimfs
public void test70ReconfigureFailsWhenTlsAutoConfDirMissing() throws Exception {
cleanup();
assertRemoved(distribution());
installation = installPackage(sh, distribution(), successfulAutoConfiguration());
assertInstalled(distribution());
verifyPackageInstallation(installation, distribution(), sh);
verifySecurityAutoConfigured(installation);
assertNotNull(installation.getElasticPassword());
// Move instead of delete because Files.deleteIfExists bails on non empty dirs
Files.move(installation.config(AUTOCONFIG_DIRNAME), installation.config("temp-autoconf-dir"));
Shell.Result result = installation.executables().nodeReconfigureTool.run("--enrollment-token a-token", "y", true);
assertThat(result.exitCode(), equalTo(ExitCodes.USAGE)); //
}
public void test71ReconfigureFailsWhenKeyStorePasswordWrong() throws Exception {
cleanup();
assertRemoved(distribution());
installation = installPackage(sh, distribution(), successfulAutoConfiguration());
assertInstalled(distribution());
verifyPackageInstallation(installation, distribution(), sh);
verifySecurityAutoConfigured(installation);
assertNotNull(installation.getElasticPassword());
Shell.Result changePassword = installation.executables().keystoreTool.run("passwd", "some-password\nsome-password\n");
assertThat(changePassword.exitCode(), equalTo(0));
Shell.Result result = installation.executables().nodeReconfigureTool.run(
"--enrollment-token a-token",
"y" + "\n" + "some-wrong-password",
true
);
assertThat(result.exitCode(), equalTo(ExitCodes.IO_ERROR)); //
assertThat(result.stderr(), containsString("Error was: Provided keystore password was incorrect"));
}
public void test71ReconfigureFailsWhenKeyStoreDoesNotContainExpectedSettings() throws Exception {
cleanup();
assertRemoved(distribution());
installation = installPackage(sh, distribution(), successfulAutoConfiguration());
assertInstalled(distribution());
verifyPackageInstallation(installation, distribution(), sh);
verifySecurityAutoConfigured(installation);
assertNotNull(installation.getElasticPassword());
Shell.Result removeSetting = installation.executables().keystoreTool.run(
"remove xpack.security.transport.ssl.keystore.secure_password"
);
assertThat(removeSetting.exitCode(), equalTo(0));
Shell.Result result = installation.executables().nodeReconfigureTool.run("--enrollment-token a-token", "y", true);
assertThat(result.exitCode(), equalTo(ExitCodes.IO_ERROR));
assertThat(
result.stderr(),
containsString(
"elasticsearch.keystore did not contain expected setting [xpack.security.transport.ssl.keystore.secure_password]."
)
);
}
public void test72ReconfigureFailsWhenConfigurationDoesNotContainSecurityAutoConfig() throws Exception {
cleanup();
assertRemoved(distribution());
installation = installPackage(sh, distribution(), successfulAutoConfiguration());
assertInstalled(distribution());
verifyPackageInstallation(installation, distribution(), sh);
verifySecurityAutoConfigured(installation);
assertNotNull(installation.getElasticPassword());
// We remove everything. We don't need to be precise and remove only auto-configuration, the rest are commented out either way
Path yml = installation.config("elasticsearch.yml");
Files.write(yml, List.of(), TRUNCATE_EXISTING);
Shell.Result result = installation.executables().nodeReconfigureTool.run("--enrollment-token a-token", "y", true);
assertThat(result.exitCode(), equalTo(ExitCodes.USAGE)); //
assertThat(result.stderr(), containsString("Expected configuration is missing from elasticsearch.yml."));
}
public void test72ReconfigureRetainsUserSettings() throws Exception {
cleanup();
assertRemoved(distribution());
installation = installPackage(sh, distribution(), successfulAutoConfiguration());
assertInstalled(distribution());
verifyPackageInstallation(installation, distribution(), sh);
verifySecurityAutoConfigured(installation);
assertNotNull(installation.getElasticPassword());
// We remove everything. We don't need to be precise and remove only auto-configuration, the rest are commented out either way
Path yml = installation.config("elasticsearch.yml");
List<String> allLines = Files.readAllLines(yml);
// Replace a comment we know exists in the auto-configuration stanza, with a user defined setting
allLines.set(
allLines.indexOf("# Enable encryption for HTTP API client connections, such as Kibana, Logstash, and Agents"),
"cluster.name: testclustername"
);
allLines.add("node.name: testnodename");
Files.write(yml, allLines, TRUNCATE_EXISTING);
// We cannot run two packaged installations simultaneously here so that we can test that the second node enrolls successfully
// We trigger with an invalid enrollment token, to verify that we removed the existing auto-configuration
Shell.Result result = installation.executables().nodeReconfigureTool.run("--enrollment-token thisisinvalid", "y", true);
assertThat(result.exitCode(), equalTo(ExitCodes.DATA_ERROR)); // invalid enrollment token
verifySecurityNotAutoConfigured(installation);
// Check that user configuration , both inside and outside the autocofiguration stanza, was retained
Path editedYml = installation.config("elasticsearch.yml");
List<String> newConfigurationLines = Files.readAllLines(editedYml);
assertThat(newConfigurationLines, hasItem("cluster.name: testclustername"));
assertThat(newConfigurationLines, hasItem("node.name: testnodename"));
}
public void test73ReconfigureCreatesFilesWithCorrectPermissions() throws Exception {
cleanup();
assertRemoved(distribution());
installation = installPackage(sh, distribution(), successfulAutoConfiguration());
assertInstalled(distribution());
verifyPackageInstallation(installation, distribution(), sh);
verifySecurityAutoConfigured(installation);
assertNotNull(installation.getElasticPassword());
final PemKeyConfig keyConfig = new PemKeyConfig(
Paths.get(getClass().getResource("http.crt").toURI()).toAbsolutePath().normalize().toString(),
Paths.get(getClass().getResource("http.key").toURI()).toAbsolutePath().normalize().toString(),
new char[0],
Paths.get(getClass().getResource("http.crt").toURI()).getParent().toAbsolutePath().normalize()
);
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(new KeyManager[] { keyConfig.createKeyManager() }, new TrustManager[] {}, new SecureRandom());
// We can't run multiple nodes as package installations. We mock an initial node that would respond to the enroll node API
try (MockWebServer mockNode = new MockWebServer(sslContext, false)) {
mockNode.start();
final String httpCaCertPemString = Files.readAllLines(
Paths.get(getClass().getResource("http_ca.crt").toURI()).toAbsolutePath().normalize()
).stream().filter(l -> l.contains("-----") == false).collect(Collectors.joining());
final String httpCaKeyPemString = Files.readAllLines(
Paths.get(getClass().getResource("http_ca.key").toURI()).toAbsolutePath().normalize()
).stream().filter(l -> l.contains("-----") == false).collect(Collectors.joining());
final String transportCaCertPemString = Files.readAllLines(
Paths.get(getClass().getResource("transport_ca.crt").toURI()).toAbsolutePath().normalize()
).stream().filter(l -> l.contains("-----") == false).collect(Collectors.joining());
final String transportKeyPemString = Files.readAllLines(
Paths.get(getClass().getResource("transport.key").toURI()).toAbsolutePath().normalize()
).stream().filter(l -> l.contains("-----") == false).collect(Collectors.joining());
final String transportCertPemString = Files.readAllLines(
Paths.get(getClass().getResource("transport.crt").toURI()).toAbsolutePath().normalize()
).stream().filter(l -> l.contains("-----") == false).collect(Collectors.joining());
final XContentBuilder responseBuilder = jsonBuilder().startObject()
.field("http_ca_key", httpCaKeyPemString)
.field("http_ca_cert", httpCaCertPemString)
.field("transport_ca_cert", transportCaCertPemString)
.field("transport_key", transportKeyPemString)
.field("transport_cert", transportCertPemString)
.array("nodes_addresses", "192.168.1.23:9300") // won't be used, can be anything
.endObject();
mockNode.enqueue(new MockResponse().setResponseCode(200).setBody(Strings.toString(responseBuilder)));
final EnrollmentToken enrollmentToken = new EnrollmentToken(
"some-api-key",
"b0150fd8a29f9012207912de9a01aa1d1f0dd696c847d3a9353881f9045bf442", // fingerprint of http_ca.crt
List.of(mockNode.getHostName() + ":" + mockNode.getPort())
);
Shell.Result result = installation.executables().nodeReconfigureTool.run(
"-v --enrollment-token " + enrollmentToken.getEncoded(),
"y",
true
);
assertThat(result.exitCode(), CoreMatchers.equalTo(0));
assertThat(installation.config(AUTOCONFIG_DIRNAME), FileMatcher.file(Directory, "root", "elasticsearch", p750));
Stream.of("http.p12", "http_ca.crt", "transport.p12")
.forEach(
file -> assertThat(
installation.config(AUTOCONFIG_DIRNAME).resolve(file),
FileMatcher.file(File, "root", "elasticsearch", p660)
)
);
}
}
private Predicate<String> successfulAutoConfiguration() {
Predicate<String> p1 = output -> output.contains("Authentication and authorization are enabled.");
Predicate<String> p2 = output -> output.contains("TLS for the transport and HTTP layers is enabled and configured.");
Predicate<String> p3 = output -> output.contains("The generated password for the elastic built-in superuser is :");
return p1.and(p2).and(p3);
}
private Predicate<String> existingSecurityConfiguration() {
return output -> output.contains("Skipping auto-configuration because security features appear to be already configured.");
}
private Predicate<String> errorOutput() {
Predicate<String> p1 = output -> output.contains("Failed to auto-configure security features.");
Predicate<String> p2 = output -> output.contains("However, authentication and authorization are still enabled.");
Predicate<String> p3 = output -> output.contains("You can reset the password of the elastic built-in superuser with");
Predicate<String> p4 = output -> output.contains("/usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic");
return p1.and(p2).and(p3).and(p4);
}
}
|
PackagesSecurityAutoConfigurationTests
|
java
|
apache__kafka
|
connect/runtime/src/test/java/org/apache/kafka/connect/integration/ExampleConnectIntegrationTest.java
|
{
"start": 2715,
"end": 11611
}
|
class ____ {
private static final Logger log = LoggerFactory.getLogger(ExampleConnectIntegrationTest.class);
private static final int NUM_RECORDS_PRODUCED = 2000;
private static final int NUM_TOPIC_PARTITIONS = 3;
private static final long RECORD_TRANSFER_DURATION_MS = TimeUnit.SECONDS.toMillis(30);
private static final long CONNECTOR_SETUP_DURATION_MS = TimeUnit.SECONDS.toMillis(60);
private static final int NUM_TASKS = 3;
private static final int NUM_WORKERS = 3;
private static final String CONNECTOR_NAME = "simple-conn";
private static final String SINK_CONNECTOR_CLASS_NAME = TestableSinkConnector.class.getSimpleName();
private static final String SOURCE_CONNECTOR_CLASS_NAME = TestableSourceConnector.class.getSimpleName();
private EmbeddedConnectCluster connect;
private ConnectorHandle connectorHandle;
@BeforeEach
public void setup() {
// setup Connect worker properties
Map<String, String> exampleWorkerProps = new HashMap<>();
exampleWorkerProps.put(OFFSET_COMMIT_INTERVAL_MS_CONFIG, String.valueOf(5_000));
// setup Kafka broker properties
Properties exampleBrokerProps = new Properties();
exampleBrokerProps.put("auto.create.topics.enable", "false");
// build a Connect cluster backed by a Kafka KRaft cluster
connect = new EmbeddedConnectCluster.Builder()
.name("connect-cluster")
.numWorkers(NUM_WORKERS)
.numBrokers(1)
.workerProps(exampleWorkerProps)
.brokerProps(exampleBrokerProps)
.build();
// start the clusters
connect.start();
// get a handle to the connector
connectorHandle = RuntimeHandles.get().connectorHandle(CONNECTOR_NAME);
}
@AfterEach
public void close() {
// delete connector handle
RuntimeHandles.get().deleteConnector(CONNECTOR_NAME);
// stop the Connect cluster and its backing Kafka cluster.
connect.stop();
}
/**
* Simple test case to configure and execute an embedded Connect cluster. The test will produce and consume
* records, and start up a sink connector which will consume these records.
*/
@Test
public void testSinkConnector() throws Exception {
// create test topic
connect.kafka().createTopic("test-topic", NUM_TOPIC_PARTITIONS);
// setup up props for the sink connector
Map<String, String> props = new HashMap<>();
props.put(CONNECTOR_CLASS_CONFIG, SINK_CONNECTOR_CLASS_NAME);
props.put(TASKS_MAX_CONFIG, String.valueOf(NUM_TASKS));
props.put(TOPICS_CONFIG, "test-topic");
props.put(KEY_CONVERTER_CLASS_CONFIG, StringConverter.class.getName());
props.put(VALUE_CONVERTER_CLASS_CONFIG, StringConverter.class.getName());
// expect all records to be consumed by the connector
connectorHandle.expectedRecords(NUM_RECORDS_PRODUCED);
// expect all records to be consumed by the connector
connectorHandle.expectedCommits(NUM_RECORDS_PRODUCED);
// validate the intended connector configuration, a config that errors
connect.assertions().assertExactlyNumErrorsOnConnectorConfigValidation(SINK_CONNECTOR_CLASS_NAME, props, 1,
"Validating connector configuration produced an unexpected number or errors.");
// add missing configuration to make the config valid
props.put("name", CONNECTOR_NAME);
// validate the intended connector configuration, a valid config
connect.assertions().assertExactlyNumErrorsOnConnectorConfigValidation(SINK_CONNECTOR_CLASS_NAME, props, 0,
"Validating connector configuration produced an unexpected number or errors.");
// start a sink connector
connect.configureConnector(CONNECTOR_NAME, props);
waitForCondition(this::checkForPartitionAssignment,
CONNECTOR_SETUP_DURATION_MS,
"Connector tasks were not assigned a partition each.");
// produce some messages into source topic partitions
for (int i = 0; i < NUM_RECORDS_PRODUCED; i++) {
connect.kafka().produce("test-topic", i % NUM_TOPIC_PARTITIONS, "key", "simple-message-value-" + i);
}
// consume all records from the source topic or fail, to ensure that they were correctly produced.
assertEquals(NUM_RECORDS_PRODUCED,
connect.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic").count(),
"Unexpected number of records consumed");
// wait for the connector tasks to consume all records.
connectorHandle.awaitRecords(RECORD_TRANSFER_DURATION_MS);
// wait for the connector tasks to commit all records.
connectorHandle.awaitCommits(RECORD_TRANSFER_DURATION_MS);
// delete connector
connect.deleteConnector(CONNECTOR_NAME);
}
/**
* Simple test case to configure and execute an embedded Connect cluster. The test will produce and consume
* records, and start up a sink connector which will consume these records.
*/
@Test
public void testSourceConnector() throws Exception {
// create test topic
connect.kafka().createTopic("test-topic", NUM_TOPIC_PARTITIONS);
// setup up props for the source connector
Map<String, String> props = new HashMap<>();
props.put(CONNECTOR_CLASS_CONFIG, SOURCE_CONNECTOR_CLASS_NAME);
props.put(TASKS_MAX_CONFIG, String.valueOf(NUM_TASKS));
props.put("topic", "test-topic");
props.put("throughput", String.valueOf(500));
props.put(KEY_CONVERTER_CLASS_CONFIG, StringConverter.class.getName());
props.put(VALUE_CONVERTER_CLASS_CONFIG, StringConverter.class.getName());
props.put(DEFAULT_TOPIC_CREATION_PREFIX + REPLICATION_FACTOR_CONFIG, String.valueOf(1));
props.put(DEFAULT_TOPIC_CREATION_PREFIX + PARTITIONS_CONFIG, String.valueOf(1));
// expect all records to be produced by the connector
connectorHandle.expectedRecords(NUM_RECORDS_PRODUCED);
// expect all records to be produced by the connector
connectorHandle.expectedCommits(NUM_RECORDS_PRODUCED);
// validate the intended connector configuration, a config that errors
connect.assertions().assertExactlyNumErrorsOnConnectorConfigValidation(SOURCE_CONNECTOR_CLASS_NAME, props, 1,
"Validating connector configuration produced an unexpected number or errors.");
// add missing configuration to make the config valid
props.put("name", CONNECTOR_NAME);
// validate the intended connector configuration, a valid config
connect.assertions().assertExactlyNumErrorsOnConnectorConfigValidation(SOURCE_CONNECTOR_CLASS_NAME, props, 0,
"Validating connector configuration produced an unexpected number or errors.");
// start a source connector
connect.configureConnector(CONNECTOR_NAME, props);
// wait for the connector tasks to produce enough records
connectorHandle.awaitRecords(RECORD_TRANSFER_DURATION_MS);
// wait for the connector tasks to commit enough records
connectorHandle.awaitCommits(RECORD_TRANSFER_DURATION_MS);
// consume all records from the source topic or fail, to ensure that they were correctly produced
int recordNum = connect.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic").count();
assertTrue(recordNum >= NUM_RECORDS_PRODUCED,
"Not enough records produced by source connector. Expected at least: " + NUM_RECORDS_PRODUCED + " + but got " + recordNum);
// delete connector
connect.deleteConnector(CONNECTOR_NAME);
}
/**
* Check if a partition was assigned to each task. This method swallows exceptions since it is invoked from a
* {@link org.apache.kafka.test.TestUtils#waitForCondition} that will throw an error if this method continued
* to return false after the specified duration has elapsed.
*
* @return true if each task was assigned a partition each, false if this was not true or an error occurred when
* executing this operation.
*/
private boolean checkForPartitionAssignment() {
try {
ConnectorStateInfo info = connect.connectorStatus(CONNECTOR_NAME);
return info != null && info.tasks().size() == NUM_TASKS
&& connectorHandle.tasks().stream().allMatch(th -> th.numPartitionsAssigned() == 1);
} catch (Exception e) {
// Log the exception and return that the partitions were not assigned
log.error("Could not check connector state info.", e);
return false;
}
}
}
|
ExampleConnectIntegrationTest
|
java
|
google__guava
|
android/guava/src/com/google/common/cache/LocalCache.java
|
{
"start": 46520,
"end": 47388
}
|
class ____<K, V> implements ValueReference<K, V> {
final V referent;
StrongValueReference(V referent) {
this.referent = referent;
}
@Override
public V get() {
return referent;
}
@Override
public int getWeight() {
return 1;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return this;
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return true;
}
@Override
public V waitForValue() {
return get();
}
@Override
public void notifyNewValue(V newValue) {}
}
/** References a weak value. */
static final
|
StrongValueReference
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/operators/hash/NonReusingHashJoinIteratorITCase.java
|
{
"start": 50640,
"end": 51776
}
|
class ____ {
private final String left;
private final String right;
public TupleMatch(String left, String right) {
this.left = left;
this.right = right;
}
@Override
public boolean equals(Object obj) {
TupleMatch that = (TupleMatch) obj;
return (this.right == null
? that.right == null
: (that.right != null && this.right.equals(that.right)))
&& (this.left == null
? that.left == null
: (that.left != null && this.left.equals(that.left)));
}
@Override
public int hashCode() {
int hc = this.left != null ? this.left.hashCode() : 23;
hc = hc ^ (this.right != null ? this.right.hashCode() : 41);
return hc;
}
@Override
public String toString() {
String s = left == null ? "<null>" : left;
s += ", " + (right == null ? "<null>" : right);
return s;
}
}
/** Private
|
TupleMatch
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NodeLabelUtil.java
|
{
"start": 1197,
"end": 1268
}
|
class ____ all NodeLabel and NodeAttribute operations.
*/
public final
|
for
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/action/QlStatusResponseTests.java
|
{
"start": 909,
"end": 3648
}
|
class ____ extends AbstractWireSerializingTestCase<QlStatusResponse> {
@Override
protected QlStatusResponse createTestInstance() {
String id = randomSearchId();
boolean isRunning = randomBoolean();
boolean isPartial = isRunning ? randomBoolean() : false;
long randomDate = (new Date(randomLongBetween(0, 3000000000000L))).getTime();
Long startTimeMillis = randomBoolean() ? null : randomDate;
long expirationTimeMillis = startTimeMillis == null ? randomDate : startTimeMillis + 3600000L;
RestStatus completionStatus = isRunning ? null : randomBoolean() ? RestStatus.OK : RestStatus.SERVICE_UNAVAILABLE;
return new QlStatusResponse(id, isRunning, isPartial, startTimeMillis, expirationTimeMillis, completionStatus);
}
@Override
protected Writeable.Reader<QlStatusResponse> instanceReader() {
return QlStatusResponse::new;
}
@Override
protected QlStatusResponse mutateInstance(QlStatusResponse instance) {
// return a response with the opposite running status
boolean isRunning = instance.isRunning() == false;
boolean isPartial = isRunning ? randomBoolean() : false;
RestStatus completionStatus = isRunning ? null : randomBoolean() ? RestStatus.OK : RestStatus.SERVICE_UNAVAILABLE;
return new QlStatusResponse(
instance.getId(),
isRunning,
isPartial,
instance.getStartTime(),
instance.getExpirationTime(),
completionStatus
);
}
public void testToXContent() throws IOException {
QlStatusResponse response = createTestInstance();
try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) {
Object[] args = new Object[] {
response.getId(),
response.isRunning(),
response.isPartial(),
response.getStartTime() != null ? "\"start_time_in_millis\" : " + response.getStartTime() + "," : "",
response.getExpirationTime(),
response.getCompletionStatus() != null ? ", \"completion_status\" : " + response.getCompletionStatus().getStatus() : "" };
String expectedJson = Strings.format("""
{
"id" : "%s",
"is_running" : %s,
"is_partial" : %s,
%s
"expiration_time_in_millis" : %s
%s
}
""", args);
response.toXContent(builder, ToXContent.EMPTY_PARAMS);
assertEquals(XContentHelper.stripWhitespace(expectedJson), Strings.toString(builder));
}
}
}
|
QlStatusResponseTests
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/util/xml/XmlValidationModeDetectorTests.java
|
{
"start": 1156,
"end": 2316
}
|
class ____ {
private final XmlValidationModeDetector xmlValidationModeDetector = new XmlValidationModeDetector();
@ParameterizedTest
@ValueSource(strings = {
"dtdWithNoComments.xml",
"dtdWithLeadingComment.xml",
"dtdWithTrailingComment.xml",
"dtdWithTrailingCommentAcrossMultipleLines.xml",
"dtdWithCommentOnNextLine.xml",
"dtdWithMultipleComments.xml"
})
void dtdDetection(String fileName) throws Exception {
assertValidationMode(fileName, VALIDATION_DTD);
}
@ParameterizedTest
@ValueSource(strings = {
"xsdWithNoComments.xml",
"xsdWithMultipleComments.xml",
"xsdWithDoctypeInComment.xml",
"xsdWithDoctypeInOpenCommentWithAdditionalCommentOnSameLine.xml"
})
void xsdDetection(String fileName) throws Exception {
assertValidationMode(fileName, VALIDATION_XSD);
}
private void assertValidationMode(String fileName, int expectedValidationMode) throws IOException {
try (InputStream inputStream = getClass().getResourceAsStream(fileName)) {
assertThat(xmlValidationModeDetector.detectValidationMode(inputStream))
.as("Validation Mode")
.isEqualTo(expectedValidationMode);
}
}
}
|
XmlValidationModeDetectorTests
|
java
|
apache__camel
|
tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/MojoHelper.java
|
{
"start": 1210,
"end": 13887
}
|
class ____ {
private MojoHelper() {
}
public static List<Path> getComponentPath(Path dir) {
switch (dir.getFileName().toString()) {
case "camel-ai":
return Arrays.asList(dir.resolve("camel-chatscript"), dir.resolve("camel-djl"),
dir.resolve("camel-langchain4j-agent"),
dir.resolve("camel-langchain4j-core"), dir.resolve("camel-langchain4j-chat"),
dir.resolve("camel-langchain4j-embeddings"), dir.resolve("camel-langchain4j-embeddingstore"),
dir.resolve("camel-langchain4j-tokenizer"),
dir.resolve("camel-langchain4j-tools"), dir.resolve("camel-langchain4j-web-search"),
dir.resolve("camel-qdrant"), dir.resolve("camel-milvus"), dir.resolve("camel-neo4j"),
dir.resolve("camel-pinecone"), dir.resolve("camel-kserve"),
dir.resolve("camel-torchserve"), dir.resolve("camel-tensorflow-serving"),
dir.resolve("camel-weaviate"), dir.resolve("camel-docling"));
case "camel-as2":
return Collections.singletonList(dir.resolve("camel-as2-component"));
case "camel-avro-rpc":
return Collections.singletonList(dir.resolve("camel-avro-rpc-component"));
case "camel-cxf":
return Arrays.asList(dir.resolve("camel-cxf-soap"), dir.resolve("camel-cxf-rest"));
case "camel-salesforce":
return Collections.singletonList(dir.resolve("camel-salesforce-component"));
case "camel-dhis2":
return Collections.singletonList(dir.resolve("camel-dhis2-component"));
case "camel-olingo2":
return Collections.singletonList(dir.resolve("camel-olingo2-component"));
case "camel-olingo4":
return Collections.singletonList(dir.resolve("camel-olingo4-component"));
case "camel-box":
return Collections.singletonList(dir.resolve("camel-box-component"));
case "camel-servicenow":
return Collections.singletonList(dir.resolve("camel-servicenow-component"));
case "camel-fhir":
return Collections.singletonList(dir.resolve("camel-fhir-component"));
case "camel-infinispan":
return Arrays.asList(dir.resolve("camel-infinispan"), dir.resolve("camel-infinispan-embedded"));
case "camel-azure":
return Arrays.asList(dir.resolve("camel-azure-eventhubs"), dir.resolve("camel-azure-storage-blob"),
dir.resolve("camel-azure-storage-datalake"), dir.resolve("camel-azure-cosmosdb"),
dir.resolve("camel-azure-storage-queue"), dir.resolve("camel-azure-servicebus"),
dir.resolve("camel-azure-key-vault"), dir.resolve("camel-azure-files"),
dir.resolve("camel-azure-schema-registry"));
case "camel-google":
return Arrays.asList(dir.resolve("camel-google-bigquery"), dir.resolve("camel-google-calendar"),
dir.resolve("camel-google-drive"), dir.resolve("camel-google-mail"), dir.resolve("camel-google-pubsub"),
dir.resolve("camel-google-pubsub-lite"), dir.resolve("camel-google-sheets"),
dir.resolve("camel-google-storage"), dir.resolve("camel-google-functions"),
dir.resolve("camel-google-secret-manager"));
case "camel-debezium":
return Arrays.asList(dir.resolve("camel-debezium-mongodb"), dir.resolve("camel-debezium-mysql"),
dir.resolve("camel-debezium-postgres"), dir.resolve("camel-debezium-sqlserver"),
dir.resolve("camel-debezium-oracle"), dir.resolve("camel-debezium-db2"));
case "camel-microprofile":
return Arrays.asList(dir.resolve("camel-microprofile-config"),
dir.resolve("camel-microprofile-fault-tolerance"),
dir.resolve("camel-microprofile-health"));
case "camel-spring-parent":
return Arrays.asList(dir.resolve("camel-spring"),
dir.resolve("camel-spring-batch"), dir.resolve("camel-spring-cloud-config"),
dir.resolve("camel-spring-jdbc"), dir.resolve("camel-spring-ldap"),
dir.resolve("camel-spring-main"), dir.resolve("camel-spring-rabbitmq"),
dir.resolve("camel-spring-redis"), dir.resolve("camel-spring-security"),
dir.resolve("camel-spring-ws"), dir.resolve("camel-spring-xml"),
dir.resolve("camel-undertow-spring-security"),
dir.resolve("camel-spring-ai").resolve("camel-spring-ai-chat"),
dir.resolve("camel-spring-ai").resolve("camel-spring-ai-embeddings"),
dir.resolve("camel-spring-ai").resolve("camel-spring-ai-tools"),
dir.resolve("camel-spring-ai").resolve("camel-spring-ai-vector-store"));
case "camel-test":
return Arrays.asList(dir.resolve("camel-test-junit5"),
dir.resolve("camel-test-spring-junit5"),
dir.resolve("camel-test-main-junit5"));
case "camel-aws":
return Arrays.asList(dir.resolve("camel-aws2-athena"), dir.resolve("camel-aws2-cw"),
dir.resolve("camel-aws2-ddb"), dir.resolve("camel-aws2-ec2"),
dir.resolve("camel-aws2-ecs"), dir.resolve("camel-aws2-eks"), dir.resolve("camel-aws2-eventbridge"),
dir.resolve("camel-aws2-iam"),
dir.resolve("camel-aws2-kinesis"), dir.resolve("camel-aws2-kms"), dir.resolve("camel-aws2-lambda"),
dir.resolve("camel-aws2-mq"),
dir.resolve("camel-aws2-msk"), dir.resolve("camel-aws2-redshift"),
dir.resolve("camel-aws2-s3"), dir.resolve("camel-aws2-ses"),
dir.resolve("camel-aws2-sns"),
dir.resolve("camel-aws2-sqs"), dir.resolve("camel-aws2-step-functions"),
dir.resolve("camel-aws2-sts"),
dir.resolve("camel-aws2-timestream"), dir.resolve("camel-aws2-translate"),
dir.resolve("camel-aws-xray"), dir.resolve("camel-aws-secrets-manager"),
dir.resolve("camel-aws-cloudtrail"), dir.resolve("camel-aws-config"), dir.resolve("camel-aws-bedrock"),
dir.resolve("camel-aws2-textract"), dir.resolve("camel-aws2-transcribe"));
case "camel-vertx":
return Arrays.asList(dir.resolve("camel-vertx"),
dir.resolve("camel-vertx-http"),
dir.resolve("camel-vertx-websocket"));
case "camel-huawei":
return Arrays.asList(dir.resolve("camel-huaweicloud-frs"),
dir.resolve("camel-huaweicloud-dms"),
dir.resolve("camel-huaweicloud-functiongraph"),
dir.resolve("camel-huaweicloud-iam"),
dir.resolve("camel-huaweicloud-imagerecognition"),
dir.resolve("camel-huaweicloud-obs"),
dir.resolve("camel-huaweicloud-smn"));
case "camel-ibm":
return Arrays.asList(dir.resolve("camel-ibm-cos"),
dir.resolve("camel-ibm-secrets-manager"),
dir.resolve("camel-ibm-watson-language"),
dir.resolve("camel-ibm-watson-discovery"),
dir.resolve("camel-ibm-watson-text-to-speech"),
dir.resolve("camel-ibm-watson-speech-to-text"));
case "camel-knative":
return Collections.singletonList(dir.resolve("camel-knative-component"));
case "camel-yaml-dsl":
return Collections.singletonList(dir.resolve("camel-yaml-dsl"));
default:
return Collections.singletonList(dir);
}
}
public static String annotationValue(AnnotationInstance ann, String key) {
if (ann == null) {
return null;
}
var v = ann.value(key);
if (v == null) {
return null;
}
var o = v.value();
if (o == null) {
return null;
}
var s = o.toString();
return s == null || s.isBlank() ? null : s;
}
public static String annotationValue(AnnotationInstance ann, String key, String subKey) {
if (ann == null) {
return null;
}
var v = ann.value(key);
if (v == null) {
return null;
}
var o = v.value();
if (o == null) {
return null;
}
AnnotationValue[] arr = (AnnotationValue[]) o;
if (arr.length == 0) {
return null;
}
for (AnnotationValue av : arr) {
String s = av.value().toString();
String before = Strings.before(s, "=");
if (subKey.equals(before)) {
return Strings.after(s, "=");
}
}
return null;
}
/**
* Gets the JSON schema type.
*
* @param type the java type
* @return the json schema type, is never null, but returns <tt>object</tt> as the generic type
*/
public static String getType(String type, boolean enumType, boolean isDuration) {
if (enumType) {
return "enum";
} else if (isDuration) {
return "duration";
} else if (type == null) {
// return generic type for unknown type
return "object";
} else if (type.equals(URI.class.getName()) || type.equals(URL.class.getName())) {
return "string";
} else if (type.equals(File.class.getName())) {
return "string";
} else if (type.equals(Date.class.getName())) {
return "string";
} else if (type.startsWith("java.lang.Class")) {
return "string";
} else if (type.startsWith("java.util.List") || type.startsWith("java.util.Collection")) {
return "array";
} else if (type.equals(Duration.class.getName())) {
return "duration";
}
String primitive = getPrimitiveType(type);
if (primitive != null) {
return primitive;
}
return "object";
}
/**
* Gets the JSON schema primitive type.
*
* @param name the java type
* @return the json schema primitive type, or <tt>null</tt> if not a primitive
*/
public static String getPrimitiveType(String name) {
// special for byte[] or Object[] as its common to use
if ("java.lang.byte[]".equals(name) || "byte[]".equals(name)) {
return "string";
} else if ("java.lang.Byte[]".equals(name) || "Byte[]".equals(name)) {
return "array";
} else if ("java.lang.Object[]".equals(name) || "Object[]".equals(name)) {
return "array";
} else if ("java.lang.String[]".equals(name) || "String[]".equals(name)) {
return "array";
} else if ("java.lang.Character".equals(name) || "Character".equals(name) || "char".equals(name)) {
return "string";
} else if ("java.lang.String".equals(name) || "String".equals(name)) {
return "string";
} else if ("java.lang.Boolean".equals(name) || "Boolean".equals(name) || "boolean".equals(name)) {
return "boolean";
} else if ("java.lang.Integer".equals(name) || "Integer".equals(name) || "int".equals(name)) {
return "integer";
} else if ("java.lang.Long".equals(name) || "Long".equals(name) || "long".equals(name)) {
return "integer";
} else if ("java.lang.Short".equals(name) || "Short".equals(name) || "short".equals(name)) {
return "integer";
} else if ("java.lang.Byte".equals(name) || "Byte".equals(name) || "byte".equals(name)) {
return "integer";
} else if ("java.lang.Float".equals(name) || "Float".equals(name) || "float".equals(name)) {
return "number";
} else if ("java.lang.Double".equals(name) || "Double".equals(name) || "double".equals(name)) {
return "number";
}
return null;
}
}
|
MojoHelper
|
java
|
spring-projects__spring-boot
|
module/spring-boot-health/src/main/java/org/springframework/boot/health/actuate/endpoint/StatusAggregator.java
|
{
"start": 1169,
"end": 1931
}
|
interface ____ {
/**
* Return {@link StatusAggregator} instance using default ordering rules.
* @return a {@code StatusAggregator} with default ordering rules.
*/
static StatusAggregator getDefault() {
return SimpleStatusAggregator.INSTANCE;
}
/**
* Return the aggregate status for the given set of statuses.
* @param statuses the statuses to aggregate
* @return the aggregate status
*/
default Status getAggregateStatus(Status... statuses) {
return getAggregateStatus(new LinkedHashSet<>(Arrays.asList(statuses)));
}
/**
* Return the aggregate status for the given set of statuses.
* @param statuses the statuses to aggregate
* @return the aggregate status
*/
Status getAggregateStatus(Set<Status> statuses);
}
|
StatusAggregator
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/component/properties/PropertiesComponentLoadPropertiesFromFileTrimValuesTest.java
|
{
"start": 1090,
"end": 3340
}
|
class ____ extends ContextTestSupport {
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
// create space.properties file
try (Writer w = Files.newBufferedWriter(testFile("space.properties"))) {
String cool = "cool.leading= Leading space" + LS + "cool.trailing=Trailing space " + LS
+ "cool.both= Both leading and trailing space " + LS;
w.write(cool);
String space
= "space.leading= \\r\\n" + LS + "space.trailing=\\t " + LS + "space.both= \\r \\t \\n " + LS;
w.write(space);
String mixed = "mixed.leading= Leading space\\r\\n" + LS + "mixed.trailing=Trailing space\\t " + LS
+ "mixed.both= Both leading and trailing space\\r \\t \\n " + LS;
w.write(mixed);
String empty = "empty.line= ";
w.write(empty);
}
context.getPropertiesComponent().setLocation(fileUri("space.properties"));
return context;
}
@Test
public void testMustTrimValues() {
assertEquals("Leading space", context.resolvePropertyPlaceholders("{{cool.leading}}"));
assertEquals("Trailing space", context.resolvePropertyPlaceholders("{{cool.trailing}}"));
assertEquals("Both leading and trailing space", context.resolvePropertyPlaceholders("{{cool.both}}"));
assertEquals("\r\n", context.resolvePropertyPlaceholders("{{space.leading}}"));
assertEquals("\t", context.resolvePropertyPlaceholders("{{space.trailing}}"));
assertEquals("\r \t \n", context.resolvePropertyPlaceholders("{{space.both}}"));
assertEquals("Leading space\r\n", context.resolvePropertyPlaceholders("{{mixed.leading}}"));
assertEquals("Trailing space\t", context.resolvePropertyPlaceholders("{{mixed.trailing}}"));
assertEquals("Both leading and trailing space\r \t \n", context.resolvePropertyPlaceholders("{{mixed.both}}"));
assertEquals("", context.resolvePropertyPlaceholders("{{empty.line}}"));
}
}
|
PropertiesComponentLoadPropertiesFromFileTrimValuesTest
|
java
|
grpc__grpc-java
|
api/src/main/java/io/grpc/TlsServerCredentials.java
|
{
"start": 1427,
"end": 7891
}
|
class ____ extends ServerCredentials {
/**
* Creates an instance using provided certificate chain and private key. Generally they should be
* PEM-encoded and the key is an unencrypted PKCS#8 key (file headers have "BEGIN CERTIFICATE" and
* "BEGIN PRIVATE KEY").
*/
public static ServerCredentials create(File certChain, File privateKey) throws IOException {
return newBuilder().keyManager(certChain, privateKey).build();
}
/**
* Creates an instance using provided certificate chain and private key. Generally they should be
* PEM-encoded and the key is an unencrypted PKCS#8 key (file headers have "BEGIN CERTIFICATE" and
* "BEGIN PRIVATE KEY").
*
* <p>The streams will not be automatically closed.
*/
public static ServerCredentials create(
InputStream certChain, InputStream privateKey) throws IOException {
return newBuilder().keyManager(certChain, privateKey).build();
}
private final boolean fakeFeature;
private final byte[] certificateChain;
private final byte[] privateKey;
private final String privateKeyPassword;
private final List<KeyManager> keyManagers;
private final ClientAuth clientAuth;
private final byte[] rootCertificates;
private final List<TrustManager> trustManagers;
TlsServerCredentials(Builder builder) {
fakeFeature = builder.fakeFeature;
certificateChain = builder.certificateChain;
privateKey = builder.privateKey;
privateKeyPassword = builder.privateKeyPassword;
keyManagers = builder.keyManagers;
clientAuth = builder.clientAuth;
rootCertificates = builder.rootCertificates;
trustManagers = builder.trustManagers;
}
/**
* The certificate chain for the server's identity, as a new byte array. Generally should be
* PEM-encoded. If {@code null}, some feature is providing key manager information via a different
* method.
*/
public byte[] getCertificateChain() {
if (certificateChain == null) {
return null;
}
return Arrays.copyOf(certificateChain, certificateChain.length);
}
/**
* The private key for the server's identity, as a new byte array. Generally should be in PKCS#8
* format. If encrypted, {@link #getPrivateKeyPassword} is the decryption key. If unencrypted, the
* password will be {@code null}. If {@code null}, some feature is providing key manager
* information via a different method.
*/
public byte[] getPrivateKey() {
if (privateKey == null) {
return null;
}
return Arrays.copyOf(privateKey, privateKey.length);
}
/** Returns the password to decrypt the private key, or {@code null} if unencrypted. */
public String getPrivateKeyPassword() {
return privateKeyPassword;
}
/**
* Returns the key manager list which provides the server's identity. Entries are scanned checking
* for specific types, like {@link javax.net.ssl.X509KeyManager}. Only a single entry for a type
* is used. Entries earlier in the list are higher priority. If {@code null}, key manager
* information is provided via a different method.
*/
public List<KeyManager> getKeyManagers() {
return keyManagers;
}
/** Non-{@code null} setting indicating whether the server should expect a client's identity. */
public ClientAuth getClientAuth() {
return clientAuth;
}
/**
* Root trust certificates for verifying the client's identity that override the system's
* defaults. Generally PEM-encoded with multiple certificates concatenated.
*/
public byte[] getRootCertificates() {
if (rootCertificates == null) {
return null;
}
return Arrays.copyOf(rootCertificates, rootCertificates.length);
}
/**
* Returns the trust manager list which verifies the client's identity. Entries are scanned
* checking for specific types, like {@link javax.net.ssl.X509TrustManager}. Only a single entry
* for a type is used. Entries earlier in the list are higher priority. If {@code null}, trust
* manager information is provided via the system's default or a different method.
*/
public List<TrustManager> getTrustManagers() {
return trustManagers;
}
/**
* Returns an empty set if this credential can be adequately understood via
* the features listed, otherwise returns a hint of features that are lacking
* to understand the configuration to be used for manual debugging.
*
* <p>An "understood" feature does not imply the caller is able to fully
* handle the feature. It simply means the caller understands the feature
* enough to use the appropriate APIs to read the configuration. The caller
* may support just a subset of a feature, in which case the caller would
* need to look at the configuration to determine if only the supported
* subset is used.
*
* <p>This method may not be as simple as a set difference. There may be
* multiple features that can independently satisfy a piece of configuration.
* If the configuration is incomprehensible, all such features would be
* returned, even though only one may be necessary.
*
* <p>An empty set does not imply that the credentials are fully understood.
* There may be optional configuration that can be ignored if not understood.
*
* <p>Since {@code Feature} is an {@code enum}, {@code understoodFeatures}
* should generally be an {@link java.util.EnumSet}. {@code
* understoodFeatures} will not be modified.
*
* @param understoodFeatures the features understood by the caller
* @return empty set if the caller can adequately understand the configuration
*/
public Set<Feature> incomprehensible(Set<Feature> understoodFeatures) {
Set<Feature> incomprehensible = EnumSet.noneOf(Feature.class);
if (fakeFeature) {
requiredFeature(understoodFeatures, incomprehensible, Feature.FAKE);
}
if (clientAuth != ClientAuth.NONE) {
requiredFeature(understoodFeatures, incomprehensible, Feature.MTLS);
}
if (keyManagers != null || trustManagers != null) {
requiredFeature(understoodFeatures, incomprehensible, Feature.CUSTOM_MANAGERS);
}
return Collections.unmodifiableSet(incomprehensible);
}
private static void requiredFeature(
Set<Feature> understoodFeatures, Set<Feature> incomprehensible, Feature feature) {
if (!understoodFeatures.contains(feature)) {
incomprehensible.add(feature);
}
}
/**
* Features to understand TLS configuration. Additional
|
TlsServerCredentials
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
|
{
"start": 262529,
"end": 263086
}
|
class ____ {
final Blackboard bb;
final String originalRelName;
DeferredLookup(Blackboard bb, String originalRelName) {
this.bb = bb;
this.originalRelName = originalRelName;
}
RexFieldAccess getFieldAccess(CorrelationId name) {
return requireNonNull(
bb.mapCorrelateToRex.get(name), () -> "Correlation " + name + " is not found");
}
}
/** A default implementation of SubQueryConverter that does no conversion. */
private static
|
DeferredLookup
|
java
|
apache__maven
|
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4590ImportedPomUsesSystemAndUserPropertiesTest.java
|
{
"start": 1131,
"end": 2644
}
|
class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify that imported POMs are processed using the same system/user properties as the importing POM.
*
* @throws Exception in case of failure
*/
@Test
public void testit() throws Exception {
File testDir = extractResources("/mng-4590");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.deleteArtifacts("org.apache.maven.its.mng4590");
verifier.filterFile("settings-template.xml", "settings.xml");
verifier.setEnvironmentVariable("MAVEN_OPTS", "-Dtest.file=pom.xml");
verifier.addCliArgument("-Dtest.dir=" + testDir.getAbsolutePath());
verifier.addCliArgument("--settings");
verifier.addCliArgument("settings.xml");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
Properties props = verifier.loadProperties("target/pom.properties");
assertEquals("1", props.getProperty("project.dependencyManagement.dependencies"));
assertEquals("dep-a", props.getProperty("project.dependencyManagement.dependencies.0.artifactId"));
assertEquals(
new File(testDir, "pom.xml").getAbsoluteFile(),
new File(props.getProperty("project.dependencyManagement.dependencies.0.systemPath")));
}
}
|
MavenITmng4590ImportedPomUsesSystemAndUserPropertiesTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/metamodel/internal/EntityInstantiatorPojoOptimized.java
|
{
"start": 507,
"end": 1057
}
|
class ____ extends AbstractEntityInstantiatorPojo {
private final InstantiationOptimizer instantiationOptimizer;
public EntityInstantiatorPojoOptimized(
EntityPersister persister,
PersistentClass persistentClass,
JavaType<?> javaType,
InstantiationOptimizer instantiationOptimizer) {
super( persister, persistentClass, javaType );
this.instantiationOptimizer = instantiationOptimizer;
}
@Override
public Object instantiate() {
return applyInterception( instantiationOptimizer.newInstance() );
}
}
|
EntityInstantiatorPojoOptimized
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/deser/creators/TestCreators2.java
|
{
"start": 4499,
"end": 5311
}
|
class ____ {
private final int intField;
private final String stringField;
public MultiPropCreator1476(@JsonProperty("intField") int intField) {
this(intField, "empty");
}
public MultiPropCreator1476(@JsonProperty("stringField") String stringField) {
this(-1, stringField);
}
@JsonCreator
public MultiPropCreator1476(@JsonProperty("intField") int intField,
@JsonProperty("stringField") String stringField) {
this.intField = intField;
this.stringField = stringField;
}
public int getIntField() {
return intField;
}
public String getStringField() {
return stringField;
}
}
// [databind#4515]
static
|
MultiPropCreator1476
|
java
|
processing__processing4
|
java/test/processing/mode/java/preproc/MissingMethodNameMessageSimplifierStrategyTest.java
|
{
"start": 272,
"end": 1301
}
|
class ____ {
private PreprocessIssueMessageSimplifier.PreprocIssueMessageSimplifierStrategy strategy;
@Before
public void setup() {
strategy = PreprocessIssueMessageSimplifier.get().createMethodMissingNameStrategy();
}
@Test
public void testPresent() {
Optional<PdeIssueEmitter.IssueMessageSimplification> msg = strategy.simplify("void (int x) \n{");
Assert.assertTrue(msg.isPresent());
}
@Test
public void testPresentNoSpace() {
Optional<PdeIssueEmitter.IssueMessageSimplification> msg = strategy.simplify("test(int x) \n{");
Assert.assertTrue(msg.isPresent());
}
@Test
public void testPresentUnderscore() {
Optional<PdeIssueEmitter.IssueMessageSimplification> msg = strategy.simplify("void (int x_y) \n{");
Assert.assertTrue(msg.isPresent());
}
@Test
public void testNotPresent() {
Optional<PdeIssueEmitter.IssueMessageSimplification> msg = strategy.simplify("int x = y");
Assert.assertTrue(msg.isEmpty());
}
}
|
MissingMethodNameMessageSimplifierStrategyTest
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/index/mapper/IpFieldScriptTests.java
|
{
"start": 1358,
"end": 4916
}
|
class ____ extends FieldScriptTestCase<IpFieldScript.Factory> {
public static final IpFieldScript.Factory DUMMY = (fieldName, params, lookup, onScriptError) -> ctx -> new IpFieldScript(
fieldName,
params,
lookup,
OnScriptError.FAIL,
ctx
) {
@Override
public void execute() {
emit("192.168.0.1");
}
};
@Override
protected ScriptContext<IpFieldScript.Factory> context() {
return IpFieldScript.CONTEXT;
}
@Override
protected IpFieldScript.Factory dummyScript() {
return DUMMY;
}
@Override
protected IpFieldScript.Factory fromSource() {
return IpFieldScript.PARSE_FROM_SOURCE;
}
public void testTooManyValues() throws IOException {
try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) {
iw.addDocument(List.of(new StoredField("_source", new BytesRef("{}"))));
try (DirectoryReader reader = iw.getReader()) {
IpFieldScript script = new IpFieldScript(
"test",
Map.of(),
new SearchLookup(field -> null, (ft, lookup, fdt) -> null, (ctx, doc) -> null),
OnScriptError.FAIL,
reader.leaves().get(0)
) {
@Override
public void execute() {
for (int i = 0; i <= AbstractFieldScript.MAX_VALUES; i++) {
new Emit(this).emit("192.168.0.1");
}
}
};
Exception e = expectThrows(IllegalArgumentException.class, script::execute);
assertThat(
e.getMessage(),
equalTo("Runtime field [test] is emitting [101] values while the maximum number of values allowed is [100]")
);
}
}
}
public final void testFromSourceDoesNotEnforceValuesLimit() throws IOException {
try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) {
int numValues = AbstractFieldScript.MAX_VALUES + randomIntBetween(1, 100);
XContentBuilder builder = JsonXContent.contentBuilder();
builder.startObject();
builder.startArray("field");
for (int i = 0; i < numValues; i++) {
builder.value("192.168.0." + i);
}
builder.endArray();
builder.endObject();
iw.addDocument(List.of(new StoredField("_source", new BytesRef(Strings.toString(builder)))));
try (DirectoryReader reader = iw.getReader()) {
IpFieldScript.LeafFactory leafFactory = fromSource().newFactory(
"field",
Collections.emptyMap(),
new SearchLookup(
field -> null,
(ft, lookup, fdt) -> null,
SourceProvider.fromLookup(MappingLookup.EMPTY, null, SourceFieldMetrics.NOOP)
),
OnScriptError.FAIL
);
IpFieldScript ipFieldScript = leafFactory.newInstance(reader.leaves().get(0));
List<InetAddress> results = new ArrayList<>();
ipFieldScript.runForDoc(0, results::add);
assertEquals(numValues, results.size());
}
}
}
}
|
IpFieldScriptTests
|
java
|
apache__flink
|
flink-table/flink-table-common/src/test/java/org/apache/flink/table/data/columnar/vector/VectorizedColumnBatchTest.java
|
{
"start": 2011,
"end": 12268
}
|
class ____ {
private static final int VECTOR_SIZE = 1024;
private static final int ARRAY_SIZE = 3;
@Test
void testTyped() throws IOException {
HeapBooleanVector col0 = new HeapBooleanVector(VECTOR_SIZE);
for (int i = 0; i < VECTOR_SIZE; i++) {
col0.vector[i] = i % 2 == 0;
}
HeapBytesVector col1 = new HeapBytesVector(VECTOR_SIZE);
for (int i = 0; i < VECTOR_SIZE; i++) {
byte[] bytes = String.valueOf(i).getBytes(StandardCharsets.UTF_8);
col1.appendBytes(i, bytes, 0, bytes.length);
}
HeapByteVector col2 = new HeapByteVector(VECTOR_SIZE);
for (int i = 0; i < VECTOR_SIZE; i++) {
col2.vector[i] = (byte) i;
}
HeapDoubleVector col3 = new HeapDoubleVector(VECTOR_SIZE);
for (int i = 0; i < VECTOR_SIZE; i++) {
col3.vector[i] = i;
}
HeapFloatVector col4 = new HeapFloatVector(VECTOR_SIZE);
for (int i = 0; i < VECTOR_SIZE; i++) {
col4.vector[i] = i;
}
HeapIntVector col5 = new HeapIntVector(VECTOR_SIZE);
for (int i = 0; i < VECTOR_SIZE; i++) {
col5.vector[i] = i;
}
HeapLongVector col6 = new HeapLongVector(VECTOR_SIZE);
for (int i = 0; i < VECTOR_SIZE; i++) {
col6.vector[i] = i;
}
HeapShortVector col7 = new HeapShortVector(VECTOR_SIZE);
for (int i = 0; i < VECTOR_SIZE; i++) {
col7.vector[i] = (short) i;
}
// The precision of Timestamp in parquet should be one of MILLIS, MICROS or NANOS.
// https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#timestamp
//
// For MILLIS, the underlying INT64 holds milliseconds
// For MICROS, the underlying INT64 holds microseconds
// For NANOS, the underlying INT96 holds nanoOfDay(8 bytes) and julianDay(4 bytes)
long[] vector8 = new long[VECTOR_SIZE];
for (int i = 0; i < VECTOR_SIZE; i++) {
vector8[i] = i;
}
TimestampColumnVector col8 =
new TimestampColumnVector() {
@Override
public boolean isNullAt(int i) {
return false;
}
@Override
public TimestampData getTimestamp(int i, int precision) {
return TimestampData.fromEpochMillis(vector8[i]);
}
};
long[] vector9 = new long[VECTOR_SIZE];
for (int i = 0; i < VECTOR_SIZE; i++) {
vector9[i] = i * 1000;
}
TimestampColumnVector col9 =
new TimestampColumnVector() {
@Override
public TimestampData getTimestamp(int i, int precision) {
long microseconds = vector9[i];
return TimestampData.fromEpochMillis(
microseconds / 1000, (int) (microseconds % 1000) * 1000);
}
@Override
public boolean isNullAt(int i) {
return false;
}
};
HeapBytesVector vector10 = new HeapBytesVector(VECTOR_SIZE);
{
int nanosecond = 123456789;
int start = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int i = 0; i < VECTOR_SIZE; i++) {
byte[] bytes = new byte[12];
long l = i * 1000000000L + nanosecond; // i means second
for (int j = 0; j < 8; j++) {
bytes[7 - j] = (byte) l;
l >>>= 8;
}
int n = 2440588; // Epoch Julian
for (int j = 0; j < 4; j++) {
bytes[11 - j] = (byte) n;
n >>>= 8;
}
vector10.start[i] = start;
vector10.length[i] = 12;
start += 12;
out.write(bytes);
}
vector10.buffer = out.toByteArray();
}
TimestampColumnVector col10 =
new TimestampColumnVector() {
@Override
public TimestampData getTimestamp(int colId, int precision) {
byte[] bytes = vector10.getBytes(colId).getBytes();
assertThat(bytes).hasSize(12);
long nanoOfDay = 0;
for (int i = 0; i < 8; i++) {
nanoOfDay <<= 8;
nanoOfDay |= (bytes[i] & (0xff));
}
int julianDay = 0;
for (int i = 8; i < 12; i++) {
julianDay <<= 8;
julianDay |= (bytes[i] & (0xff));
}
long millisecond =
(julianDay - DateTimeUtils.EPOCH_JULIAN)
* DateTimeUtils.MILLIS_PER_DAY
+ nanoOfDay / 1000000;
int nanoOfMillisecond = (int) (nanoOfDay % 1000000);
return TimestampData.fromEpochMillis(millisecond, nanoOfMillisecond);
}
@Override
public boolean isNullAt(int i) {
return false;
}
};
long[] vector11 = new long[VECTOR_SIZE];
DecimalColumnVector col11 =
new DecimalColumnVector() {
@Override
public boolean isNullAt(int i) {
return false;
}
@Override
public DecimalData getDecimal(int i, int precision, int scale) {
return DecimalData.fromUnscaledLong(vector11[i], precision, scale);
}
};
for (int i = 0; i < VECTOR_SIZE; i++) {
vector11[i] = i;
}
HeapIntVector col12Data = new HeapIntVector(VECTOR_SIZE * ARRAY_SIZE);
for (int i = 0; i < VECTOR_SIZE * ARRAY_SIZE; i++) {
col12Data.vector[i] = i;
}
ArrayColumnVector col12 =
new ArrayColumnVector() {
@Override
public boolean isNullAt(int i) {
return false;
}
@Override
public ArrayData getArray(int i) {
return new ColumnarArrayData(col12Data, i * ARRAY_SIZE, ARRAY_SIZE);
}
};
VectorizedColumnBatch batch =
new VectorizedColumnBatch(
new ColumnVector[] {
col0, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10,
col11, col12
});
batch.setNumRows(VECTOR_SIZE);
for (int i = 0; i < batch.getNumRows(); i++) {
ColumnarRowData row = new ColumnarRowData(batch, i);
assertThat(row.getBoolean(0)).isEqualTo(i % 2 == 0);
assertThat(row.getString(1).toString()).isEqualTo(String.valueOf(i));
assertThat(row.getByte(2)).isEqualTo((byte) i);
assertThat(row.getDouble(3)).isEqualTo(i);
assertThat((float) i).isEqualTo(row.getFloat(4));
assertThat(row.getInt(5)).isEqualTo(i);
assertThat(row.getLong(6)).isEqualTo(i);
assertThat(row.getShort(7)).isEqualTo((short) i);
assertThat(row.getTimestamp(8, 3).getMillisecond()).isEqualTo(i);
assertThat(row.getTimestamp(9, 6).getMillisecond()).isEqualTo(i);
assertThat(row.getTimestamp(10, 9).getMillisecond()).isEqualTo(i * 1000L + 123);
assertThat(row.getTimestamp(10, 9).getNanoOfMillisecond()).isEqualTo(456789);
assertThat(row.getDecimal(11, 10, 0).toUnscaledLong()).isEqualTo(i);
for (int j = 0; j < ARRAY_SIZE; j++) {
assertThat(row.getArray(12).getInt(j)).isEqualTo(i * ARRAY_SIZE + j);
}
}
assertThat(batch.getNumRows()).isEqualTo(VECTOR_SIZE);
}
@Test
void testNull() {
// all null
HeapIntVector col0 = new HeapIntVector(VECTOR_SIZE);
for (int i = 0; i < VECTOR_SIZE; i++) {
col0.setNullAt(i);
}
// some null
HeapIntVector col1 = new HeapIntVector(VECTOR_SIZE);
for (int i = 0; i < VECTOR_SIZE; i++) {
if (i % 2 == 0) {
col1.setNullAt(i);
} else {
col1.vector[i] = i;
}
}
VectorizedColumnBatch batch = new VectorizedColumnBatch(new ColumnVector[] {col0, col1});
for (int i = 0; i < VECTOR_SIZE; i++) {
ColumnarRowData row = new ColumnarRowData(batch, i);
assertThat(row.isNullAt(0)).isTrue();
if (i % 2 == 0) {
assertThat(row.isNullAt(1)).isTrue();
} else {
assertThat(i).isEqualTo(row.getInt(1));
}
}
}
@Test
void testDictionary() {
// all null
HeapIntVector col = new HeapIntVector(VECTOR_SIZE);
Integer[] dict = new Integer[2];
dict[0] = 1998;
dict[1] = 9998;
col.setDictionary(new ColumnVectorTest.TestDictionary(dict));
HeapIntVector heapIntVector = col.reserveDictionaryIds(VECTOR_SIZE);
for (int i = 0; i < VECTOR_SIZE; i++) {
heapIntVector.vector[i] = i % 2 == 0 ? 0 : 1;
}
VectorizedColumnBatch batch = new VectorizedColumnBatch(new ColumnVector[] {col});
for (int i = 0; i < VECTOR_SIZE; i++) {
ColumnarRowData row = new ColumnarRowData(batch, i);
if (i % 2 == 0) {
assertThat(1998).isEqualTo(row.getInt(0));
} else {
assertThat(9998).isEqualTo(row.getInt(0));
}
}
}
}
|
VectorizedColumnBatchTest
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/core/annotation/MergedAnnotation.java
|
{
"start": 13162,
"end": 13274
}
|
enum ____ attribute value from the annotation.
* @param attributeName the attribute name
* @param type the
|
array
|
java
|
spring-projects__spring-framework
|
spring-web/src/main/java/org/springframework/http/ReactiveHttpOutputMessage.java
|
{
"start": 1167,
"end": 3135
}
|
interface ____ extends HttpMessage {
/**
* Return a {@link DataBufferFactory} that can be used to create the body.
* @return a buffer factory
* @see #writeWith(Publisher)
*/
DataBufferFactory bufferFactory();
/**
* Register an action to apply just before the HttpOutputMessage is committed.
* <p><strong>Note:</strong> the supplied action must be properly deferred,
* for example, via {@link Mono#defer} or {@link Mono#fromRunnable}, to ensure it's
* executed in the right order, relative to other actions.
* @param action the action to apply
*/
void beforeCommit(Supplier<? extends Mono<Void>> action);
/**
* Whether the HttpOutputMessage is committed.
*/
boolean isCommitted();
/**
* Use the given {@link Publisher} to write the body of the message to the
* underlying HTTP layer.
* @param body the body content publisher
* @return a {@link Mono} that indicates completion or error
*/
Mono<Void> writeWith(Publisher<? extends DataBuffer> body);
/**
* Use the given {@link Publisher} of {@code Publishers} to write the body
* of the HttpOutputMessage to the underlying HTTP layer, flushing after
* each {@code Publisher<DataBuffer>}.
* @param body the body content publisher
* @return a {@link Mono} that indicates completion or error
*/
Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body);
/**
* Indicate that message handling is complete, allowing for any cleanup or
* end-of-processing tasks to be performed such as applying header changes
* made via {@link #getHeaders()} to the underlying HTTP message (if not
* applied already).
* <p>This method should be automatically invoked at the end of message
* processing so typically applications should not have to invoke it.
* If invoked multiple times it should have no side effects.
* @return a {@link Mono} that indicates completion or error
*/
Mono<Void> setComplete();
}
|
ReactiveHttpOutputMessage
|
java
|
elastic__elasticsearch
|
test/framework/src/main/java/org/elasticsearch/transport/AbstractSimpleTransportTestCase.java
|
{
"start": 92375,
"end": 139831
}
|
class ____ implements TransportResponseHandler<TestResponse> {
private final int id;
private final Executor executor = randomExecutor(threadPool);
TestResponseHandler(int id) {
this.id = id;
}
@Override
public TestResponse read(StreamInput in) throws IOException {
return new TestResponse(in);
}
@Override
public void handleResponse(TestResponse response) {
logger.debug("---> received response: {}", response.info);
allRequestsDone.countDown();
}
@Override
public void handleException(TransportException exp) {
logger.debug((Supplier<?>) () -> "---> received exception for id " + id, exp);
allRequestsDone.countDown();
Throwable unwrap = ExceptionsHelper.unwrap(exp, IOException.class);
assertNotNull(unwrap);
assertEquals(IOException.class, unwrap.getClass());
assertEquals("forced failure", unwrap.getMessage());
}
@Override
public Executor executor() {
return executor;
}
}
for (int i = 0; i < iters; i++) {
TransportService service = randomFrom(serviceC, serviceB, serviceA);
DiscoveryNode node = randomFrom(nodeC, nodeB, nodeA);
logger.debug("send from {} to {}", toNodeMap.get(service), node);
service.sendRequest(
node,
"internal:action1",
new TestRequest("REQ[" + i + "]"),
TransportRequestOptions.EMPTY,
new TestResponseHandler(i)
);
}
logger.debug("waiting for response");
fail.set(randomBoolean());
boolean await = allRequestsDone.await(5, TimeUnit.SECONDS);
if (await == false) {
logger.debug("now failing forcefully");
fail.set(true);
assertTrue(allRequestsDone.await(5, TimeUnit.SECONDS));
}
logger.debug("DONE");
serviceC.close();
// when we close C here we have to disconnect the service otherwise assertions mit trip with pending connections in tearDown
// since the disconnect will then happen concurrently and that might confuse the assertions since we disconnect due to a
// connection reset by peer or other exceptions depending on the implementation
serviceB.disconnectFromNode(nodeC);
serviceA.disconnectFromNode(nodeC);
}
public void testRegisterHandlerTwice() {
serviceB.registerRequestHandler("internal:action1", randomExecutor(threadPool), TestRequest::new, (request, message, task) -> {
throw new AssertionError("boom");
});
expectThrows(
IllegalArgumentException.class,
() -> serviceB.registerRequestHandler(
"internal:action1",
randomExecutor(threadPool),
TestRequest::new,
(request, message, task) -> {
throw new AssertionError("boom");
}
)
);
serviceA.registerRequestHandler("internal:action1", randomExecutor(threadPool), TestRequest::new, (request, message, task) -> {
throw new AssertionError("boom");
});
}
public void testHandshakeWithIncompatVersion() {
assumeTrue("only tcp transport has a handshake method", serviceA.getOriginalTransport() instanceof TcpTransport);
TransportVersion transportVersion = TransportVersion.fromId(TransportVersion.minimumCompatible().id() - 1);
try (
MockTransportService service = buildService(
"TS_C",
new VersionInformation(
Version.CURRENT.minimumCompatibilityVersion(),
IndexVersions.MINIMUM_COMPATIBLE,
IndexVersion.current()
),
transportVersion,
Settings.EMPTY
)
) {
TransportAddress address = service.boundAddress().publishAddress();
DiscoveryNode node = DiscoveryNodeUtils.builder("TS_TPC")
.name("TS_TPC")
.address(address)
.roles(emptySet())
.version(version0)
.build();
ConnectionProfile.Builder builder = new ConnectionProfile.Builder();
builder.addConnections(
1,
TransportRequestOptions.Type.BULK,
TransportRequestOptions.Type.PING,
TransportRequestOptions.Type.RECOVERY,
TransportRequestOptions.Type.REG,
TransportRequestOptions.Type.STATE
);
assertNotNull(openConnectionExpectFailure(serviceA, node, builder.build()));
}
}
public void testHandshakeUpdatesVersion() throws IOException {
assumeTrue("only tcp transport has a handshake method", serviceA.getOriginalTransport() instanceof TcpTransport);
TransportVersion transportVersion = TransportVersionUtils.randomVersionBetween(
random(),
TransportVersion.minimumCompatible(),
TransportVersion.current()
);
try (
MockTransportService service = buildService(
"TS_C",
new VersionInformation(
Version.CURRENT.minimumCompatibilityVersion(),
IndexVersions.MINIMUM_COMPATIBLE,
IndexVersion.current()
),
transportVersion,
Settings.EMPTY
)
) {
TransportAddress address = service.boundAddress().publishAddress();
DiscoveryNode node = DiscoveryNodeUtils.builder("TS_TPC")
.name("TS_TPC")
.address(address)
.roles(emptySet())
.version(VersionInformation.inferVersions(Version.fromString("2.0.0")))
.build();
ConnectionProfile.Builder builder = new ConnectionProfile.Builder();
builder.addConnections(
1,
TransportRequestOptions.Type.BULK,
TransportRequestOptions.Type.PING,
TransportRequestOptions.Type.RECOVERY,
TransportRequestOptions.Type.REG,
TransportRequestOptions.Type.STATE
);
try (Transport.Connection connection = openConnection(serviceA, node, builder.build())) {
assertEquals(transportVersion, connection.getTransportVersion());
}
}
}
public void testKeepAlivePings() throws Exception {
assumeTrue("only tcp transport has keep alive pings", serviceA.getOriginalTransport() instanceof TcpTransport);
TcpTransport originalTransport = (TcpTransport) serviceA.getOriginalTransport();
ConnectionProfile defaultProfile = ConnectionProfile.buildDefaultConnectionProfile(Settings.EMPTY);
ConnectionProfile connectionProfile = new ConnectionProfile.Builder(defaultProfile).setPingInterval(TimeValue.timeValueMillis(50))
.build();
try (TransportService service = buildService("TS_TPC", VersionInformation.CURRENT, TransportVersion.current(), Settings.EMPTY)) {
PlainActionFuture<Transport.Connection> future = new PlainActionFuture<>();
DiscoveryNode node = DiscoveryNodeUtils.builder("TS_TPC")
.name("TS_TPC")
.address(service.boundAddress().publishAddress())
.attributes(emptyMap())
.roles(emptySet())
.version(version0)
.build();
originalTransport.openConnection(node, connectionProfile, future);
try (Transport.Connection connection = future.actionGet()) {
assertBusy(() -> { assertTrue(originalTransport.getKeepAlive().successfulPingCount() > 30); });
assertEquals(0, originalTransport.getKeepAlive().failedPingCount());
}
}
}
public void testTcpHandshake() {
assumeTrue("only tcp transport has a handshake method", serviceA.getOriginalTransport() instanceof TcpTransport);
ConnectionProfile connectionProfile = ConnectionProfile.buildDefaultConnectionProfile(Settings.EMPTY);
try (TransportService service = buildService("TS_TPC", VersionInformation.CURRENT, TransportVersion.current(), Settings.EMPTY)) {
DiscoveryNode node = DiscoveryNodeUtils.builder("TS_TPC")
.name("TS_TPC")
.address(service.boundAddress().publishAddress())
.roles(emptySet())
.version(version0)
.build();
PlainActionFuture<Transport.Connection> future = new PlainActionFuture<>();
serviceA.getOriginalTransport().openConnection(node, connectionProfile, future);
try (Transport.Connection connection = future.actionGet()) {
assertEquals(TransportVersion.current(), connection.getTransportVersion());
}
}
}
public void testTcpHandshakeTimeout() throws IOException {
try (ServerSocket socket = new MockServerSocket()) {
socket.bind(getLocalEphemeral(), 1);
socket.setReuseAddress(true);
DiscoveryNode dummy = DiscoveryNodeUtils.builder("TEST")
.address(new TransportAddress(socket.getInetAddress(), socket.getLocalPort()))
.roles(emptySet())
.version(version0)
.build();
ConnectionProfile.Builder builder = new ConnectionProfile.Builder();
builder.addConnections(
1,
TransportRequestOptions.Type.BULK,
TransportRequestOptions.Type.PING,
TransportRequestOptions.Type.RECOVERY,
TransportRequestOptions.Type.REG,
TransportRequestOptions.Type.STATE
);
builder.setHandshakeTimeout(TimeValue.timeValueMillis(1));
ConnectTransportException ex = connectToNodeExpectFailure(serviceA, dummy, builder.build());
assertEquals("[][" + dummy.getAddress() + "] handshake_timeout[1ms]", ex.getMessage());
}
}
public void testTcpHandshakeConnectionReset() throws IOException, InterruptedException {
try (ServerSocket socket = new MockServerSocket()) {
socket.bind(getLocalEphemeral(), 1);
socket.setReuseAddress(true);
DiscoveryNode dummy = DiscoveryNodeUtils.builder("TEST")
.address(new TransportAddress(socket.getInetAddress(), socket.getLocalPort()))
.roles(emptySet())
.version(version0)
.build();
Thread t = new Thread() {
@Override
public void run() {
try (Socket accept = socket.accept()) {
if (randomBoolean()) { // sometimes wait until the other side sends the message
accept.getInputStream().read();
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
};
t.start();
ConnectionProfile.Builder builder = new ConnectionProfile.Builder();
builder.addConnections(
1,
TransportRequestOptions.Type.BULK,
TransportRequestOptions.Type.PING,
TransportRequestOptions.Type.RECOVERY,
TransportRequestOptions.Type.REG,
TransportRequestOptions.Type.STATE
);
builder.setHandshakeTimeout(TimeValue.timeValueHours(1));
ConnectTransportException ex = connectToNodeExpectFailure(serviceA, dummy, builder.build());
assertEquals("[][" + dummy.getAddress() + "] general node connection failure", ex.getMessage());
assertThat(ex.getCause().getMessage(), startsWith("handshake failed"));
t.join();
}
}
public void testResponseHeadersArePreserved() throws InterruptedException {
List<String> executors = new ArrayList<>(ThreadPool.THREAD_POOL_TYPES.keySet());
CollectionUtil.timSort(executors); // makes sure it's reproducible
serviceA.registerRequestHandler(
"internal:action",
EsExecutors.DIRECT_EXECUTOR_SERVICE,
TestRequest::new,
(request, channel, task) -> {
threadPool.getThreadContext().putTransient("boom", new Object());
threadPool.getThreadContext().addResponseHeader("foo.bar", "baz");
if ("fail".equals(request.info)) {
throw new RuntimeException("boom");
} else {
channel.sendResponse(ActionResponse.Empty.INSTANCE);
}
}
);
CountDownLatch latch = new CountDownLatch(2);
TransportResponseHandler<TransportResponse> transportResponseHandler = new TransportResponseHandler<TransportResponse>() {
private final String executor = randomFrom(executors);
@Override
public TransportResponse read(StreamInput in) {
return ActionResponse.Empty.INSTANCE;
}
@Override
public void handleResponse(TransportResponse response) {
try {
assertSame(response, ActionResponse.Empty.INSTANCE);
assertTrue(threadPool.getThreadContext().getResponseHeaders().containsKey("foo.bar"));
assertEquals(1, threadPool.getThreadContext().getResponseHeaders().get("foo.bar").size());
assertEquals("baz", threadPool.getThreadContext().getResponseHeaders().get("foo.bar").get(0));
assertNull(threadPool.getThreadContext().getTransient("boom"));
} finally {
latch.countDown();
}
}
@Override
public void handleException(TransportException exp) {
try {
assertTrue(threadPool.getThreadContext().getResponseHeaders().containsKey("foo.bar"));
assertEquals(1, threadPool.getThreadContext().getResponseHeaders().get("foo.bar").size());
assertEquals("baz", threadPool.getThreadContext().getResponseHeaders().get("foo.bar").get(0));
assertNull(threadPool.getThreadContext().getTransient("boom"));
} finally {
latch.countDown();
}
}
@Override
public Executor executor() {
return threadPool.executor(executor);
}
};
serviceB.sendRequest(nodeA, "internal:action", new TestRequest(randomFrom("fail", "pass")), transportResponseHandler);
serviceA.sendRequest(nodeA, "internal:action", new TestRequest(randomFrom("fail", "pass")), transportResponseHandler);
latch.await();
}
public void testHandlerIsInvokedOnConnectionClose() throws IOException, InterruptedException {
List<String> executors = new ArrayList<>(ThreadPool.THREAD_POOL_TYPES.keySet());
CollectionUtil.timSort(executors); // makes sure it's reproducible
TransportService serviceC = buildService("TS_C", version0, transportVersion0, Settings.EMPTY);
serviceC.registerRequestHandler(
"internal:action",
EsExecutors.DIRECT_EXECUTOR_SERVICE,
TestRequest::new,
(request, channel, task) -> {
// do nothing
}
);
CountDownLatch latch = new CountDownLatch(1);
TransportResponseHandler<TransportResponse> transportResponseHandler = new TransportResponseHandler<TransportResponse>() {
@Override
public TransportResponse read(StreamInput in) {
return ActionResponse.Empty.INSTANCE;
}
@Override
public void handleResponse(TransportResponse response) {
try {
fail("no response expected");
} finally {
latch.countDown();
}
}
@Override
public void handleException(TransportException exp) {
try {
if (exp instanceof SendRequestTransportException) {
assertTrue(exp.getCause().getClass().toString(), exp.getCause() instanceof NodeNotConnectedException);
} else {
// here the concurrent disconnect was faster and invoked the listener first
assertTrue(exp.getClass().toString(), exp instanceof NodeDisconnectedException);
}
} finally {
latch.countDown();
}
}
@Override
public Executor executor() {
return threadPool.executor(randomFrom(executors));
}
};
ConnectionProfile.Builder builder = new ConnectionProfile.Builder();
builder.addConnections(
1,
TransportRequestOptions.Type.BULK,
TransportRequestOptions.Type.PING,
TransportRequestOptions.Type.RECOVERY,
TransportRequestOptions.Type.REG,
TransportRequestOptions.Type.STATE
);
try (Transport.Connection connection = openConnection(serviceB, serviceC.getLocalNode(), builder.build())) {
serviceC.close();
serviceB.sendRequest(
connection,
"internal:action",
new TestRequest("boom"),
TransportRequestOptions.EMPTY,
transportResponseHandler
);
}
latch.await();
}
public void testConcurrentDisconnectOnNonPublishedConnection() throws IOException, InterruptedException {
MockTransportService serviceC = buildService("TS_C", version0, transportVersion0, Settings.EMPTY);
CountDownLatch receivedLatch = new CountDownLatch(1);
CountDownLatch sendResponseLatch = new CountDownLatch(1);
serviceC.registerRequestHandler(
"internal:action",
EsExecutors.DIRECT_EXECUTOR_SERVICE,
TestRequest::new,
(request, channel, task) -> {
// don't block on a network thread here
threadPool.generic().execute(new AbstractRunnable() {
@Override
public void onFailure(Exception e) {
channel.sendResponse(e);
}
@Override
protected void doRun() throws Exception {
receivedLatch.countDown();
sendResponseLatch.await();
channel.sendResponse(ActionResponse.Empty.INSTANCE);
}
});
}
);
CountDownLatch responseLatch = new CountDownLatch(1);
TransportResponseHandler<ActionResponse.Empty> transportResponseHandler = new TransportResponseHandler.Empty() {
@Override
public Executor executor() {
return TransportResponseHandler.TRANSPORT_WORKER;
}
@Override
public void handleResponse() {
responseLatch.countDown();
}
@Override
public void handleException(TransportException exp) {
responseLatch.countDown();
}
};
ConnectionProfile.Builder builder = new ConnectionProfile.Builder();
builder.addConnections(
1,
TransportRequestOptions.Type.BULK,
TransportRequestOptions.Type.PING,
TransportRequestOptions.Type.RECOVERY,
TransportRequestOptions.Type.REG,
TransportRequestOptions.Type.STATE
);
try (Transport.Connection connection = openConnection(serviceB, serviceC.getLocalNode(), builder.build())) {
serviceB.sendRequest(
connection,
"internal:action",
new TestRequest("hello world"),
TransportRequestOptions.EMPTY,
transportResponseHandler
);
receivedLatch.await();
serviceC.close();
sendResponseLatch.countDown();
responseLatch.await();
}
}
public void testTransportStats() throws Exception {
MockTransportService serviceC = buildService("TS_C", version0, transportVersion0, Settings.EMPTY);
CountDownLatch receivedLatch = new CountDownLatch(1);
CountDownLatch sendResponseLatch = new CountDownLatch(1);
serviceB.registerRequestHandler(
"internal:action",
EsExecutors.DIRECT_EXECUTOR_SERVICE,
TestRequest::new,
(request, channel, task) -> {
// don't block on a network thread here
threadPool.generic().execute(new AbstractRunnable() {
@Override
public void onFailure(Exception e) {
channel.sendResponse(e);
}
@Override
protected void doRun() throws Exception {
receivedLatch.countDown();
sendResponseLatch.await();
channel.sendResponse(ActionResponse.Empty.INSTANCE);
}
});
}
);
CountDownLatch responseLatch = new CountDownLatch(1);
TransportResponseHandler<ActionResponse.Empty> transportResponseHandler = new TransportResponseHandler.Empty() {
@Override
public Executor executor() {
return TransportResponseHandler.TRANSPORT_WORKER;
}
@Override
public void handleResponse() {
responseLatch.countDown();
}
@Override
public void handleException(TransportException exp) {
responseLatch.countDown();
}
};
TransportStats stats = serviceC.transport.getStats(); // nothing transmitted / read yet
assertEquals(0, stats.getRxCount());
assertEquals(0, stats.getTxCount());
assertEquals(0, stats.getRxSize().getBytes());
assertEquals(0, stats.getTxSize().getBytes());
ConnectionProfile.Builder builder = new ConnectionProfile.Builder();
builder.addConnections(
1,
TransportRequestOptions.Type.BULK,
TransportRequestOptions.Type.PING,
TransportRequestOptions.Type.RECOVERY,
TransportRequestOptions.Type.REG,
TransportRequestOptions.Type.STATE
);
try (Transport.Connection connection = openConnection(serviceC, serviceB.getLocalNode(), builder.build())) {
assertBusy(() -> { // netty for instance invokes this concurrently so we better use assert busy here
TransportStats transportStats = serviceC.transport.getStats(); // we did a single round-trip to do the initial handshake
assertEquals(1, transportStats.getRxCount());
assertEquals(1, transportStats.getTxCount());
assertEquals(35, transportStats.getRxSize().getBytes());
assertEquals(60, transportStats.getTxSize().getBytes());
});
serviceC.sendRequest(
connection,
"internal:action",
new TestRequest("hello world"),
TransportRequestOptions.EMPTY,
transportResponseHandler
);
receivedLatch.await();
assertBusy(() -> { // netty for instance invokes this concurrently so we better use assert busy here
TransportStats transportStats = serviceC.transport.getStats(); // request has been send
assertEquals(1, transportStats.getRxCount());
assertEquals(2, transportStats.getTxCount());
assertEquals(35, transportStats.getRxSize().getBytes());
assertEquals(119, transportStats.getTxSize().getBytes());
});
sendResponseLatch.countDown();
responseLatch.await();
stats = serviceC.transport.getStats(); // response has been received
assertEquals(2, stats.getRxCount());
assertEquals(2, stats.getTxCount());
assertEquals(60, stats.getRxSize().getBytes());
assertEquals(119, stats.getTxSize().getBytes());
} finally {
serviceC.close();
}
}
public void testAcceptedChannelCount() throws Exception {
assertBusy(() -> {
TransportStats transportStats = serviceA.transport.getStats();
assertEquals(channelsPerNodeConnection(), transportStats.getServerOpen());
});
assertBusy(() -> {
TransportStats transportStats = serviceB.transport.getStats();
assertEquals(channelsPerNodeConnection(), transportStats.getServerOpen());
});
serviceA.close();
assertBusy(() -> {
TransportStats transportStats = serviceB.transport.getStats();
assertEquals(0, transportStats.getServerOpen());
});
}
public void testTransportStatsWithException() throws Exception {
MockTransportService serviceC = buildService("TS_C", version0, transportVersion0, Settings.EMPTY);
CountDownLatch receivedLatch = new CountDownLatch(1);
CountDownLatch sendResponseLatch = new CountDownLatch(1);
Exception ex = new RuntimeException("boom");
ex.setStackTrace(new StackTraceElement[0]);
serviceB.registerRequestHandler(
"internal:action",
EsExecutors.DIRECT_EXECUTOR_SERVICE,
TestRequest::new,
(request, channel, task) -> {
// don't block on a network thread here
threadPool.generic().execute(new AbstractRunnable() {
@Override
public void onFailure(Exception e) {
channel.sendResponse(e);
}
@Override
protected void doRun() throws Exception {
receivedLatch.countDown();
sendResponseLatch.await();
onFailure(ex);
}
});
}
);
CountDownLatch responseLatch = new CountDownLatch(1);
AtomicReference<TransportException> receivedException = new AtomicReference<>(null);
TransportResponseHandler<ActionResponse.Empty> transportResponseHandler = new TransportResponseHandler.Empty() {
@Override
public Executor executor() {
return TransportResponseHandler.TRANSPORT_WORKER;
}
@Override
public void handleResponse() {
responseLatch.countDown();
}
@Override
public void handleException(TransportException exp) {
receivedException.set(exp);
responseLatch.countDown();
}
};
TransportStats stats = serviceC.transport.getStats(); // nothing transmitted / read yet
assertEquals(0, stats.getRxCount());
assertEquals(0, stats.getTxCount());
assertEquals(0, stats.getRxSize().getBytes());
assertEquals(0, stats.getTxSize().getBytes());
ConnectionProfile.Builder builder = new ConnectionProfile.Builder();
builder.addConnections(
1,
TransportRequestOptions.Type.BULK,
TransportRequestOptions.Type.PING,
TransportRequestOptions.Type.RECOVERY,
TransportRequestOptions.Type.REG,
TransportRequestOptions.Type.STATE
);
try (Transport.Connection connection = openConnection(serviceC, serviceB.getLocalNode(), builder.build())) {
assertBusy(() -> { // netty for instance invokes this concurrently so we better use assert busy here
TransportStats transportStats = serviceC.transport.getStats(); // request has been sent
assertEquals(1, transportStats.getRxCount());
assertEquals(1, transportStats.getTxCount());
assertEquals(35, transportStats.getRxSize().getBytes());
assertEquals(60, transportStats.getTxSize().getBytes());
});
serviceC.sendRequest(
connection,
"internal:action",
new TestRequest("hello world"),
TransportRequestOptions.EMPTY,
transportResponseHandler
);
receivedLatch.await();
assertBusy(() -> { // netty for instance invokes this concurrently so we better use assert busy here
TransportStats transportStats = serviceC.transport.getStats(); // request has been sent
assertEquals(1, transportStats.getRxCount());
assertEquals(2, transportStats.getTxCount());
assertEquals(35, transportStats.getRxSize().getBytes());
assertEquals(119, transportStats.getTxSize().getBytes());
});
sendResponseLatch.countDown();
responseLatch.await();
stats = serviceC.transport.getStats(); // exception response has been received
assertEquals(2, stats.getRxCount());
assertEquals(2, stats.getTxCount());
TransportException exception = receivedException.get();
assertNotNull(exception);
BytesStreamOutput streamOutput = new BytesStreamOutput();
streamOutput.setTransportVersion(transportVersion0);
exception.writeTo(streamOutput);
String failedMessage = "Unexpected read bytes size. The transport exception that was received=" + exception;
// 57 bytes are the non-exception message bytes that have been received. It should include the initial
// handshake message and the header, version, etc bytes in the exception message.
assertEquals(failedMessage, 63 + streamOutput.bytes().length(), stats.getRxSize().getBytes());
assertEquals(119, stats.getTxSize().getBytes());
} finally {
serviceC.close();
}
}
public void testTransportProfilesWithPortAndHost() {
boolean doIPV6 = NetworkUtils.SUPPORTS_V6;
List<String> hosts;
if (doIPV6) {
hosts = Arrays.asList("_local:ipv6_", "_local:ipv4_");
} else {
hosts = Arrays.asList("_local:ipv4_");
}
try (
MockTransportService serviceC = buildService(
"TS_C",
version0,
transportVersion0,
Settings.builder()
.put("transport.profiles.default.bind_host", "_local:ipv4_")
.put("transport.profiles.some_profile.port", "8900-9000")
.put("transport.profiles.some_profile.bind_host", "_local:ipv4_")
.put("transport.profiles.some_other_profile.port", "8700-8800")
.putList("transport.profiles.some_other_profile.bind_host", hosts)
.putList("transport.profiles.some_other_profile.publish_host", "_local:ipv4_")
.build()
)
) {
Map<String, BoundTransportAddress> profileBoundAddresses = serviceC.transport.profileBoundAddresses();
assertTrue(profileBoundAddresses.containsKey("some_profile"));
assertTrue(profileBoundAddresses.containsKey("some_other_profile"));
assertTrue(profileBoundAddresses.get("some_profile").publishAddress().getPort() >= 8900);
assertTrue(profileBoundAddresses.get("some_profile").publishAddress().getPort() < 9000);
assertTrue(profileBoundAddresses.get("some_other_profile").publishAddress().getPort() >= 8700);
assertTrue(profileBoundAddresses.get("some_other_profile").publishAddress().getPort() < 8800);
assertTrue(profileBoundAddresses.get("some_profile").boundAddresses().length >= 1);
if (doIPV6) {
assertTrue(profileBoundAddresses.get("some_other_profile").boundAddresses().length >= 2);
int ipv4 = 0;
int ipv6 = 0;
for (TransportAddress addr : profileBoundAddresses.get("some_other_profile").boundAddresses()) {
if (addr.address().getAddress() instanceof Inet4Address) {
ipv4++;
} else if (addr.address().getAddress() instanceof Inet6Address) {
ipv6++;
} else {
fail("what kind of address is this: " + addr.address().getAddress());
}
}
assertTrue("num ipv4 is wrong: " + ipv4, ipv4 >= 1);
assertTrue("num ipv6 is wrong: " + ipv6, ipv6 >= 1);
} else {
assertTrue(profileBoundAddresses.get("some_other_profile").boundAddresses().length >= 1);
}
assertTrue(profileBoundAddresses.get("some_other_profile").publishAddress().address().getAddress() instanceof Inet4Address);
}
}
public void testProfileSettings() {
boolean enable = randomBoolean();
Settings globalSettings = Settings.builder()
.put("network.tcp.no_delay", enable)
.put("network.tcp.keep_alive", enable)
.put("network.tcp.keep_idle", "42")
.put("network.tcp.keep_interval", "7")
.put("network.tcp.keep_count", "13")
.put("network.tcp.reuse_address", enable)
.put("network.tcp.send_buffer_size", "43000b")
.put("network.tcp.receive_buffer_size", "42000b")
.put("network.publish_host", "the_publish_host")
.put("network.bind_host", "the_bind_host")
.build();
Settings globalSettings2 = Settings.builder()
.put("network.tcp.no_delay", enable == false)
.put("network.tcp.keep_alive", enable == false)
.put("network.tcp.keep_idle", "43")
.put("network.tcp.keep_interval", "8")
.put("network.tcp.keep_count", "14")
.put("network.tcp.reuse_address", enable == false)
.put("network.tcp.send_buffer_size", "4b")
.put("network.tcp.receive_buffer_size", "3b")
.put("network.publish_host", "another_publish_host")
.put("network.bind_host", "another_bind_host")
.build();
Settings transportSettings = Settings.builder()
.put("transport.tcp.no_delay", enable)
.put("transport.tcp.keep_alive", enable)
.put("transport.tcp.keep_idle", "42")
.put("transport.tcp.keep_interval", "7")
.put("transport.tcp.keep_count", "13")
.put("transport.tcp.reuse_address", enable)
.put("transport.tcp.send_buffer_size", "43000b")
.put("transport.tcp.receive_buffer_size", "42000b")
.put("transport.publish_host", "the_publish_host")
.put("transport.port", "9700-9800")
.put("transport.bind_host", "the_bind_host")
.put(globalSettings2)
.build();
Settings transportSettings2 = Settings.builder()
.put("transport.tcp.no_delay", enable == false)
.put("transport.tcp.keep_alive", enable == false)
.put("transport.tcp.keep_idle", "43")
.put("transport.tcp.keep_interval", "8")
.put("transport.tcp.keep_count", "14")
.put("transport.tcp.reuse_address", enable == false)
.put("transport.tcp.send_buffer_size", "5b")
.put("transport.tcp.receive_buffer_size", "6b")
.put("transport.publish_host", "another_publish_host")
.put("transport.port", "9702-9802")
.put("transport.bind_host", "another_bind_host")
.put(globalSettings2)
.build();
Settings defaultProfileSettings = Settings.builder()
.put("transport.profiles.default.tcp.no_delay", enable)
.put("transport.profiles.default.tcp.keep_alive", enable)
.put("transport.profiles.default.tcp.keep_idle", "42")
.put("transport.profiles.default.tcp.keep_interval", "7")
.put("transport.profiles.default.tcp.keep_count", "13")
.put("transport.profiles.default.tcp.reuse_address", enable)
.put("transport.profiles.default.tcp.send_buffer_size", "43000b")
.put("transport.profiles.default.tcp.receive_buffer_size", "42000b")
.put("transport.profiles.default.port", "9700-9800")
.put("transport.profiles.default.publish_host", "the_publish_host")
.put("transport.profiles.default.bind_host", "the_bind_host")
.put("transport.profiles.default.publish_port", 42)
.put(randomBoolean() ? transportSettings2 : globalSettings2) // ensure that we have profile precedence
.build();
Settings profileSettings = Settings.builder()
.put("transport.profiles.some_profile.tcp.no_delay", enable)
.put("transport.profiles.some_profile.tcp.keep_alive", enable)
.put("transport.profiles.some_profile.tcp.keep_idle", "42")
.put("transport.profiles.some_profile.tcp.keep_interval", "7")
.put("transport.profiles.some_profile.tcp.keep_count", "13")
.put("transport.profiles.some_profile.tcp.reuse_address", enable)
.put("transport.profiles.some_profile.tcp.send_buffer_size", "43000b")
.put("transport.profiles.some_profile.tcp.receive_buffer_size", "42000b")
.put("transport.profiles.some_profile.port", "9700-9800")
.put("transport.profiles.some_profile.publish_host", "the_publish_host")
.put("transport.profiles.some_profile.bind_host", "the_bind_host")
.put("transport.profiles.some_profile.publish_port", 42)
.put(randomBoolean() ? transportSettings2 : globalSettings2) // ensure that we have profile precedence
.put(randomBoolean() ? defaultProfileSettings : Settings.EMPTY)
.build();
Settings randomSettings = randomFrom(random(), globalSettings, transportSettings, profileSettings);
ClusterSettings clusterSettings = new ClusterSettings(randomSettings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
clusterSettings.validate(randomSettings, false);
TcpTransport.ProfileSettings settings = new TcpTransport.ProfileSettings(
Settings.builder().put(randomSettings).put("transport.profiles.some_profile.port", "9700-9800").build(), // port is required
"some_profile"
);
assertEquals(enable, settings.tcpNoDelay);
assertEquals(enable, settings.tcpKeepAlive);
assertEquals(42, settings.tcpKeepIdle);
assertEquals(7, settings.tcpKeepInterval);
assertEquals(13, settings.tcpKeepCount);
assertEquals(enable, settings.reuseAddress);
assertEquals(43000, settings.sendBufferSize.getBytes());
assertEquals(42000, settings.receiveBufferSize.getBytes());
if (randomSettings == profileSettings) {
assertEquals(42, settings.publishPort);
} else {
assertEquals(-1, settings.publishPort);
}
if (randomSettings == globalSettings) { // publish host has no global fallback for the profile since we later resolve it based on
// the bound address
assertEquals(Collections.emptyList(), settings.publishHosts);
} else {
assertEquals(Collections.singletonList("the_publish_host"), settings.publishHosts);
}
assertEquals("9700-9800", settings.portOrRange);
assertEquals(Collections.singletonList("the_bind_host"), settings.bindHosts);
}
public void testProfilesIncludesDefault() {
Set<TcpTransport.ProfileSettings> profileSettings = TcpTransport.getProfileSettings(Settings.EMPTY);
assertEquals(1, profileSettings.size());
assertEquals(TransportSettings.DEFAULT_PROFILE, profileSettings.stream().findAny().get().profileName);
profileSettings = TcpTransport.getProfileSettings(Settings.builder().put("transport.profiles.test.port", "0").build());
assertEquals(2, profileSettings.size());
assertEquals(
new HashSet<>(Arrays.asList("default", "test")),
profileSettings.stream().map(s -> s.profileName).collect(Collectors.toSet())
);
profileSettings = TcpTransport.getProfileSettings(
Settings.builder().put("transport.profiles.test.port", "0").put("transport.profiles.default.port", "0").build()
);
assertEquals(2, profileSettings.size());
assertEquals(
new HashSet<>(Arrays.asList("default", "test")),
profileSettings.stream().map(s -> s.profileName).collect(Collectors.toSet())
);
}
public void testBindUnavailableAddress() {
int port = serviceA.boundAddress().publishAddress().getPort();
String address = serviceA.boundAddress().publishAddress().getAddress();
Settings settings = Settings.builder()
.put(Node.NODE_NAME_SETTING.getKey(), "foobar")
.put(TransportSettings.HOST.getKey(), address)
.put(TransportSettings.PORT.getKey(), port)
.build();
BindTransportException bindTransportException = expectThrows(
BindTransportException.class,
() -> buildService("test", VersionInformation.CURRENT, TransportVersion.current(), settings)
);
InetSocketAddress inetSocketAddress = serviceA.boundAddress().publishAddress().address();
assertEquals("Failed to bind to " + NetworkAddress.format(inetSocketAddress), bindTransportException.getMessage());
}
public void testChannelCloseWhileConnecting() {
try (MockTransportService service = buildService("TS_C", version0, transportVersion0, Settings.EMPTY)) {
AtomicBoolean connectionClosedListenerCalled = new AtomicBoolean(false);
service.addConnectionListener(new TransportConnectionListener() {
@Override
public void onConnectionOpened(final Transport.Connection connection) {
closeConnectionChannel(connection);
try {
assertBusy(() -> assertTrue(connection.isClosed()));
} catch (Exception e) {
throw new AssertionError(e);
}
}
@Override
public void onConnectionClosed(Transport.Connection connection) {
connectionClosedListenerCalled.set(true);
}
});
final ConnectionProfile.Builder builder = new ConnectionProfile.Builder();
builder.addConnections(
1,
TransportRequestOptions.Type.BULK,
TransportRequestOptions.Type.PING,
TransportRequestOptions.Type.RECOVERY,
TransportRequestOptions.Type.REG,
TransportRequestOptions.Type.STATE
);
final ConnectTransportException e = openConnectionExpectFailure(service, nodeA, builder.build());
assertThat(e, hasToString(containsString(("a channel closed while connecting"))));
assertTrue(connectionClosedListenerCalled.get());
}
}
public void testFailToSendTransportException() throws InterruptedException {
TransportException exception = doFailToSend(new TransportException("fail to send"));
assertThat(exception.getMessage(), equalTo("fail to send"));
assertThat(exception.getCause(), nullValue());
}
public void testFailToSendIllegalStateException() throws InterruptedException {
TransportException exception = doFailToSend(new IllegalStateException("fail to send"));
assertThat(exception, instanceOf(SendRequestTransportException.class));
assertThat(exception.getMessage(), containsString("fail-to-send-action"));
assertThat(exception.getCause(), instanceOf(IllegalStateException.class));
assertThat(exception.getCause().getMessage(), equalTo("fail to send"));
}
public void testChannelToString() {
final String ACTION = "internal:action";
serviceA.registerRequestHandler(ACTION, EsExecutors.DIRECT_EXECUTOR_SERVICE, EmptyRequest::new, (request, channel, task) -> {
assertThat(
channel.toString(),
allOf(
containsString("DirectResponseChannel"),
containsString('{' + ACTION + '}'),
containsString("TaskTransportChannel{task=" + task.getId() + '}')
)
);
assertThat(new ChannelActionListener<>(channel).toString(), containsString(channel.toString()));
channel.sendResponse(ActionResponse.Empty.INSTANCE);
});
serviceB.registerRequestHandler(ACTION, EsExecutors.DIRECT_EXECUTOR_SERVICE, EmptyRequest::new, (request, channel, task) -> {
assertThat(
channel.toString(),
allOf(
containsString("TcpTransportChannel"),
containsString('{' + ACTION + '}'),
containsString("TaskTransportChannel{task=" + task.getId() + '}'),
containsString("localAddress="),
containsString(serviceB.getLocalNode().getAddress().toString())
)
);
channel.sendResponse(ActionResponse.Empty.INSTANCE);
});
safeAwait(
listener -> submitRequest(
serviceA,
serviceA.getLocalNode(),
ACTION,
new EmptyRequest(),
new ActionListenerResponseHandler<>(
listener,
ignored -> ActionResponse.Empty.INSTANCE,
TransportResponseHandler.TRANSPORT_WORKER
)
)
);
safeAwait(
listener -> submitRequest(
serviceA,
serviceB.getLocalNode(),
ACTION,
new EmptyRequest(),
new ActionListenerResponseHandler<>(
listener,
ignored -> ActionResponse.Empty.INSTANCE,
TransportResponseHandler.TRANSPORT_WORKER
)
)
);
}
public void testActionStats() throws Exception {
final String ACTION = "internal:action";
|
TestResponseHandler
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/HazelcastMultimapEndpointBuilderFactory.java
|
{
"start": 18555,
"end": 22748
}
|
interface ____
extends
HazelcastMultimapEndpointConsumerBuilder,
HazelcastMultimapEndpointProducerBuilder {
default AdvancedHazelcastMultimapEndpointBuilder advanced() {
return (AdvancedHazelcastMultimapEndpointBuilder) this;
}
/**
* To specify a default operation to use, if no operation header has
* been provided.
*
* The option is a:
* <code>org.apache.camel.component.hazelcast.HazelcastOperation</code>
* type.
*
* Group: common
*
* @param defaultOperation the value to set
* @return the dsl builder
*/
default HazelcastMultimapEndpointBuilder defaultOperation(org.apache.camel.component.hazelcast.HazelcastOperation defaultOperation) {
doSetProperty("defaultOperation", defaultOperation);
return this;
}
/**
* To specify a default operation to use, if no operation header has
* been provided.
*
* The option will be converted to a
* <code>org.apache.camel.component.hazelcast.HazelcastOperation</code>
* type.
*
* Group: common
*
* @param defaultOperation the value to set
* @return the dsl builder
*/
default HazelcastMultimapEndpointBuilder defaultOperation(String defaultOperation) {
doSetProperty("defaultOperation", defaultOperation);
return this;
}
/**
* Hazelcast configuration file.
*
* This option can also be loaded from an existing file, by prefixing
* with file: or classpath: followed by the location of the file.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param hazelcastConfigUri the value to set
* @return the dsl builder
*/
default HazelcastMultimapEndpointBuilder hazelcastConfigUri(String hazelcastConfigUri) {
doSetProperty("hazelcastConfigUri", hazelcastConfigUri);
return this;
}
/**
* The hazelcast instance reference which can be used for hazelcast
* endpoint.
*
* The option is a: <code>com.hazelcast.core.HazelcastInstance</code>
* type.
*
* Group: common
*
* @param hazelcastInstance the value to set
* @return the dsl builder
*/
default HazelcastMultimapEndpointBuilder hazelcastInstance(com.hazelcast.core.HazelcastInstance hazelcastInstance) {
doSetProperty("hazelcastInstance", hazelcastInstance);
return this;
}
/**
* The hazelcast instance reference which can be used for hazelcast
* endpoint.
*
* The option will be converted to a
* <code>com.hazelcast.core.HazelcastInstance</code> type.
*
* Group: common
*
* @param hazelcastInstance the value to set
* @return the dsl builder
*/
default HazelcastMultimapEndpointBuilder hazelcastInstance(String hazelcastInstance) {
doSetProperty("hazelcastInstance", hazelcastInstance);
return this;
}
/**
* The hazelcast instance reference name which can be used for hazelcast
* endpoint. If you don't specify the instance reference, camel use the
* default hazelcast instance from the camel-hazelcast instance.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param hazelcastInstanceName the value to set
* @return the dsl builder
*/
default HazelcastMultimapEndpointBuilder hazelcastInstanceName(String hazelcastInstanceName) {
doSetProperty("hazelcastInstanceName", hazelcastInstanceName);
return this;
}
}
/**
* Advanced builder for endpoint for the Hazelcast Multimap component.
*/
public
|
HazelcastMultimapEndpointBuilder
|
java
|
apache__dubbo
|
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtilTest.java
|
{
"start": 882,
"end": 1051
}
|
class ____ {
@Test
void switchContextLoader() {
ClassLoadUtil.switchContextLoader(Thread.currentThread().getContextClassLoader());
}
}
|
ClassLoadUtilTest
|
java
|
assertj__assertj-core
|
assertj-guava/src/main/java/org/assertj/guava/error/ShouldHaveSameContent.java
|
{
"start": 807,
"end": 1174
}
|
class ____ extends BasicErrorMessageFactory {
public static ErrorMessageFactory shouldHaveSameContent(ByteSource actual, ByteSource expected) {
return new ShouldHaveSameContent(actual, expected);
}
private ShouldHaveSameContent(ByteSource actual, ByteSource expected) {
super("%nexpected: %s%n but was: %s", expected, actual);
}
}
|
ShouldHaveSameContent
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ql/TreatKeywordTest.java
|
{
"start": 12205,
"end": 12663
}
|
class ____ extends JoinedEntity {
@OneToMany(mappedBy = "other")
Set<JoinedEntity> others;
public JoinedEntitySubclass2() {
}
public JoinedEntitySubclass2(Integer id, String name) {
super( id, name );
}
public JoinedEntitySubclass2(Integer id, String name, JoinedEntity other) {
super( id, name, other );
}
}
@Entity( name = "JoinedEntitySubSubclass2" )
@Table( name = "JoinedEntitySubSubclass2" )
public static
|
JoinedEntitySubclass2
|
java
|
apache__camel
|
tooling/camel-util-json/src/main/java/org/apache/camel/util/json/JsonArray.java
|
{
"start": 11946,
"end": 19714
}
|
enum ____ to get the Enum<T>. */
returnType = (Class<T>) Class.forName(returnTypeName.toString());
returnable = Enum.valueOf(returnType, enumName.toString());
return returnable;
}
/**
* A convenience method that assumes there is a Number or String value at the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a float.
* @throws ClassCastException if there was a value but didn't match the assumed return type.
* @throws NumberFormatException if a String isn't a valid representation of a BigDecimal or if the Number
* represents the double or float Infinity or NaN.
* @throws IndexOutOfBoundsException if the index is outside of the range of element indexes in the JsonArray.
* @see Number
*/
public Float getFloat(final int index) {
Object returnable = this.get(index);
if (returnable == null) {
return null;
}
if (returnable instanceof String) {
/* A String can be used to construct a BigDecimal. */
returnable = new BigDecimal((String) returnable);
}
return ((Number) returnable).floatValue();
}
/**
* A convenience method that assumes there is a Number or String value at the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a int.
* @throws ClassCastException if there was a value but didn't match the assumed return type.
* @throws NumberFormatException if a String isn't a valid representation of a BigDecimal or if the Number
* represents the double or float Infinity or NaN.
* @throws IndexOutOfBoundsException if the index is outside of the range of element indexes in the JsonArray.
* @see Number
*/
public Integer getInteger(final int index) {
Object returnable = this.get(index);
if (returnable == null) {
return null;
}
if (returnable instanceof String) {
/* A String can be used to construct a BigDecimal. */
returnable = new BigDecimal((String) returnable);
}
return ((Number) returnable).intValue();
}
/**
* A convenience method that assumes there is a Number or String value at the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a long.
* @throws ClassCastException if there was a value but didn't match the assumed return type.
* @throws NumberFormatException if a String isn't a valid representation of a BigDecimal or if the Number
* represents the double or float Infinity or NaN.
* @throws IndexOutOfBoundsException if the index is outside of the range of element indexes in the JsonArray.
* @see Number
*/
public Long getLong(final int index) {
Object returnable = this.get(index);
if (returnable == null) {
return null;
}
if (returnable instanceof String) {
/* A String can be used to construct a BigDecimal. */
returnable = new BigDecimal((String) returnable);
}
return ((Number) returnable).longValue();
}
/**
* A convenience method that assumes there is a Map value at the given index.
*
* @param <T> the kind of map to expect at the index. Note unless manually added, Map values
* will be a JsonObject.
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a Map.
* @throws ClassCastException if there was a value but didn't match the assumed return type.
* @throws IndexOutOfBoundsException if the index is outside of the range of element indexes in the JsonArray.
* @see Map
*/
@SuppressWarnings("unchecked")
public <T extends Map<?, ?>> T getMap(final int index) {
/*
* The unchecked warning is suppressed because there is no way of
* guaranteeing at compile time the cast will work.
*/
return (T) this.get(index);
}
/**
* A convenience method that assumes there is a Number or String value at the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a short.
* @throws ClassCastException if there was a value but didn't match the assumed return type.
* @throws NumberFormatException if a String isn't a valid representation of a BigDecimal or if the Number
* represents the double or float Infinity or NaN.
* @throws IndexOutOfBoundsException if the index is outside of the range of element indexes in the JsonArray.
* @see Number
*/
public Short getShort(final int index) {
Object returnable = this.get(index);
if (returnable == null) {
return null;
}
if (returnable instanceof String) {
/* A String can be used to construct a BigDecimal. */
returnable = new BigDecimal((String) returnable);
}
return ((Number) returnable).shortValue();
}
/**
* A convenience method that assumes there is a Boolean, Number, or String value at the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a String.
* @throws ClassCastException if there was a value but didn't match the assumed return type.
* @throws IndexOutOfBoundsException if the index is outside of the range of element indexes in the JsonArray.
*/
public String getString(final int index) {
Object returnable = this.get(index);
if (returnable instanceof Boolean) {
returnable = returnable.toString();
} else if (returnable instanceof Number) {
returnable = returnable.toString();
}
return (String) returnable;
}
/*
* (non-Javadoc)
* @see org.apache.camel.util.json.Jsonable#asJsonString()
*/
@Override
public String toJson() {
final StringWriter writable = new StringWriter();
try {
this.toJson(writable);
} catch (final IOException caught) {
/* See java.io.StringWriter. */
}
return writable.toString();
}
/*
* (non-Javadoc)
* @see org.apache.camel.util.json.Jsonable#toJsonString(java.io.Writer)
*/
@Override
public void toJson(final Writer writable) throws IOException {
boolean isFirstElement = true;
final Iterator<Object> elements = this.iterator();
writable.write('[');
while (elements.hasNext()) {
if (isFirstElement) {
isFirstElement = false;
} else {
writable.write(',');
}
Jsoner.serialize(elements.next(), writable);
}
writable.write(']');
}
}
|
names
|
java
|
apache__dubbo
|
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RestSpringScopeModelInitializer.java
|
{
"start": 1268,
"end": 1706
}
|
class ____ implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory();
beanFactory.registerBean(GeneralTypeConverter.class);
beanFactory.registerBean(DefaultParameterNameReader.class);
beanFactory.registerBean(CompositeArgumentResolver.class);
}
}
|
RestSpringScopeModelInitializer
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/UnicodeInCodeTest.java
|
{
"start": 3449,
"end": 3704
}
|
class ____ {
static final double \u03c0 = 3;
}
""")
.doTest();
}
@Test
public void suppressibleAtMethodLevel() {
helper
.addSourceLines(
"Test.java",
"""
|
Test
|
java
|
grpc__grpc-java
|
core/src/testFixtures/java/io/grpc/internal/ReadableBufferTestBase.java
|
{
"start": 1030,
"end": 1127
}
|
class ____ tests of {@link ReadableBuffer} subclasses.
*/
@RunWith(JUnit4.class)
public abstract
|
for
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/tool/schema/spi/DelayedDropAction.java
|
{
"start": 474,
"end": 662
}
|
interface ____ {
/**
* Perform the delayed schema drop.
*
* @param serviceRegistry Access to the ServiceRegistry
*/
void perform(ServiceRegistry serviceRegistry);
}
|
DelayedDropAction
|
java
|
spring-projects__spring-boot
|
buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/configuration/DockerConfigurationMetadata.java
|
{
"start": 5801,
"end": 6855
}
|
class ____ extends MappedObject {
private final @Nullable String currentContext;
private final @Nullable String credsStore;
private final Map<String, String> credHelpers;
private final Map<String, Auth> auths;
private DockerConfig(JsonNode node) {
super(node, MethodHandles.lookup());
this.currentContext = valueAt("/currentContext", String.class);
this.credsStore = valueAt("/credsStore", String.class);
this.credHelpers = mapAt("/credHelpers", JsonNode::stringValue);
this.auths = mapAt("/auths", Auth::new);
}
@Nullable String getCurrentContext() {
return this.currentContext;
}
@Nullable String getCredsStore() {
return this.credsStore;
}
Map<String, String> getCredHelpers() {
return this.credHelpers;
}
Map<String, Auth> getAuths() {
return this.auths;
}
static DockerConfig fromJson(String json) {
return new DockerConfig(SharedJsonMapper.get().readTree(json));
}
static DockerConfig empty() {
return new DockerConfig(NullNode.instance);
}
}
static final
|
DockerConfig
|
java
|
grpc__grpc-java
|
api/src/main/java/io/grpc/CallOptions.java
|
{
"start": 10939,
"end": 18128
}
|
class ____<T> {
private final String debugString;
private final T defaultValue;
private Key(String debugString, T defaultValue) {
this.debugString = debugString;
this.defaultValue = defaultValue;
}
/**
* Returns the user supplied default value for this key.
*/
public T getDefault() {
return defaultValue;
}
@Override
public String toString() {
return debugString;
}
/**
* Factory method for creating instances of {@link Key}.
*
* @param debugString a string used to describe this key, used for debugging.
* @param defaultValue default value to return when value for key not set
* @param <T> Key type
* @return Key object
* @deprecated Use {@link #create} or {@link #createWithDefault} instead. This method will
* be removed.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1869")
@Deprecated
public static <T> Key<T> of(String debugString, T defaultValue) {
Preconditions.checkNotNull(debugString, "debugString");
return new Key<>(debugString, defaultValue);
}
/**
* Factory method for creating instances of {@link Key}. The default value of the
* key is {@code null}.
*
* @param debugString a debug string that describes this key.
* @param <T> Key type
* @return Key object
* @since 1.13.0
*/
public static <T> Key<T> create(String debugString) {
Preconditions.checkNotNull(debugString, "debugString");
return new Key<>(debugString, /*defaultValue=*/ null);
}
/**
* Factory method for creating instances of {@link Key}.
*
* @param debugString a debug string that describes this key.
* @param defaultValue default value to return when value for key not set
* @param <T> Key type
* @return Key object
* @since 1.13.0
*/
public static <T> Key<T> createWithDefault(String debugString, T defaultValue) {
Preconditions.checkNotNull(debugString, "debugString");
return new Key<>(debugString, defaultValue);
}
}
/**
* Sets a custom option. Any existing value for the key is overwritten.
*
* @param key The option key
* @param value The option value.
* @since 1.13.0
*/
public <T> CallOptions withOption(Key<T> key, T value) {
Preconditions.checkNotNull(key, "key");
Preconditions.checkNotNull(value, "value");
Builder builder = toBuilder(this);
int existingIdx = -1;
for (int i = 0; i < customOptions.length; i++) {
if (key.equals(customOptions[i][0])) {
existingIdx = i;
break;
}
}
builder.customOptions = new Object[customOptions.length + (existingIdx == -1 ? 1 : 0)][2];
System.arraycopy(customOptions, 0, builder.customOptions, 0, customOptions.length);
if (existingIdx == -1) {
// Add a new option
builder.customOptions[customOptions.length] = new Object[] {key, value};
} else {
// Replace an existing option
builder.customOptions[existingIdx] = new Object[] {key, value};
}
return builder.build();
}
/**
* Get the value for a custom option or its inherent default.
* @param key Key identifying option
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1869")
@SuppressWarnings("unchecked")
public <T> T getOption(Key<T> key) {
Preconditions.checkNotNull(key, "key");
for (int i = 0; i < customOptions.length; i++) {
if (key.equals(customOptions[i][0])) {
return (T) customOptions[i][1];
}
}
return key.defaultValue;
}
/**
* Returns the executor override to use for this specific call, or {@code null} if there is no
* override. The executor is only for servicing this one call, so is not safe to use after
* {@link ClientCall.Listener#onClose}.
*/
@Nullable
public Executor getExecutor() {
return executor;
}
/**
* Returns whether <a href="https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md">
* 'wait for ready'</a> option is enabled for the call. 'Fail fast' is the default option for gRPC
* calls and 'wait for ready' is the opposite to it.
*/
public boolean isWaitForReady() {
return Boolean.TRUE.equals(waitForReady);
}
Boolean getWaitForReady() {
return waitForReady;
}
/**
* Sets the maximum allowed message size acceptable from the remote peer. If unset, this will
* default to the value set on the {@link ManagedChannelBuilder#maxInboundMessageSize(int)}.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/2563")
public CallOptions withMaxInboundMessageSize(int maxSize) {
checkArgument(maxSize >= 0, "invalid maxsize %s", maxSize);
Builder builder = toBuilder(this);
builder.maxInboundMessageSize = maxSize;
return builder.build();
}
/**
* Sets the maximum allowed message size acceptable sent to the remote peer.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/2563")
public CallOptions withMaxOutboundMessageSize(int maxSize) {
checkArgument(maxSize >= 0, "invalid maxsize %s", maxSize);
Builder builder = toBuilder(this);
builder.maxOutboundMessageSize = maxSize;
return builder.build();
}
/**
* Gets the maximum allowed message size acceptable from the remote peer.
*/
@Nullable
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/2563")
public Integer getMaxInboundMessageSize() {
return maxInboundMessageSize;
}
/**
* Gets the maximum allowed message size acceptable to send the remote peer.
*/
@Nullable
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/2563")
public Integer getMaxOutboundMessageSize() {
return maxOutboundMessageSize;
}
/**
* Copy CallOptions.
*/
private static Builder toBuilder(CallOptions other) {
Builder builder = new Builder();
builder.deadline = other.deadline;
builder.executor = other.executor;
builder.authority = other.authority;
builder.credentials = other.credentials;
builder.compressorName = other.compressorName;
builder.customOptions = other.customOptions;
builder.streamTracerFactories = other.streamTracerFactories;
builder.waitForReady = other.waitForReady;
builder.maxInboundMessageSize = other.maxInboundMessageSize;
builder.maxOutboundMessageSize = other.maxOutboundMessageSize;
builder.onReadyThreshold = other.onReadyThreshold;
return builder;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("deadline", deadline)
.add("authority", authority)
.add("callCredentials", credentials)
.add("executor", executor != null ? executor.getClass() : null)
.add("compressorName", compressorName)
.add("customOptions", Arrays.deepToString(customOptions))
.add("waitForReady", isWaitForReady())
.add("maxInboundMessageSize", maxInboundMessageSize)
.add("maxOutboundMessageSize", maxOutboundMessageSize)
.add("onReadyThreshold", onReadyThreshold)
.add("streamTracerFactories", streamTracerFactories)
.toString();
}
}
|
Key
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java
|
{
"start": 1831,
"end": 1955
}
|
class ____ {
private MockHttpServletResponse response = new MockHttpServletResponse();
@Nested
|
MockHttpServletResponseTests
|
java
|
quarkusio__quarkus
|
extensions/security-jpa/runtime/src/main/java/io/quarkus/security/jpa/runtime/JpaTrustedIdentityProvider.java
|
{
"start": 794,
"end": 2845
}
|
class ____ implements IdentityProvider<TrustedAuthenticationRequest> {
private static Logger log = Logger.getLogger(JpaTrustedIdentityProvider.class);
@Inject
SessionFactory sessionFactory;
@Override
public Class<TrustedAuthenticationRequest> getRequestType() {
return TrustedAuthenticationRequest.class;
}
@Override
public Uni<SecurityIdentity> authenticate(TrustedAuthenticationRequest request,
AuthenticationRequestContext context) {
return context.runBlocking(new Supplier<SecurityIdentity>() {
@Override
public SecurityIdentity get() {
if (requireActiveCDIRequestContext() && !Arc.container().requestContext().isActive()) {
var requestContext = Arc.container().requestContext();
requestContext.activate();
try {
return authenticate(request);
} finally {
requestContext.terminate();
}
}
return authenticate(request);
}
});
}
private SecurityIdentity authenticate(TrustedAuthenticationRequest request) {
try (Session session = sessionFactory.openSession()) {
session.setHibernateFlushMode(FlushMode.MANUAL);
session.setDefaultReadOnly(true);
return authenticate(session, request);
} catch (SecurityException e) {
log.debug("Authentication failed", e);
throw new AuthenticationFailedException(e);
}
}
protected boolean requireActiveCDIRequestContext() {
return false;
}
protected <T> T getSingleUser(Query query) {
@SuppressWarnings("unchecked")
List<T> results = (List<T>) query.getResultList();
return JpaIdentityProviderUtil.getSingleUser(results);
}
public abstract SecurityIdentity authenticate(EntityManager em,
TrustedAuthenticationRequest request);
}
|
JpaTrustedIdentityProvider
|
java
|
quarkusio__quarkus
|
extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CustomIdentityProviderTestCase.java
|
{
"start": 709,
"end": 3023
}
|
class ____ {
private static Class<?>[] testClasses = {
ProtectedResource.class,
CustomIdentityProvider.class
};
@RegisterExtension
static final QuarkusDevModeTest test = new QuarkusDevModeTest()
.withApplicationRoot((jar) -> jar
.addClasses(testClasses)
.addAsResource("application-introspection-disabled.properties", "application.properties"));
@Test
public void testCustomIdentityProviderSuccess() throws IOException, InterruptedException {
try (final WebClient webClient = createWebClient()) {
HtmlPage page = webClient.getPage("http://localhost:8080/protected");
assertEquals("Sign in to quarkus", page.getTitleText());
HtmlForm loginForm = page.getForms().get(0);
loginForm.getInputByName("username").setValueAttribute("alice");
loginForm.getInputByName("password").setValueAttribute("alice");
page = loginForm.getButtonByName("login").click();
assertEquals("alice", page.getBody().asNormalizedText());
webClient.getCookieManager().clearCookies();
}
}
@Test
public void testCustomIdentityProviderFailure() throws IOException, InterruptedException {
try (final WebClient webClient = createWebClient()) {
HtmlPage page = webClient.getPage("http://localhost:8080/protected");
assertEquals("Sign in to quarkus", page.getTitleText());
HtmlForm loginForm = page.getForms().get(0);
loginForm.getInputByName("username").setValueAttribute("jdoe");
loginForm.getInputByName("password").setValueAttribute("jdoe");
try {
loginForm.getButtonByName("login").click();
fail("Exception is expected because `jdoe` is not allowed to access the service");
} catch (FailingHttpStatusCodeException ex) {
assertEquals(401, ex.getStatusCode());
}
webClient.getCookieManager().clearCookies();
}
}
private WebClient createWebClient() {
WebClient webClient = new WebClient();
webClient.setCssErrorHandler(new SilentCssErrorHandler());
return webClient;
}
}
|
CustomIdentityProviderTestCase
|
java
|
google__guice
|
core/test/com/google/inject/util/OverrideModuleTest.java
|
{
"start": 19422,
"end": 19659
}
|
class ____ implements Scope {
boolean used = false;
@Override
public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
assertFalse(used);
used = true;
return unscoped;
}
}
static
|
SingleUseScope
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MllpEndpointBuilderFactory.java
|
{
"start": 77380,
"end": 83836
}
|
class ____ {
/**
* The internal instance of the builder used to access to all the
* methods representing the name of headers.
*/
private static final MllpHeaderNameBuilder INSTANCE = new MllpHeaderNameBuilder();
/**
* The local TCP Address of the Socket.
*
* The option is a: {@code String} type.
*
* Group: common
*
* @return the name of the header {@code MllpLocalAddress}.
*/
public String mllpLocalAddress() {
return "CamelMllpLocalAddress";
}
/**
* The remote TCP Address of the Socket.
*
* The option is a: {@code String} type.
*
* Group: common
*
* @return the name of the header {@code MllpRemoteAddress}.
*/
public String mllpRemoteAddress() {
return "CamelMllpRemoteAddress";
}
/**
* The HL7 Acknowledgment received in bytes.
*
* The option is a: {@code byte[]} type.
*
* Group: common
*
* @return the name of the header {@code MllpAcknowledgement}.
*/
public String mllpAcknowledgement() {
return "CamelMllpAcknowledgement";
}
/**
* The HL7 Acknowledgment received, converted to a String.
*
* The option is a: {@code String} type.
*
* Group: common
*
* @return the name of the header {@code MllpAcknowledgementString}.
*/
public String mllpAcknowledgementString() {
return "CamelMllpAcknowledgementString";
}
/**
* The HL7 acknowledgement type (AA, AE, AR, etc).
*
* The option is a: {@code String} type.
*
* Group: common
*
* @return the name of the header {@code MllpAcknowledgementType}.
*/
public String mllpAcknowledgementType() {
return "CamelMllpAcknowledgementType";
}
/**
* MSH-3 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpSendingApplication}.
*/
public String mllpSendingApplication() {
return "CamelMllpSendingApplication";
}
/**
* MSH-4 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpSendingFacility}.
*/
public String mllpSendingFacility() {
return "CamelMllpSendingFacility";
}
/**
* MSH-5 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpReceivingApplication}.
*/
public String mllpReceivingApplication() {
return "CamelMllpReceivingApplication";
}
/**
* MSH-6 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpReceivingFacility}.
*/
public String mllpReceivingFacility() {
return "CamelMllpReceivingFacility";
}
/**
* MSH-7 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpTimestamp}.
*/
public String mllpTimestamp() {
return "CamelMllpTimestamp";
}
/**
* MSH-8 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpSecurity}.
*/
public String mllpSecurity() {
return "CamelMllpSecurity";
}
/**
* MSH-9 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpMessageType}.
*/
public String mllpMessageType() {
return "CamelMllpMessageType";
}
/**
* MSH-9.1 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpEventType}.
*/
public String mllpEventType() {
return "CamelMllpEventType";
}
/**
* MSH-9.2 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpTriggerEvent}.
*/
public String mllpTriggerEvent() {
return "CamelMllpTriggerEvent";
}
/**
* MSH-10 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpMessageControlId}.
*/
public String mllpMessageControlId() {
return "CamelMllpMessageControlId";
}
/**
* MSH-11 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpProcessingId}.
*/
public String mllpProcessingId() {
return "CamelMllpProcessingId";
}
/**
* MSH-12 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpVersionId}.
*/
public String mllpVersionId() {
return "CamelMllpVersionId";
}
/**
* MSH-18 value.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code MllpCharset}.
*/
public String mllpCharset() {
return "CamelMllpCharset";
}
}
static MllpEndpointBuilder endpointBuilder(String componentName, String path) {
|
MllpHeaderNameBuilder
|
java
|
spring-projects__spring-framework
|
spring-test/src/main/java/org/springframework/test/context/event/ApplicationEventsHolder.java
|
{
"start": 1078,
"end": 1438
}
|
class ____ {@code public}, it is only intended for use within
* the <em>Spring TestContext Framework</em> or in the implementation of
* third-party extensions. Test authors should therefore allow the current
* instance of {@code ApplicationEvents} to be
* {@link org.springframework.beans.factory.annotation.Autowired @Autowired}
* into a field in the test
|
is
|
java
|
quarkusio__quarkus
|
integration-tests/main/src/main/java/io/quarkus/it/config/ApplicationInfoResource.java
|
{
"start": 250,
"end": 702
}
|
class ____ {
@ConfigProperty(name = "quarkus.application.version")
String applicationVersion;
@ConfigProperty(name = "quarkus.application.name")
String applicationName;
@ConfigProperty(name = "quarkus.profile")
String applicationProfile;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return applicationName + "/" + applicationVersion + "/" + applicationProfile;
}
}
|
ApplicationInfoResource
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/provider/GlobalResponseFilter.java
|
{
"start": 374,
"end": 764
}
|
class ____ implements ResteasyReactiveClientResponseFilter {
public static final int STATUS = 222;
@Override
public void filter(ResteasyReactiveClientRequestContext requestContext, ClientResponseContext responseContext) {
if (responseContext.getStatus() != GlobalRequestFilter.STATUS) {
responseContext.setStatus(STATUS);
}
}
}
|
GlobalResponseFilter
|
java
|
elastic__elasticsearch
|
libs/h3/src/test/java/org/elasticsearch/h3/HexRingTests.java
|
{
"start": 955,
"end": 2639
}
|
class ____ extends ESTestCase {
public void testInvalidHexRingPos() {
long h3 = H3.geoToH3(GeoTestUtil.nextLatitude(), GeoTestUtil.nextLongitude(), randomIntBetween(0, H3.MAX_H3_RES));
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> H3.hexRingPosToH3(h3, -1));
assertEquals(ex.getMessage(), "invalid ring position");
int pos = H3.isPentagon(h3) ? 5 : 6;
ex = expectThrows(IllegalArgumentException.class, () -> H3.hexRingPosToH3(h3, pos));
assertEquals(ex.getMessage(), "invalid ring position");
}
public void testHexRing() {
for (int i = 0; i < 500; i++) {
double lat = GeoTestUtil.nextLatitude();
double lon = GeoTestUtil.nextLongitude();
for (int res = 0; res <= H3.MAX_H3_RES; res++) {
String origin = H3.geoToH3Address(lat, lon, res);
assertFalse(H3.areNeighborCells(origin, origin));
String[] ring = H3.hexRing(origin);
Arrays.sort(ring);
for (String destination : ring) {
assertTrue(H3.areNeighborCells(origin, destination));
String[] newRing = H3.hexRing(destination);
for (String newDestination : newRing) {
if (Arrays.binarySearch(ring, newDestination) >= 0) {
assertTrue(H3.areNeighborCells(origin, newDestination));
} else {
assertFalse(H3.areNeighborCells(origin, newDestination));
}
}
}
}
}
}
}
|
HexRingTests
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/ComponentProcessorTest.java
|
{
"start": 48904,
"end": 49297
}
|
class ____ {",
" @SuppressWarnings(\"BadInject\") // Ignore this check as we want to test this case"
+ " in particular.",
" @Inject Object object;",
"",
" @Inject",
" LocalInjectMemberWithConstructor() {}",
" }",
"",
" public static final
|
LocalInjectMemberWithConstructor
|
java
|
mybatis__mybatis-3
|
src/test/java/org/apache/ibatis/submitted/empty_row/Parent.java
|
{
"start": 729,
"end": 1614
}
|
class ____ {
private Integer id;
private String col1;
private String col2;
private Child child;
private List<Child> children;
private List<Pet> pets;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCol1() {
return col1;
}
public void setCol1(String col1) {
this.col1 = col1;
}
public String getCol2() {
return col2;
}
public void setCol2(String col2) {
this.col2 = col2;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
public List<Child> getChildren() {
return children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
public List<Pet> getPets() {
return pets;
}
public void setPets(List<Pet> pets) {
this.pets = pets;
}
}
|
Parent
|
java
|
apache__maven
|
compat/maven-toolchain-builder/src/test/java/org/apache/maven/toolchain/merge/MavenToolchainMergerTest.java
|
{
"start": 1259,
"end": 6111
}
|
class ____ {
private MavenToolchainMerger merger = new MavenToolchainMerger();
private DefaultToolchainsReader reader = new DefaultToolchainsReader();
@Test
void testMergeNulls() {
merger.merge(null, null, null);
PersistedToolchains pt = new PersistedToolchains();
merger.merge(pt, null, null);
merger.merge(null, pt, null);
}
@Test
void testMergeJdk() throws Exception {
try (InputStream isDominant = MavenToolchainMergerTest.class.getResourceAsStream("toolchains-jdks.xml");
InputStream isRecessive = MavenToolchainMergerTest.class.getResourceAsStream("toolchains-jdks.xml")) {
PersistedToolchains dominant = read(isDominant);
PersistedToolchains recessive = read(isRecessive);
assertEquals(2, dominant.getToolchains().size());
merger.merge(dominant, recessive, TrackableBase.USER_LEVEL);
assertEquals(2, dominant.getToolchains().size());
}
}
@Test
void testMergeJdkExtra() throws Exception {
try (InputStream jdksIS = MavenToolchainMergerTest.class.getResourceAsStream("toolchains-jdks.xml");
InputStream jdksExtraIS =
MavenToolchainMergerTest.class.getResourceAsStream("toolchains-jdks-extra.xml")) {
PersistedToolchains jdks = read(jdksIS);
PersistedToolchains jdksExtra = read(jdksExtraIS);
assertEquals(2, jdks.getToolchains().size());
merger.merge(jdks, jdksExtra, TrackableBase.USER_LEVEL);
assertEquals(4, jdks.getToolchains().size());
assertEquals(2, jdksExtra.getToolchains().size());
}
try (InputStream jdksIS = MavenToolchainMergerTest.class.getResourceAsStream("toolchains-jdks.xml");
InputStream jdksExtraIS =
MavenToolchainMergerTest.class.getResourceAsStream("toolchains-jdks-extra.xml")) {
PersistedToolchains jdks = read(jdksIS);
PersistedToolchains jdksExtra = read(jdksExtraIS);
assertEquals(2, jdks.getToolchains().size());
// switch dominant with recessive
merger.merge(jdksExtra, jdks, TrackableBase.USER_LEVEL);
assertEquals(4, jdksExtra.getToolchains().size());
assertEquals(2, jdks.getToolchains().size());
}
}
@Test
void testMergeJdkExtend() throws Exception {
try (InputStream jdksIS = MavenToolchainMergerTest.class.getResourceAsStream("toolchains-jdks.xml");
InputStream jdksExtendIS =
MavenToolchainMergerTest.class.getResourceAsStream("toolchains-jdks-extend.xml")) {
PersistedToolchains jdks = read(jdksIS);
PersistedToolchains jdksExtend = read(jdksExtendIS);
assertEquals(2, jdks.getToolchains().size());
merger.merge(jdks, jdksExtend, TrackableBase.USER_LEVEL);
assertEquals(2, jdks.getToolchains().size());
Xpp3Dom config0 = (Xpp3Dom) jdks.getToolchains().get(0).getConfiguration();
assertEquals("lib/tools.jar", config0.getChild("toolsJar").getValue());
assertEquals(2, config0.getChildCount());
Xpp3Dom config1 = (Xpp3Dom) jdks.getToolchains().get(1).getConfiguration();
assertEquals(2, config1.getChildCount());
assertEquals("lib/classes.jar", config1.getChild("toolsJar").getValue());
assertEquals(2, jdksExtend.getToolchains().size());
}
try (InputStream jdksIS = MavenToolchainMergerTest.class.getResourceAsStream("toolchains-jdks.xml");
InputStream jdksExtendIS =
MavenToolchainMergerTest.class.getResourceAsStream("toolchains-jdks-extend.xml")) {
PersistedToolchains jdks = read(jdksIS);
PersistedToolchains jdksExtend = read(jdksExtendIS);
assertEquals(2, jdks.getToolchains().size());
// switch dominant with recessive
merger.merge(jdksExtend, jdks, TrackableBase.USER_LEVEL);
assertEquals(2, jdksExtend.getToolchains().size());
Xpp3Dom config0 = (Xpp3Dom) jdksExtend.getToolchains().get(0).getConfiguration();
assertEquals("lib/tools.jar", config0.getChild("toolsJar").getValue());
assertEquals(2, config0.getChildCount());
Xpp3Dom config1 = (Xpp3Dom) jdksExtend.getToolchains().get(1).getConfiguration();
assertEquals(2, config1.getChildCount());
assertEquals("lib/classes.jar", config1.getChild("toolsJar").getValue());
assertEquals(2, jdks.getToolchains().size());
}
}
private PersistedToolchains read(InputStream is) throws IOException {
return reader.read(is, Collections.emptyMap());
}
}
|
MavenToolchainMergerTest
|
java
|
quarkusio__quarkus
|
extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/SmallRyeAuthGraphQLWSSubprotocolHandler.java
|
{
"start": 660,
"end": 2428
}
|
class ____ extends GraphQLWSSubprotocolHandler {
private final SmallRyeAuthGraphQLWSHandler authHander;
public SmallRyeAuthGraphQLWSSubprotocolHandler(GraphQLWebSocketSession session,
Map<String, Object> context,
RoutingContext ctx,
SmallRyeGraphQLAbstractHandler handler,
Optional<String> authorizationClientInitPayloadName) {
super(session, context);
this.authHander = new SmallRyeAuthGraphQLWSHandler(session, ctx, handler, authorizationClientInitPayloadName);
}
@Override
protected void onMessage(JsonObject message) {
if (message != null && message.getString("type").equals("connection_init")) {
Map<String, Object> payload = (Map<String, Object>) message.get("payload");
this.authHander.handlePayload(payload, () -> {
// Identity has been updated. Now pass the successful connection_init back to the SmallRye GraphQL library to take over
super.onMessage(message);
}, failure -> {
// Failure handling Authorization. This method triggers a 4401 (Unauthorized).
if (!session.isClosed()) {
if (failure instanceof SmallRyeAuthSecurityIdentityAlreadyAssignedException) {
session.close((short) 4400, "Authorization specified in multiple locations");
} else {
session.close((short) 4403, "Forbidden");
}
}
});
} else {
super.onMessage(message);
}
}
@Override
public void onClose() {
super.onClose();
this.authHander.cancelAuthExpiry();
}
}
|
SmallRyeAuthGraphQLWSSubprotocolHandler
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerRequiredModifiers.java
|
{
"start": 17991,
"end": 19450
}
|
class ____ another file, rewrites it to
* refer to a logger in this file, defining one if necessary.
*/
private Description rehomeLogger(ExpressionTree tree, VisitorState state) {
Symbol sym = ASTHelpers.getSymbol(tree);
if (sym == null) {
return NO_MATCH;
}
Type type = sym.type;
if (!ASTHelpers.isSameType(type, LOGGER_TYPE.get(state), state)) {
return NO_MATCH;
}
Symbol owner = sym.owner;
if (!(owner instanceof ClassSymbol)) {
// This may be looking up FluentLogger itself, as a member of its package, or reading a local.
return NO_MATCH;
}
if (!(isStatic(sym) || tree instanceof IdentifierTree)) {
// We can only be referring to another class's logger statically, or implicitly through a
// superclass as an identifier. This early exit avoids flagging instance field lookups.
return NO_MATCH;
}
/* Loggers owned by public interfaces should be moved regardless of whether they're defined in
the current file, because fields in interfaces must be public, but loggers should be private.
*/
boolean needsMoveFromInterface = owner.isInterface();
Symbol outermostClassOfLogger = findUltimateOwningClass(owner);
ClassTree outermostClassOfFile = null;
for (Tree parent : state.getPath()) {
Symbol ownerSym = ASTHelpers.getSymbol(parent);
if (outermostClassOfLogger.equals(ownerSym)) {
/* Seems to be a logger owned by a
|
in
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/error/ShouldBeCanonicalPath.java
|
{
"start": 812,
"end": 1211
}
|
class ____ extends BasicErrorMessageFactory {
private static final String SHOULD_BE_CANONICAL = "%nExpecting actual:%n %s%nto be a canonical path";
public static ErrorMessageFactory shouldBeCanonicalPath(final Path actual) {
return new ShouldBeCanonicalPath(actual);
}
private ShouldBeCanonicalPath(final Path actual) {
super(SHOULD_BE_CANONICAL, actual);
}
}
|
ShouldBeCanonicalPath
|
java
|
spring-projects__spring-framework
|
spring-test/src/main/java/org/springframework/test/web/client/MockRestServiceServer.java
|
{
"start": 9275,
"end": 9915
}
|
class ____ extends AbstractMockRestServiceServerBuilder {
private final RestClient.Builder restClientBuilder;
RestClientMockRestServiceServerBuilder(RestClient.Builder restClientBuilder) {
Assert.notNull(restClientBuilder, "RestClient.Builder must not be null");
this.restClientBuilder = restClientBuilder;
}
@Override
protected void injectRequestFactory(ClientHttpRequestFactory requestFactory) {
if (shouldBufferContent()) {
this.restClientBuilder.bufferContent((uri, httpMethod) -> true);
}
this.restClientBuilder.requestFactory(requestFactory);
}
}
private static
|
RestClientMockRestServiceServerBuilder
|
java
|
reactor__reactor-core
|
reactor-core/src/main/java/reactor/core/publisher/MonoMapFuseable.java
|
{
"start": 1172,
"end": 2301
}
|
class ____<T, R> extends InternalMonoOperator<T, R>
implements Fuseable {
final Function<? super T, ? extends R> mapper;
/**
* Constructs a StreamMap instance with the given source and mapper.
*
* @param source the source Publisher instance
* @param mapper the mapper function
* @throws NullPointerException if either {@code source} or {@code mapper} is null.
*/
MonoMapFuseable(Mono<? extends T> source, Function<? super T, ? extends R> mapper) {
super(source);
this.mapper = Objects.requireNonNull(mapper, "mapper");
}
@Override
@SuppressWarnings("unchecked")
public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super R> actual) {
if (actual instanceof ConditionalSubscriber) {
ConditionalSubscriber<? super R> cs = (ConditionalSubscriber<? super R>) actual;
return new FluxMapFuseable.MapFuseableConditionalSubscriber<>(cs, mapper);
}
return new FluxMapFuseable.MapFuseableSubscriber<>(actual, mapper);
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return super.scanUnsafe(key);
}
}
|
MonoMapFuseable
|
java
|
apache__camel
|
components/camel-swift/src/test/java/org/apache/camel/dataformat/swift/mt/SpringSwiftMtDataFormatTest.java
|
{
"start": 1664,
"end": 3667
}
|
class ____ extends CamelSpringTestSupport {
@Test
void testUnmarshal() throws Exception {
MockEndpoint mockEndpoint = getMockEndpoint("mock:unmarshal");
mockEndpoint.expectedMessageCount(1);
Object result
= template.requestBody("direct:unmarshal", Files.readAllBytes(Paths.get("src/test/resources/mt/message1.txt")));
assertNotNull(result);
assertInstanceOf(MT515.class, result);
mockEndpoint.assertIsSatisfied();
}
@Test
void testMarshal() throws Exception {
MockEndpoint mockEndpoint = getMockEndpoint("mock:marshal");
mockEndpoint.expectedMessageCount(1);
MT103 message = MT103.parse(Files.readString(Paths.get("src/test/resources/mt/message2.txt")));
Object result = template.requestBody("direct:marshal", message);
assertNotNull(result);
assertInstanceOf(InputStream.class, result);
MT103 actual = MT103.parse((InputStream) result);
assertEquals(message.message(), actual.message());
mockEndpoint.assertIsSatisfied();
}
@Test
void testMarshalJson() throws Exception {
MockEndpoint mockEndpoint = getMockEndpoint("mock:marshalJson");
mockEndpoint.expectedMessageCount(1);
MT103 message = MT103.parse(Files.readString(Paths.get("src/test/resources/mt/message2.txt")));
Object result = template.requestBody("direct:marshalJson", message);
assertNotNull(result);
assertInstanceOf(InputStream.class, result);
ObjectMapper mapper = new ObjectMapper();
assertEquals(mapper.readTree(Files.readString(Paths.get("src/test/resources/mt/message2.json"))),
mapper.readTree((InputStream) result));
mockEndpoint.assertIsSatisfied();
}
@Override
protected AbstractApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("routes/SpringSwiftMtDataFormatTest.xml");
}
}
|
SpringSwiftMtDataFormatTest
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/selfinvocation/SelfInvocationTest.java
|
{
"start": 1395,
"end": 1670
}
|
class ____ {
public String ping() {
return nok();
}
@Nok
public String nok() {
return "nokMethod";
}
@Ok
public String ok() {
return nok();
}
}
}
|
DependentInterceptedBean
|
java
|
apache__flink
|
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/data/util/DataFormatConverters.java
|
{
"start": 37749,
"end": 38532
}
|
class ____
extends DataFormatConverter<ArrayData, int[]> {
private static final long serialVersionUID = 1780941126232395638L;
public static final PrimitiveIntArrayConverter INSTANCE = new PrimitiveIntArrayConverter();
private PrimitiveIntArrayConverter() {}
@Override
ArrayData toInternalImpl(int[] value) {
return new GenericArrayData(value);
}
@Override
int[] toExternalImpl(ArrayData value) {
return value.toIntArray();
}
@Override
int[] toExternalImpl(RowData row, int column) {
return toExternalImpl(row.getArray(column));
}
}
/** Converter for primitive boolean array. */
public static final
|
PrimitiveIntArrayConverter
|
java
|
spring-projects__spring-framework
|
spring-beans/src/main/java/org/springframework/beans/factory/xml/PluggableSchemaResolver.java
|
{
"start": 1488,
"end": 2265
}
|
class ____ look for mapping files in the classpath using the
* pattern: {@code META-INF/spring.schemas} allowing for multiple files to exist on
* the classpath at any one time.
*
* <p>The format of {@code META-INF/spring.schemas} is a properties file where each line
* should be of the form {@code systemId=schema-location} where {@code schema-location}
* should also be a schema file in the classpath. Since {@code systemId} is commonly a
* URL, one must be careful to escape any ':' characters which are treated as delimiters
* in properties files.
*
* <p>The pattern for the mapping files can be overridden using the
* {@link #PluggableSchemaResolver(ClassLoader, String)} constructor.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
*/
public
|
will
|
java
|
apache__camel
|
components/camel-digitalocean/src/main/java/org/apache/camel/component/digitalocean/producer/DigitalOceanActionsProducer.java
|
{
"start": 1450,
"end": 3106
}
|
class ____ extends DigitalOceanProducer {
public DigitalOceanActionsProducer(DigitalOceanEndpoint endpoint, DigitalOceanConfiguration configuration) {
super(endpoint, configuration);
}
@Override
public void process(Exchange exchange) throws Exception {
switch (determineOperation(exchange)) {
case list:
getActions(exchange);
break;
case get:
getAction(exchange);
break;
default:
throw new IllegalArgumentException("Unsupported operation");
}
}
private void getAction(Exchange exchange) throws RequestUnsuccessfulException, DigitalOceanException {
Integer actionId = exchange.getIn().getHeader(DigitalOceanHeaders.ID, Integer.class);
if (ObjectHelper.isEmpty(actionId)) {
throw new IllegalArgumentException(DigitalOceanHeaders.ID + " must be specified");
}
Action action = getEndpoint().getDigitalOceanClient().getActionInfo(actionId);
LOG.trace("Action [{}] ", action);
exchange.getMessage().setBody(action);
}
private void getActions(Exchange exchange) throws RequestUnsuccessfulException, DigitalOceanException {
Actions actions = getEndpoint().getDigitalOceanClient().getAvailableActions(configuration.getPage(),
configuration.getPerPage());
LOG.trace("All Actions : page {} / {} per page [{}] ", configuration.getPage(), configuration.getPerPage(),
actions.getActions());
exchange.getMessage().setBody(actions.getActions());
}
}
|
DigitalOceanActionsProducer
|
java
|
apache__spark
|
launcher/src/main/java/org/apache/spark/launcher/SparkLauncher.java
|
{
"start": 2182,
"end": 2414
}
|
class ____. */
public static final String DRIVER_DEFAULT_EXTRA_CLASS_PATH =
"spark.driver.defaultExtraClassPath";
public static final String DRIVER_DEFAULT_EXTRA_CLASS_PATH_VALUE = "";
/** Configuration key for the driver
|
path
|
java
|
apache__camel
|
components/camel-olingo2/camel-olingo2-component/src/generated/java/org/apache/camel/component/olingo2/internal/Olingo2ApiCollection.java
|
{
"start": 627,
"end": 1915
}
|
class ____ extends ApiCollection<Olingo2ApiName, Olingo2Configuration> {
private Olingo2ApiCollection() {
final Map<String, String> aliases = new HashMap<>();
final Map<Olingo2ApiName, ApiMethodHelper<? extends ApiMethod>> apiHelpers = new EnumMap<>(Olingo2ApiName.class);
final Map<Class<? extends ApiMethod>, Olingo2ApiName> apiMethods = new HashMap<>();
List<String> nullableArgs;
aliases.clear();
nullableArgs = Arrays.asList("queryParams", "endpointHttpHeaders", "edm", "responseHandler");
apiHelpers.put(Olingo2ApiName.DEFAULT, new ApiMethodHelper<>(Olingo2AppApiMethod.class, aliases, nullableArgs));
apiMethods.put(Olingo2AppApiMethod.class, Olingo2ApiName.DEFAULT);
setApiHelpers(apiHelpers);
setApiMethods(apiMethods);
}
public Olingo2Configuration getEndpointConfiguration(Olingo2ApiName apiName) {
Olingo2Configuration result = null;
switch (apiName) {
case DEFAULT:
result = new Olingo2AppEndpointConfiguration();
break;
}
return result;
}
public static Olingo2ApiCollection getCollection() {
return Olingo2ApiCollectionHolder.INSTANCE;
}
private static final
|
Olingo2ApiCollection
|
java
|
spring-projects__spring-boot
|
core/spring-boot-test/src/test/java/org/springframework/boot/test/json/Jackson2TesterTests.java
|
{
"start": 2668,
"end": 3040
}
|
class ____ {
public org.springframework.boot.test.json.@Nullable Jackson2Tester<ExampleObject> base;
public org.springframework.boot.test.json.Jackson2Tester<ExampleObject> baseSet = new org.springframework.boot.test.json.Jackson2Tester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class), new ObjectMapper());
}
static
|
InitFieldsBaseClass
|
java
|
spring-projects__spring-framework
|
spring-test/src/main/java/org/springframework/test/context/support/DefaultBootstrapContext.java
|
{
"start": 1440,
"end": 1811
}
|
class ____ this bootstrap context; never {@code null}
* @param cacheAwareContextLoaderDelegate the context loader delegate to use for
* transparent interaction with the {@code ContextCache}; never {@code null}
*/
public DefaultBootstrapContext(Class<?> testClass, CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate) {
Assert.notNull(testClass, "Test
|
for
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/spec/IntervalJoinSpec.java
|
{
"start": 1672,
"end": 3097
}
|
class ____ {
public static final String FIELD_NAME_WINDOW_BOUNDS = "windowBounds";
public static final String FIELD_NAME_JOIN_SPEC = "joinSpec";
@JsonProperty(FIELD_NAME_WINDOW_BOUNDS)
private final WindowBounds windowBounds;
@JsonProperty(FIELD_NAME_JOIN_SPEC)
private final JoinSpec joinSpec;
@JsonCreator
public IntervalJoinSpec(
@JsonProperty(FIELD_NAME_JOIN_SPEC) JoinSpec joinSpec,
@JsonProperty(FIELD_NAME_WINDOW_BOUNDS) WindowBounds windowBounds) {
this.windowBounds = windowBounds;
this.joinSpec = joinSpec;
}
@JsonIgnore
public WindowBounds getWindowBounds() {
return windowBounds;
}
@JsonIgnore
public JoinSpec getJoinSpec() {
return joinSpec;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
IntervalJoinSpec that = (IntervalJoinSpec) o;
return Objects.equals(windowBounds, that.windowBounds)
&& Objects.equals(joinSpec, that.joinSpec);
}
@Override
public int hashCode() {
return Objects.hash(windowBounds, joinSpec);
}
/** WindowBounds describes the time range condition of a Interval Join. */
@JsonIgnoreProperties(ignoreUnknown = true)
public static
|
IntervalJoinSpec
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_hasHour_Test.java
|
{
"start": 1054,
"end": 1918
}
|
class ____ {
@Test
void should_pass_if_actual_is_in_given_hour() {
// GIVEN
LocalTime actual = LocalTime.of(23, 59, 59);
// WHEN/THEN
then(actual).hasHour(23);
}
@Test
void should_fail_if_actual_is_not_in_given_hour() {
// GIVEN
LocalTime actual = LocalTime.of(23, 59, 59);
int expectedHour = 22;
// WHEN
var assertionError = expectAssertionError(() -> assertThat(actual).hasHour(expectedHour));
// THEN
then(assertionError).hasMessage(shouldHaveDateField(actual, "hour", expectedHour).create());
}
@Test
void should_fail_if_actual_is_null() {
// GIVEN
LocalTime actual = null;
// WHEN
var assertionError = expectAssertionError(() -> assertThat(actual).hasHour(LocalTime.now().getHour()));
// THEN
then(assertionError).hasMessage(actualIsNull());
}
}
|
LocalTimeAssert_hasHour_Test
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/SpringManagedStatisticsLevelRoutesOnlyTest.java
|
{
"start": 1177,
"end": 1490
}
|
class ____ extends ManagedStatisticsLevelRoutesOnlyTest {
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this, "org/apache/camel/spring/management/ManagedStatisticsLevelRoutesOnlyTest.xml");
}
}
|
SpringManagedStatisticsLevelRoutesOnlyTest
|
java
|
quarkusio__quarkus
|
extensions/hibernate-search-orm-elasticsearch/runtime-dev/src/main/java/io/quarkus/hibernate/search/orm/elasticsearch/runtime/dev/HibernateSearchElasticsearchDevInfo.java
|
{
"start": 1445,
"end": 2071
}
|
class ____ implements Comparable<PersistenceUnit> {
public final String name;
public final List<IndexedEntity> indexedEntities;
public PersistenceUnit(String name, List<IndexedEntity> indexedEntities) {
this.name = name;
this.indexedEntities = indexedEntities;
}
@Deprecated // Only useful for the legacy Dev UI
public String getPersistenceUnitName() {
return name;
}
@Override
public int compareTo(PersistenceUnit o) {
return this.name.compareTo(o.name);
}
}
public static
|
PersistenceUnit
|
java
|
quarkusio__quarkus
|
independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/config/RegistryMavenRepoConfigImpl.java
|
{
"start": 733,
"end": 1796
}
|
class ____ implements RegistryMavenRepoConfig {
private final String id;
private final String url;
private RegistryMavenRepoConfigImpl(String id, String url) {
this.id = id;
this.url = url;
}
@Override
public String getId() {
return id;
}
@Override
public String getUrl() {
return url;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
RegistryMavenRepoConfigImpl that = (RegistryMavenRepoConfigImpl) o;
return Objects.equals(id, that.id) && Objects.equals(url, that.url);
}
@Override
public int hashCode() {
return Objects.hash(id, url);
}
@Override
public String toString() {
return "BaseRegistryMavenRepoConfig{" +
"id='" + id + '\'' +
", url='" + url + '\'' +
'}';
}
/**
* Builder.
*/
public static
|
RegistryMavenRepoConfigImpl
|
java
|
google__guava
|
android/guava/src/com/google/common/util/concurrent/ClosingFuture.java
|
{
"start": 84922,
"end": 85742
}
|
class ____<
V1 extends @Nullable Object,
V2 extends @Nullable Object,
V3 extends @Nullable Object,
V4 extends @Nullable Object,
V5 extends @Nullable Object>
extends Combiner {
/**
* A function that returns a value when applied to the values of the five futures passed to
* {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture, ClosingFuture,
* ClosingFuture)}.
*
* @param <V1> the type returned by the first future
* @param <V2> the type returned by the second future
* @param <V3> the type returned by the third future
* @param <V4> the type returned by the fourth future
* @param <V5> the type returned by the fifth future
* @param <U> the type returned by the function
*/
public
|
Combiner5
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/core/plugin/DirectoryBasedPluginFinderTest.java
|
{
"start": 1535,
"end": 4676
}
|
class ____ {
@TempDir private static java.nio.file.Path tempFolder;
@Test
void createPluginDescriptorsForDirectory() throws Exception {
File rootFolder = TempDirUtils.newFolder(tempFolder);
PluginFinder descriptorsFactory = new DirectoryBasedPluginFinder(rootFolder.toPath());
Collection<PluginDescriptor> actual = descriptorsFactory.findPlugins();
assertThat(actual).isEmpty();
List<File> subDirs =
Stream.of("A", "B", "C")
.map(s -> new File(rootFolder, s))
.collect(Collectors.toList());
for (File subDir : subDirs) {
Preconditions.checkState(subDir.mkdirs());
}
assertThatThrownBy(descriptorsFactory::findPlugins)
.isInstanceOf(RuntimeException.class)
.hasCauseInstanceOf(IOException.class);
for (File subDir : subDirs) {
// we create a file and another subfolder to check that they are ignored
Preconditions.checkState(new File(subDir, "ignore-test.zip").createNewFile());
Preconditions.checkState(new File(subDir, "ignore-dir").mkdirs());
}
assertThatThrownBy(descriptorsFactory::findPlugins)
.isInstanceOf(RuntimeException.class)
.hasCauseInstanceOf(IOException.class);
List<PluginDescriptor> expected = new ArrayList<>(3);
for (int i = 0; i < subDirs.size(); ++i) {
File subDir = subDirs.get(i);
URL[] jarURLs = new URL[i + 1];
for (int j = 0; j <= i; ++j) {
File file = new File(subDir, "jar-file-" + j + ".jar");
Preconditions.checkState(file.createNewFile());
jarURLs[j] = file.toURI().toURL();
}
Arrays.sort(jarURLs, Comparator.comparing(URL::toString));
expected.add(new PluginDescriptor(subDir.getName(), jarURLs, new String[0]));
}
actual = descriptorsFactory.findPlugins();
assertThat(equalsIgnoreOrder(expected, new ArrayList<>(actual))).isTrue();
}
private boolean equalsIgnoreOrder(List<PluginDescriptor> a, List<PluginDescriptor> b) {
if (a.size() != b.size()) {
return false;
}
final Comparator<PluginDescriptor> comparator =
Comparator.comparing(PluginDescriptor::getPluginId);
a.sort(comparator);
b.sort(comparator);
final Iterator<PluginDescriptor> iterA = a.iterator();
final Iterator<PluginDescriptor> iterB = b.iterator();
while (iterA.hasNext()) {
if (!equals(iterA.next(), iterB.next())) {
return false;
}
}
return true;
}
private static boolean equals(@Nonnull PluginDescriptor a, @Nonnull PluginDescriptor b) {
return a.getPluginId().equals(b.getPluginId())
&& Arrays.deepEquals(a.getPluginResourceURLs(), b.getPluginResourceURLs())
&& Arrays.deepEquals(a.getLoaderExcludePatterns(), b.getLoaderExcludePatterns());
}
}
|
DirectoryBasedPluginFinderTest
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskManagerRunnerTest.java
|
{
"start": 12670,
"end": 13946
}
|
class ____
implements TaskManagerRunner.TaskExecutorServiceFactory {
@Override
public TaskManagerRunner.TaskExecutorService createTaskExecutor(
Configuration configuration,
ResourceID resourceID,
RpcService rpcService,
HighAvailabilityServices highAvailabilityServices,
HeartbeatServices heartbeatServices,
MetricRegistry metricRegistry,
BlobCacheService blobCacheService,
boolean localCommunicationOnly,
ExternalResourceInfoProvider externalResourceInfoProvider,
WorkingDirectory workingDirectory,
FatalErrorHandler fatalErrorHandler,
DelegationTokenReceiverRepository delegationTokenReceiverRepository) {
return TestingTaskExecutorService.newBuilder()
.setStartRunnable(
() ->
fatalErrorHandler.onFatalError(
new FlinkException(
"Cannot instantiate the TaskExecutorService.")))
.build();
}
}
}
|
TestingFailingTaskExecutorServiceFactory
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/Flight.java
|
{
"start": 464,
"end": 1455
}
|
class ____ {
@Id
private Integer id;
@Column( name = "flight_number" )
private String number;
@ManyToOne( fetch = LAZY )
private Airport origination;
@ManyToOne( fetch = LAZY )
private Airport destination;
public Flight() {
}
public Flight(Integer id, String number) {
this.id = id;
this.number = number;
}
public Flight(Integer id, String number, Airport origination, Airport destination) {
this.id = id;
this.number = number;
this.origination = origination;
this.destination = destination;
}
public Integer getId() {
return id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Airport getOrigination() {
return origination;
}
public void setOrigination(Airport origination) {
this.origination = origination;
}
public Airport getDestination() {
return destination;
}
public void setDestination(Airport destination) {
this.destination = destination;
}
}
|
Flight
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/mock/MockRef.java
|
{
"start": 730,
"end": 1365
}
|
class ____ implements Ref {
private String baseTypeName;
private Object object;
public void setBaseTypeName(String baseTypeName) {
this.baseTypeName = baseTypeName;
}
@Override
public String getBaseTypeName() throws SQLException {
return baseTypeName;
}
@Override
public Object getObject(Map<String, Class<?>> map) throws SQLException {
return object;
}
@Override
public Object getObject() throws SQLException {
return object;
}
@Override
public void setObject(Object value) throws SQLException {
this.object = value;
}
}
|
MockRef
|
java
|
google__dagger
|
hilt-compiler/main/java/dagger/hilt/android/processor/internal/bindvalue/BindValueGenerator.java
|
{
"start": 2552,
"end": 6696
}
|
class ____ {
// // providesMethods ...
// }
void generate() throws IOException {
TypeSpec.Builder builder = TypeSpec.classBuilder(className);
JavaPoetExtKt.addOriginatingElement(builder, metadata.testElement())
.addAnnotation(Processors.getOriginatingElementAnnotation(metadata.testElement()))
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addAnnotation(Module.class)
.addAnnotation(
Components.getInstallInAnnotationSpec(ImmutableSet.of(ClassNames.SINGLETON_COMPONENT)))
.addMethod(providesTestMethod());
Processors.addGeneratedAnnotation(builder, env, getClass());
metadata.bindValueElements().stream()
.map(this::providesMethod)
.sorted(comparing(MethodSpec::toString))
.forEachOrdered(builder::addMethod);
env.getFiler()
.write(JavaFile.builder(className.packageName(), builder.build()).build(), Mode.Isolating);
}
// @Provides
// static FooTest providesFooTest(@ApplicationContext Context context) {
// return (FooTest)
// ((TestApplicationComponentManager)
// ((TestApplicationComponentManagerHolder) context).componentManager())
// .getTestInstance();
// }
private MethodSpec providesTestMethod() {
String methodName = "provides" + testClassName.simpleName();
MethodSpec.Builder builder =
MethodSpec.methodBuilder(methodName)
.addAnnotation(Provides.class)
.addModifiers(Modifier.STATIC)
.addParameter(
ParameterSpec.builder(ClassNames.CONTEXT, "context")
.addAnnotation(ClassNames.APPLICATION_CONTEXT)
.build())
.returns(testClassName)
.addStatement(
"return ($T) (($T) (($T) context).componentManager()).getTestInstance()",
testClassName,
ClassNames.TEST_APPLICATION_COMPONENT_MANAGER,
ClassNames.TEST_APPLICATION_COMPONENT_MANAGER_HOLDER);
return builder.build();
}
// @Provides
// @BarQualifier
// static Bar providesBarQualifierBar(FooTest test) {
// return test.bar;
// }
private MethodSpec providesMethod(BindValueElement bindValue) {
// We only allow fields in the Test class, which should have unique variable names.
String methodName =
"provides" + LOWER_CAMEL.to(UPPER_CAMEL, bindValue.fieldElement().getName());
MethodSpec.Builder builder =
MethodSpec.methodBuilder(methodName)
.addAnnotation(Provides.class)
.addModifiers(Modifier.STATIC)
.returns(bindValue.fieldElement().getType().getTypeName());
if (XElements.isStatic(bindValue.fieldElement())) {
builder.addStatement("return $T.$L", testClassName, bindValue.fieldElement().getName());
} else {
builder
.addParameter(testClassName, "test")
.addStatement(
"return $L",
bindValue.getterElement().isPresent()
? CodeBlock.of("test.$L()", bindValue.getterElement().get().getJvmName())
: CodeBlock.of("test.$L", bindValue.fieldElement().getName()));
}
ClassName annotationClassName = bindValue.annotationName();
if (BindValueMetadata.BIND_VALUE_INTO_MAP_ANNOTATIONS.contains(annotationClassName)) {
builder.addAnnotation(IntoMap.class);
// It is safe to call get() on the Optional<AnnotationMirror> returned by mapKey()
// because a @BindValueIntoMap is required to have one and is checked in
// BindValueMetadata.BindValueElement.create().
builder.addAnnotation(XAnnotations.getAnnotationSpec(bindValue.mapKey().get()));
} else if (BindValueMetadata.BIND_VALUE_INTO_SET_ANNOTATIONS.contains(annotationClassName)) {
builder.addAnnotation(IntoSet.class);
} else if (BindValueMetadata.BIND_ELEMENTS_INTO_SET_ANNOTATIONS.contains(annotationClassName)) {
builder.addAnnotation(ElementsIntoSet.class);
}
bindValue.qualifier().ifPresent(q -> builder.addAnnotation(XAnnotations.getAnnotationSpec(q)));
return builder.build();
}
}
|
FooTest_BindValueModule
|
java
|
quarkusio__quarkus
|
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/config/unsupportedproperties/UnsupportedPropertiesTest.java
|
{
"start": 8219,
"end": 8903
}
|
class ____ {
@Id
private Long id;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<ChildEntity> children = new ArrayList<>();
public ParentEntity() {
}
public ParentEntity(long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<ChildEntity> getChildren() {
return children;
}
public void setChildren(List<ChildEntity> children) {
this.children = children;
}
}
@Entity
public static
|
ParentEntity
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/jsontype/SealedTypesWithJsonTypeInfoSimpleClassName4061Test.java
|
{
"start": 9243,
"end": 9383
}
|
class ____
extends SealedTypesWithJsonTypeInfoSimpleClassName4061Test.MixedMinimalSuper4061 {
}
final
|
MixedMinimalSub4061AForSealedClasses
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/ValuesDoubleAggregatorFunctionSupplier.java
|
{
"start": 651,
"end": 1625
}
|
class ____ implements AggregatorFunctionSupplier {
public ValuesDoubleAggregatorFunctionSupplier() {
}
@Override
public List<IntermediateStateDesc> nonGroupingIntermediateStateDesc() {
return ValuesDoubleAggregatorFunction.intermediateStateDesc();
}
@Override
public List<IntermediateStateDesc> groupingIntermediateStateDesc() {
return ValuesDoubleGroupingAggregatorFunction.intermediateStateDesc();
}
@Override
public ValuesDoubleAggregatorFunction aggregator(DriverContext driverContext,
List<Integer> channels) {
return ValuesDoubleAggregatorFunction.create(driverContext, channels);
}
@Override
public ValuesDoubleGroupingAggregatorFunction groupingAggregator(DriverContext driverContext,
List<Integer> channels) {
return ValuesDoubleGroupingAggregatorFunction.create(channels, driverContext);
}
@Override
public String describe() {
return "values of doubles";
}
}
|
ValuesDoubleAggregatorFunctionSupplier
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/common/errors/ControllerMovedException.java
|
{
"start": 847,
"end": 1152
}
|
class ____ extends ApiException {
private static final long serialVersionUID = 1L;
public ControllerMovedException(String message) {
super(message);
}
public ControllerMovedException(String message, Throwable cause) {
super(message, cause);
}
}
|
ControllerMovedException
|
java
|
bumptech__glide
|
library/test/src/test/java/com/bumptech/glide/request/target/ViewTargetTest.java
|
{
"start": 21916,
"end": 22197
}
|
class ____ extends ViewTarget<View, Object> {
AttachStateTarget(View view) {
super(view);
}
@Override
public void onResourceReady(
@NonNull Object resource, @Nullable Transition<? super Object> transition) {}
}
private static final
|
AttachStateTarget
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/test/codec/FastjsonSCodec.java
|
{
"start": 620,
"end": 3133
}
|
class ____ implements Codec {
public FastjsonSCodec(){
System.out.println("fastjson-" + JSON.VERSION);
}
public String getName() {
return "fastjsonS";
}
public <T> T decodeObject(String text, Class<T> clazz) {
ParserConfig config = new ParserConfig();
DefaultJSONParser parser = new DefaultJSONParser(text, config);
parser.config(Feature.DisableCircularReferenceDetect, true);
return parser.parseObject(clazz);
}
public <T> Collection<T> decodeArray(String text, Class<T> clazz) throws Exception {
ParserConfig config = new ParserConfig();
DefaultJSONParser parser = new DefaultJSONParser(text, config);
parser.config(Feature.DisableCircularReferenceDetect, true);
return parser.parseArray(clazz);
}
public final Object decodeObject(String text) {
ParserConfig config = new ParserConfig();
DefaultJSONParser parser = new DefaultJSONParser(text, config);
parser.config(Feature.DisableCircularReferenceDetect, true);
return parser.parse();
}
public final Object decode(String text) {
ParserConfig config = new ParserConfig();
DefaultJSONParser parser = new DefaultJSONParser(text, config);
parser.config(Feature.DisableCircularReferenceDetect, true);
return parser.parse();
}
// private JavaBeanSerializer serializer = new JavaBeanSerializer(Long_100_Entity.class);
public String encode(Object object) throws Exception {
SerializeConfig config = new SerializeConfig();
SerializeWriter out = new SerializeWriter();
out.config(SerializerFeature.DisableCircularReferenceDetect, true);
// out.config(SerializerFeature.DisableCheckSpecialChar, true);
JSONSerializer serializer = new JSONSerializer(out, config);
serializer.write(object);
String text = out.toString();
out.close();
return text;
}
@SuppressWarnings("unchecked")
public <T> T decodeObject(byte[] input, Class<T> clazz) throws Exception {
return (T) JSON.parseObject(input, clazz, Feature.DisableCircularReferenceDetect);
}
@Override
public byte[] encodeToBytes(Object object) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public void encode(OutputStream out, Object object) throws Exception {
out.write(encodeToBytes(object));
}
}
|
FastjsonSCodec
|
java
|
junit-team__junit5
|
junit-jupiter-params/src/main/java/org/junit/jupiter/params/ParameterizedTest.java
|
{
"start": 6308,
"end": 10971
}
|
interface ____ {
/**
* See {@link ParameterizedInvocationConstants#DISPLAY_NAME_PLACEHOLDER}.
*
* @since 5.3
* @see #name
* @deprecated Please reference
* {@link ParameterizedInvocationConstants#DISPLAY_NAME_PLACEHOLDER}
* instead.
*/
@API(status = DEPRECATED, since = "5.13")
@Deprecated(since = "5.13")
String DISPLAY_NAME_PLACEHOLDER = ParameterizedInvocationConstants.DISPLAY_NAME_PLACEHOLDER;
/**
* See {@link ParameterizedInvocationConstants#INDEX_PLACEHOLDER}.
*
* @since 5.3
* @see #name
* @see ParameterizedInvocationConstants#DEFAULT_DISPLAY_NAME
* @deprecated Please reference
* {@link ParameterizedInvocationConstants#INDEX_PLACEHOLDER} instead.
*/
@API(status = DEPRECATED, since = "5.13")
@Deprecated(since = "5.13")
String INDEX_PLACEHOLDER = ParameterizedInvocationConstants.INDEX_PLACEHOLDER;
/**
* See {@link ParameterizedInvocationConstants#ARGUMENTS_PLACEHOLDER}.
*
* @since 5.3
* @see #name
* @deprecated Please reference
* {@link ParameterizedInvocationConstants#ARGUMENTS_PLACEHOLDER} instead.
*/
@API(status = DEPRECATED, since = "5.13")
@Deprecated(since = "5.13")
String ARGUMENTS_PLACEHOLDER = ParameterizedInvocationConstants.ARGUMENTS_PLACEHOLDER;
/**
* See
* {@link ParameterizedInvocationConstants#ARGUMENTS_WITH_NAMES_PLACEHOLDER}.
*
* @since 5.6
* @see #name
* @see ParameterizedInvocationConstants#ARGUMENT_SET_NAME_OR_ARGUMENTS_WITH_NAMES_PLACEHOLDER
* @deprecated Please reference
* {@link ParameterizedInvocationConstants#ARGUMENTS_WITH_NAMES_PLACEHOLDER}
* instead.
*/
@API(status = DEPRECATED, since = "5.13")
@Deprecated(since = "5.13")
String ARGUMENTS_WITH_NAMES_PLACEHOLDER = ParameterizedInvocationConstants.ARGUMENTS_WITH_NAMES_PLACEHOLDER;
/**
* See
* {@link ParameterizedInvocationConstants#ARGUMENT_SET_NAME_PLACEHOLDER}.
*
* @since 5.11
* @see #name
* @see ParameterizedInvocationConstants#ARGUMENT_SET_NAME_OR_ARGUMENTS_WITH_NAMES_PLACEHOLDER
* @see org.junit.jupiter.params.provider.Arguments#argumentSet(String, Object...)
* @deprecated Please reference
* {@link ParameterizedInvocationConstants#ARGUMENT_SET_NAME_PLACEHOLDER}
* instead.
*/
@API(status = DEPRECATED, since = "5.13")
@Deprecated(since = "5.13")
String ARGUMENT_SET_NAME_PLACEHOLDER = ParameterizedInvocationConstants.ARGUMENT_SET_NAME_PLACEHOLDER;
/**
* See
* {@link ParameterizedInvocationConstants#ARGUMENT_SET_NAME_OR_ARGUMENTS_WITH_NAMES_PLACEHOLDER}.
*
* @since 5.11
* @see #name
* @see ParameterizedInvocationConstants#ARGUMENT_SET_NAME_PLACEHOLDER
* @see ParameterizedInvocationConstants#ARGUMENTS_WITH_NAMES_PLACEHOLDER
* @see ParameterizedInvocationConstants#DEFAULT_DISPLAY_NAME
* @see org.junit.jupiter.params.provider.Arguments#argumentSet(String, Object...)
* @deprecated Please reference
* {@link ParameterizedInvocationConstants#ARGUMENT_SET_NAME_OR_ARGUMENTS_WITH_NAMES_PLACEHOLDER}
* instead.
*/
@API(status = DEPRECATED, since = "5.13")
@Deprecated(since = "5.13")
String ARGUMENT_SET_NAME_OR_ARGUMENTS_WITH_NAMES_PLACEHOLDER = //
ParameterizedInvocationConstants.ARGUMENT_SET_NAME_OR_ARGUMENTS_WITH_NAMES_PLACEHOLDER;
/**
* See
* {@link ParameterizedInvocationConstants#DEFAULT_DISPLAY_NAME}.
*
* @since 5.3
* @see #name
* @see ParameterizedInvocationConstants#DISPLAY_NAME_PLACEHOLDER
* @see ParameterizedInvocationConstants#INDEX_PLACEHOLDER
* @see ParameterizedInvocationConstants#ARGUMENT_SET_NAME_OR_ARGUMENTS_WITH_NAMES_PLACEHOLDER
* @deprecated Please reference
* {@link ParameterizedInvocationConstants#DEFAULT_DISPLAY_NAME} instead.
*/
@API(status = DEPRECATED, since = "5.13")
@Deprecated(since = "5.13")
String DEFAULT_DISPLAY_NAME = ParameterizedInvocationConstants.DEFAULT_DISPLAY_NAME;
/**
* The display name to be used for individual invocations of the
* parameterized test; never blank or consisting solely of whitespace.
*
* <p>Defaults to <code>{@value ParameterizedInvocationNameFormatter#DEFAULT_DISPLAY_NAME}</code>.
*
* <p>If the default display name flag
* (<code>{@value ParameterizedInvocationNameFormatter#DEFAULT_DISPLAY_NAME}</code>)
* is not overridden, JUnit will:
* <ul>
* <li>Look up the {@value ParameterizedInvocationNameFormatter#DISPLAY_NAME_PATTERN_KEY}
* <em>configuration parameter</em> and use it if available. The configuration
* parameter can be supplied via the {@code Launcher} API, build tools (e.g.,
* Gradle and Maven), a JVM system property, or the JUnit Platform configuration
* file (i.e., a file named {@code junit-platform.properties} in the root of
* the
|
ParameterizedTest
|
java
|
apache__camel
|
dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/TransformTest.java
|
{
"start": 1332,
"end": 3521
}
|
class ____ {
private Path workingDir;
@BeforeEach
public void setup() throws IOException {
Path base = Paths.get("target");
workingDir = Files.createTempDirectory(base, "camel-transform");
}
@AfterEach
public void end() throws IOException {
// force removing, since deleteOnExit is not removing.
PathUtils.deleteDirectory(workingDir);
}
@Test
public void shouldTransformToYaml() throws Exception {
Path outPath = workingDir.resolve("transform.yaml");
String[] args = new String[] { "--output=" + outPath.toString() };
TransformRoute command = createCommand(new String[] { "src/test/resources/transform.xml" }, args);
int exit = command.doCall();
Assertions.assertEquals(0, exit);
Assertions.assertTrue(Files.exists(outPath));
String data = Files.readString(outPath);
String expected
= IOHelper.stripLineComments(Paths.get("src/test/resources/transform-out.yaml"), "#", true);
Assertions.assertEquals(expected, data);
}
@Test
public void shouldTransformBlueprintToYaml() throws Exception {
Path outPath = workingDir.resolve("blueprint.yaml");
String[] args = new String[] { "--output=" + outPath.toString() };
TransformRoute command = createCommand(new String[] { "src/test/resources/blueprint.xml" }, args);
int exit = command.doCall();
Assertions.assertEquals(0, exit);
Assertions.assertTrue(Files.exists(outPath));
String data = Files.readString(outPath);
String expected
= IOHelper.stripLineComments(Paths.get("src/test/resources/blueprint-out.yaml"), "#", true);
assertThat(data).isEqualToIgnoringNewLines(expected);
}
private TransformRoute createCommand(String[] files, String... args) {
TransformRoute command = new TransformRoute(new CamelJBangMain());
CommandLine.populateCommand(command, "--format=yaml");
if (args != null) {
CommandLine.populateCommand(command, args);
}
command.files = Arrays.asList(files);
return command;
}
}
|
TransformTest
|
java
|
apache__rocketmq
|
proxy/src/test/java/org/apache/rocketmq/proxy/service/sysmessage/HeartbeatSyncerTest.java
|
{
"start": 4482,
"end": 21619
}
|
class ____ extends InitConfigTest {
@Mock
private TopicRouteService topicRouteService;
@Mock
private AdminService adminService;
@Mock
private ConsumerManager consumerManager;
@Mock
private MQClientAPIFactory mqClientAPIFactory;
@Mock
private MQClientAPIExt mqClientAPIExt;
@Mock
private ProxyRelayService proxyRelayService;
private String clientId;
private final String remoteAddress = "10.152.39.53:9768";
private final String localAddress = "11.193.0.1:1210";
private final String clusterName = "cluster";
private final String brokerName = "broker-01";
@Before
public void before() throws Throwable {
super.before();
this.clientId = RandomStringUtils.randomAlphabetic(10);
when(mqClientAPIFactory.getClient()).thenReturn(mqClientAPIExt);
{
TopicRouteData topicRouteData = new TopicRouteData();
QueueData queueData = new QueueData();
queueData.setReadQueueNums(8);
queueData.setWriteQueueNums(8);
queueData.setPerm(6);
queueData.setBrokerName(brokerName);
topicRouteData.getQueueDatas().add(queueData);
BrokerData brokerData = new BrokerData();
brokerData.setCluster(clusterName);
brokerData.setBrokerName(brokerName);
HashMap<Long, String> brokerAddr = new HashMap<>();
brokerAddr.put(0L, "127.0.0.1:10911");
brokerData.setBrokerAddrs(brokerAddr);
topicRouteData.getBrokerDatas().add(brokerData);
MessageQueueView messageQueueView = new MessageQueueView("foo", topicRouteData, null);
when(this.topicRouteService.getAllMessageQueueView(any(), anyString())).thenReturn(messageQueueView);
}
}
@Test
public void testSyncGrpcV2Channel() throws Exception {
String consumerGroup = "consumerGroup";
GrpcClientSettingsManager grpcClientSettingsManager = mock(GrpcClientSettingsManager.class);
GrpcChannelManager grpcChannelManager = mock(GrpcChannelManager.class);
GrpcClientChannel grpcClientChannel = new GrpcClientChannel(
proxyRelayService, grpcClientSettingsManager, grpcChannelManager,
ProxyContext.create().setRemoteAddress(remoteAddress).setLocalAddress(localAddress),
clientId);
ClientChannelInfo clientChannelInfo = new ClientChannelInfo(
grpcClientChannel,
clientId,
LanguageCode.JAVA,
5
);
ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
SendResult sendResult = new SendResult();
sendResult.setSendStatus(SendStatus.SEND_OK);
doReturn(CompletableFuture.completedFuture(sendResult)).when(this.mqClientAPIExt)
.sendMessageAsync(anyString(), anyString(), messageArgumentCaptor.capture(), any(), anyLong());
Settings settings = Settings.newBuilder()
.setSubscription(Subscription.newBuilder()
.addSubscriptions(SubscriptionEntry.newBuilder()
.setTopic(Resource.newBuilder().setName("topic").build())
.setExpression(FilterExpression.newBuilder()
.setType(FilterType.TAG)
.setExpression("tag")
.build())
.build())
.build())
.build();
when(grpcClientSettingsManager.getRawClientSettings(eq(clientId))).thenReturn(settings);
HeartbeatSyncer heartbeatSyncer = new HeartbeatSyncer(topicRouteService, adminService, consumerManager, mqClientAPIFactory, null);
heartbeatSyncer.onConsumerRegister(
consumerGroup,
clientChannelInfo,
ConsumeType.CONSUME_PASSIVELY,
MessageModel.CLUSTERING,
ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET,
Sets.newHashSet(FilterAPI.buildSubscriptionData("topic", "tag"))
);
await().atMost(Duration.ofSeconds(3)).until(() -> !messageArgumentCaptor.getAllValues().isEmpty());
heartbeatSyncer.consumeMessage(Lists.newArrayList(convertFromMessage(messageArgumentCaptor.getValue())), null);
verify(consumerManager, never()).registerConsumer(anyString(), any(), any(), any(), any(), any(), anyBoolean());
String localServeAddr = ConfigurationManager.getProxyConfig().getLocalServeAddr();
// change local serve addr, to simulate other proxy receive messages
heartbeatSyncer.localProxyId = RandomStringUtils.randomAlphabetic(10);
ArgumentCaptor<ClientChannelInfo> syncChannelInfoArgumentCaptor = ArgumentCaptor.forClass(ClientChannelInfo.class);
doReturn(true).when(consumerManager).registerConsumer(anyString(), syncChannelInfoArgumentCaptor.capture(), any(), any(), any(), any(), anyBoolean());
heartbeatSyncer.consumeMessage(Lists.newArrayList(convertFromMessage(messageArgumentCaptor.getValue())), null);
heartbeatSyncer.consumeMessage(Lists.newArrayList(convertFromMessage(messageArgumentCaptor.getValue())), null);
assertEquals(2, syncChannelInfoArgumentCaptor.getAllValues().size());
List<ClientChannelInfo> channelInfoList = syncChannelInfoArgumentCaptor.getAllValues();
assertSame(channelInfoList.get(0).getChannel(), channelInfoList.get(1).getChannel());
assertEquals(settings, GrpcClientChannel.parseChannelExtendAttribute(channelInfoList.get(0).getChannel()));
assertEquals(settings, GrpcClientChannel.parseChannelExtendAttribute(channelInfoList.get(1).getChannel()));
// start test sync client unregister
// reset localServeAddr
ConfigurationManager.getProxyConfig().setLocalServeAddr(localServeAddr);
heartbeatSyncer.onConsumerUnRegister(consumerGroup, clientChannelInfo);
await().atMost(Duration.ofSeconds(3)).until(() -> messageArgumentCaptor.getAllValues().size() == 2);
ArgumentCaptor<ClientChannelInfo> syncUnRegisterChannelInfoArgumentCaptor = ArgumentCaptor.forClass(ClientChannelInfo.class);
doNothing().when(consumerManager).unregisterConsumer(anyString(), syncUnRegisterChannelInfoArgumentCaptor.capture(), anyBoolean());
// change local serve addr, to simulate other proxy receive messages
heartbeatSyncer.localProxyId = RandomStringUtils.randomAlphabetic(10);
heartbeatSyncer.consumeMessage(Lists.newArrayList(convertFromMessage(messageArgumentCaptor.getAllValues().get(1))), null);
assertSame(channelInfoList.get(0).getChannel(), syncUnRegisterChannelInfoArgumentCaptor.getValue().getChannel());
}
@Test
public void testSyncRemotingChannel() throws Exception {
String consumerGroup = "consumerGroup";
String consumerGroup2 = "consumerGroup2";
Channel channel = createMockChannel();
Set<SubscriptionData> subscriptionDataSet = new HashSet<>();
subscriptionDataSet.add(FilterAPI.buildSubscriptionData("topic", "tagSub"));
Set<SubscriptionData> subscriptionDataSet2 = new HashSet<>();
subscriptionDataSet2.add(FilterAPI.buildSubscriptionData("topic2", "tagSub2"));
RemotingProxyOutClient remotingProxyOutClient = mock(RemotingProxyOutClient.class);
RemotingChannel remotingChannel = new RemotingChannel(remotingProxyOutClient, proxyRelayService, channel, clientId, subscriptionDataSet);
ClientChannelInfo clientChannelInfo = new ClientChannelInfo(
remotingChannel,
clientId,
LanguageCode.JAVA,
4
);
RemotingChannel remotingChannel2 = new RemotingChannel(remotingProxyOutClient, proxyRelayService, channel, clientId, subscriptionDataSet2);
ClientChannelInfo clientChannelInfo2 = new ClientChannelInfo(
remotingChannel2,
clientId,
LanguageCode.JAVA,
4
);
HeartbeatSyncer heartbeatSyncer = new HeartbeatSyncer(topicRouteService, adminService, consumerManager, mqClientAPIFactory, null);
SendResult okSendResult = new SendResult();
okSendResult.setSendStatus(SendStatus.SEND_OK);
{
ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
doReturn(CompletableFuture.completedFuture(okSendResult)).when(this.mqClientAPIExt)
.sendMessageAsync(anyString(), anyString(), messageArgumentCaptor.capture(), any(), anyLong());
heartbeatSyncer.onConsumerRegister(
consumerGroup,
clientChannelInfo,
ConsumeType.CONSUME_PASSIVELY,
MessageModel.CLUSTERING,
ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET,
subscriptionDataSet
);
heartbeatSyncer.onConsumerRegister(
consumerGroup2,
clientChannelInfo2,
ConsumeType.CONSUME_PASSIVELY,
MessageModel.CLUSTERING,
ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET,
subscriptionDataSet2
);
await().atMost(Duration.ofSeconds(3)).until(() -> messageArgumentCaptor.getAllValues().size() == 2);
heartbeatSyncer.consumeMessage(convertFromMessage(messageArgumentCaptor.getAllValues()), null);
verify(consumerManager, never()).registerConsumer(anyString(), any(), any(), any(), any(), any(), anyBoolean());
// change local serve addr, to simulate other proxy receive messages
heartbeatSyncer.localProxyId = RandomStringUtils.randomAlphabetic(10);
ArgumentCaptor<ClientChannelInfo> syncChannelInfoArgumentCaptor = ArgumentCaptor.forClass(ClientChannelInfo.class);
doReturn(true).when(consumerManager).registerConsumer(anyString(), syncChannelInfoArgumentCaptor.capture(), any(), any(), any(), any(), anyBoolean());
heartbeatSyncer.consumeMessage(convertFromMessage(messageArgumentCaptor.getAllValues()), null);
heartbeatSyncer.consumeMessage(convertFromMessage(messageArgumentCaptor.getAllValues()), null);
/*
data in syncChannelInfoArgumentCaptor will be like:
1st, data of group1
2nd, data of group2
3rd, data of group1
4th, data of group2
*/
assertEquals(4, syncChannelInfoArgumentCaptor.getAllValues().size());
List<ClientChannelInfo> channelInfoList = syncChannelInfoArgumentCaptor.getAllValues();
assertSame(channelInfoList.get(0).getChannel(), channelInfoList.get(2).getChannel());
assertNotSame(channelInfoList.get(0).getChannel(), channelInfoList.get(1).getChannel());
Set<Set<SubscriptionData>> checkSubscriptionDatas = new HashSet<>();
checkSubscriptionDatas.add(RemotingChannel.parseChannelExtendAttribute(channelInfoList.get(0).getChannel()));
checkSubscriptionDatas.add(RemotingChannel.parseChannelExtendAttribute(channelInfoList.get(1).getChannel()));
assertTrue(checkSubscriptionDatas.contains(subscriptionDataSet));
assertTrue(checkSubscriptionDatas.contains(subscriptionDataSet2));
}
{
// start test sync client unregister
// reset localServeAddr
ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
doReturn(CompletableFuture.completedFuture(okSendResult)).when(this.mqClientAPIExt)
.sendMessageAsync(anyString(), anyString(), messageArgumentCaptor.capture(), any(), anyLong());
heartbeatSyncer.onConsumerUnRegister(consumerGroup, clientChannelInfo);
heartbeatSyncer.onConsumerUnRegister(consumerGroup2, clientChannelInfo2);
await().atMost(Duration.ofSeconds(3)).until(() -> messageArgumentCaptor.getAllValues().size() == 2);
ArgumentCaptor<ClientChannelInfo> syncUnRegisterChannelInfoArgumentCaptor = ArgumentCaptor.forClass(ClientChannelInfo.class);
doNothing().when(consumerManager).unregisterConsumer(anyString(), syncUnRegisterChannelInfoArgumentCaptor.capture(), anyBoolean());
// change local serve addr, to simulate other proxy receive messages
heartbeatSyncer.localProxyId = RandomStringUtils.randomAlphabetic(10);
heartbeatSyncer.consumeMessage(convertFromMessage(messageArgumentCaptor.getAllValues()), null);
List<ClientChannelInfo> channelInfoList = syncUnRegisterChannelInfoArgumentCaptor.getAllValues();
assertNotSame(channelInfoList.get(0).getChannel(), channelInfoList.get(1).getChannel());
Set<Set<SubscriptionData>> checkSubscriptionDatas = new HashSet<>();
checkSubscriptionDatas.add(RemotingChannel.parseChannelExtendAttribute(channelInfoList.get(0).getChannel()));
checkSubscriptionDatas.add(RemotingChannel.parseChannelExtendAttribute(channelInfoList.get(1).getChannel()));
assertTrue(checkSubscriptionDatas.contains(subscriptionDataSet));
assertTrue(checkSubscriptionDatas.contains(subscriptionDataSet2));
}
}
@Test
public void testProcessConsumerGroupEventForRemoting() {
String consumerGroup = "consumerGroup";
Channel channel = createMockChannel();
RemotingProxyOutClient remotingProxyOutClient = mock(RemotingProxyOutClient.class);
RemotingChannel remotingChannel = new RemotingChannel(remotingProxyOutClient, proxyRelayService, channel, clientId, Collections.emptySet());
ClientChannelInfo clientChannelInfo = new ClientChannelInfo(
remotingChannel,
clientId,
LanguageCode.JAVA,
4
);
testProcessConsumerGroupEvent(consumerGroup, clientChannelInfo);
}
@Test
public void testProcessConsumerGroupEventForGrpcV2() {
String consumerGroup = "consumerGroup";
GrpcClientSettingsManager grpcClientSettingsManager = mock(GrpcClientSettingsManager.class);
GrpcChannelManager grpcChannelManager = mock(GrpcChannelManager.class);
GrpcClientChannel grpcClientChannel = new GrpcClientChannel(
proxyRelayService, grpcClientSettingsManager, grpcChannelManager,
ProxyContext.create().setRemoteAddress(remoteAddress).setLocalAddress(localAddress),
clientId);
ClientChannelInfo clientChannelInfo = new ClientChannelInfo(
grpcClientChannel,
clientId,
LanguageCode.JAVA,
5
);
testProcessConsumerGroupEvent(consumerGroup, clientChannelInfo);
}
private void testProcessConsumerGroupEvent(String consumerGroup, ClientChannelInfo clientChannelInfo) {
HeartbeatSyncer heartbeatSyncer = new HeartbeatSyncer(topicRouteService, adminService, consumerManager, mqClientAPIFactory, null);
SendResult okSendResult = new SendResult();
okSendResult.setSendStatus(SendStatus.SEND_OK);
ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
doReturn(CompletableFuture.completedFuture(okSendResult)).when(this.mqClientAPIExt)
.sendMessageAsync(anyString(), anyString(), messageArgumentCaptor.capture(), any(), anyLong());
heartbeatSyncer.onConsumerRegister(
consumerGroup,
clientChannelInfo,
ConsumeType.CONSUME_PASSIVELY,
MessageModel.CLUSTERING,
ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET,
Collections.emptySet()
);
await().atMost(Duration.ofSeconds(3)).until(() -> messageArgumentCaptor.getAllValues().size() == 1);
// change local serve addr, to simulate other proxy receive messages
heartbeatSyncer.localProxyId = RandomStringUtils.randomAlphabetic(10);
ArgumentCaptor<ClientChannelInfo> channelInfoArgumentCaptor = ArgumentCaptor.forClass(ClientChannelInfo.class);
doReturn(true).when(consumerManager).registerConsumer(anyString(), channelInfoArgumentCaptor.capture(), any(), any(), any(), any(), anyBoolean());
heartbeatSyncer.consumeMessage(convertFromMessage(messageArgumentCaptor.getAllValues()), null);
assertEquals(1, heartbeatSyncer.remoteChannelMap.size());
heartbeatSyncer.processConsumerGroupEvent(ConsumerGroupEvent.CLIENT_UNREGISTER, consumerGroup, channelInfoArgumentCaptor.getValue());
assertTrue(heartbeatSyncer.remoteChannelMap.isEmpty());
}
private MessageExt convertFromMessage(Message message) {
MessageExt messageExt = new MessageExt();
messageExt.setTopic(message.getTopic());
messageExt.setBody(message.getBody());
return messageExt;
}
private List<MessageExt> convertFromMessage(List<Message> message) {
return message.stream().map(this::convertFromMessage).collect(Collectors.toList());
}
private Channel createMockChannel() {
return new MockChannel(RandomStringUtils.randomAlphabetic(10));
}
private
|
HeartbeatSyncerTest
|
java
|
quarkusio__quarkus
|
integration-tests/oidc-dev-services/src/test/java/io/quarkus/it/oidc/dev/services/BearerAuthenticationOidcDevServicesTest.java
|
{
"start": 296,
"end": 3329
}
|
class ____ {
static final OidcTestClient oidcTestClient = new OidcTestClient();
@AfterAll
public static void close() {
oidcTestClient.close();
}
@Test
public void testLoginAsCustomUser() {
RestAssured.given()
.auth().oauth2(getAccessToken("Ronald"))
.get("/secured/admin-only")
.then()
.statusCode(200)
.body(Matchers.containsString("Ronald"))
.body(Matchers.containsString("admin"));
RestAssured.given()
.auth().oauth2(getAccessToken("Ronald"))
.get("/secured/user-only")
.then()
.statusCode(403);
}
@Test
public void testLoginAsAlice() {
RestAssured.given()
.auth().oauth2(getAccessToken("alice"))
.get("/secured/admin-only")
.then()
.statusCode(200)
.body(Matchers.containsString("alice"))
.body(Matchers.containsString("admin"))
.body(Matchers.containsString("user"));
RestAssured.given()
.auth().oauth2(getAccessToken("alice"))
.get("/secured/user-only")
.then()
.statusCode(200)
.body(Matchers.startsWith("alice@example.com "))
.body(Matchers.containsString("admin"))
.body(Matchers.containsString("user"));
}
@Test
public void testLoginAsBob() {
RestAssured.given()
.auth().oauth2(getAccessToken("bob"))
.get("/secured/admin-only")
.then()
.statusCode(403);
RestAssured.given()
.auth().oauth2(getAccessToken("bob"))
.get("/secured/user-only")
.then()
.statusCode(200)
.body(Matchers.startsWith("bob@example.com "))
.body(Matchers.containsString("user"));
}
@Test
void testEmailAndName() {
// test users get an @example.com appended if username is not an email address
RestAssured.given()
.auth().oauth2(getAccessToken("bob"))
.get("/secured/user-only")
.then()
.statusCode(200)
.body(Matchers.startsWith("bob@example.com "))
.body(Matchers.containsString(" Bob"));
// Test no additional @example.com is appended if requested username is likely already an email address
RestAssured.given()
.auth().oauth2(getAccessToken("bob@example.com"))
.get("/secured/user-only")
.then()
.statusCode(200)
.body(Matchers.startsWith("bob@example.com "))
.body(Matchers.containsString(" Bob"));
}
private String getAccessToken(String user) {
return oidcTestClient.getAccessToken(user, user);
}
}
|
BearerAuthenticationOidcDevServicesTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/LastIntByTimestampAggregatorFunctionTests.java
|
{
"start": 948,
"end": 2956
}
|
class ____ extends AggregatorFunctionTestCase {
@Override
protected SourceOperator simpleInput(BlockFactory blockFactory, int size) {
FirstLongByTimestampGroupingAggregatorFunctionTests.TimestampGen tsgen = randomFrom(
FirstLongByTimestampGroupingAggregatorFunctionTests.TimestampGen.values()
);
return new ListRowsBlockSourceOperator(
blockFactory,
List.of(ElementType.INT, ElementType.LONG),
IntStream.range(0, size).mapToObj(l -> List.of(randomInt(), tsgen.gen())).toList()
);
}
@Override
protected AggregatorFunctionSupplier aggregatorFunction() {
return new LastIntByTimestampAggregatorFunctionSupplier();
}
@Override
protected int inputCount() {
return 2;
}
@Override
protected String expectedDescriptionOfAggregator() {
return "last_int_by_timestamp";
}
@Override
public void assertSimpleOutput(List<Page> input, Block result) {
ExpectedWork work = new ExpectedWork(false);
for (Page page : input) {
IntBlock values = page.getBlock(0);
LongBlock timestamps = page.getBlock(1);
for (int p = 0; p < page.getPositionCount(); p++) {
int tsStart = timestamps.getFirstValueIndex(p);
int tsEnd = tsStart + timestamps.getValueCount(p);
for (int tsOffset = tsStart; tsOffset < tsEnd; tsOffset++) {
long timestamp = timestamps.getLong(tsOffset);
int vStart = values.getFirstValueIndex(p);
int vEnd = vStart + values.getValueCount(p);
for (int vOffset = vStart; vOffset < vEnd; vOffset++) {
int value = values.getInt(vOffset);
work.add(timestamp, value);
}
}
}
}
work.check(BlockUtils.toJavaObject(result, 0));
}
}
|
LastIntByTimestampAggregatorFunctionTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/internal/MapMember.java
|
{
"start": 330,
"end": 781
}
|
class ____ implements Member {
private final String name;
private final Class<?> type;
public MapMember(String name, Class<?> type) {
this.name = name;
this.type = type;
}
public Class<?> getType() {
return type;
}
public int getModifiers() {
return Modifier.PUBLIC;
}
public boolean isSynthetic() {
return false;
}
public String getName() {
return name;
}
public Class<?> getDeclaringClass() {
return null;
}
}
|
MapMember
|
java
|
quarkusio__quarkus
|
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/i18n/MessageBundleCustomDefaultLocaleTest.java
|
{
"start": 1427,
"end": 1550
}
|
interface ____ {
@Message("Ahoj světe!")
String helloWorld();
}
@Localized("en")
public
|
Messages
|
java
|
grpc__grpc-java
|
api/src/main/java/io/grpc/LoadBalancer.java
|
{
"start": 17375,
"end": 17844
}
|
class ____ {
/**
* Make a balancing decision for a new RPC.
*
* @param args the pick arguments
* @since 1.3.0
*/
public abstract PickResult pickSubchannel(PickSubchannelArgs args);
}
/**
* Provides arguments for a {@link SubchannelPicker#pickSubchannel(
* LoadBalancer.PickSubchannelArgs)}.
*
* @since 1.2.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
public abstract static
|
SubchannelPicker
|
java
|
apache__logging-log4j2
|
log4j-core-test/src/test/java/org/apache/logging/log4j/core/jmx/ServerTest.java
|
{
"start": 1025,
"end": 4554
}
|
class ____ {
@Test
void testEscapeQuotesButDoesNotEscapeEquals() throws Exception {
final String ctx = "WebAppClassLoader=1320771902@4eb9613e"; // LOG4J2-492
final String ctxName = Server.escape(ctx);
assertEquals("\"WebAppClassLoader=1320771902@4eb9613e\"", ctxName);
new ObjectName(String.format(LoggerContextAdminMBean.PATTERN, ctxName));
// no MalformedObjectNameException = success
}
@Test
void testEscapeQuotesButDoesNotEscapeComma() throws Exception {
final String ctx = "a,b,c";
final String ctxName = Server.escape(ctx);
assertEquals("\"a,b,c\"", ctxName);
new ObjectName(String.format(LoggerContextAdminMBean.PATTERN, ctxName));
// no MalformedObjectNameException = success
}
@Test
void testEscapeQuotesButDoesNotEscapeColon() throws Exception {
final String ctx = "a:b:c";
final String ctxName = Server.escape(ctx);
assertEquals("\"a:b:c\"", ctxName);
new ObjectName(String.format(LoggerContextAdminMBean.PATTERN, ctxName));
// no MalformedObjectNameException = success
}
@Test
void testEscapeQuotesAndEscapesQuestion() throws Exception {
final String ctx = "a?c";
final String ctxName = Server.escape(ctx);
assertEquals("\"a\\?c\"", ctxName);
new ObjectName(String.format(LoggerContextAdminMBean.PATTERN, ctxName));
// no MalformedObjectNameException = success
}
@Test
void testEscapeQuotesAndEscapesStar() throws Exception {
final String ctx = "a*c";
final String ctxName = Server.escape(ctx);
assertEquals("\"a\\*c\"", ctxName);
new ObjectName(String.format(LoggerContextAdminMBean.PATTERN, ctxName));
// no MalformedObjectNameException = success
}
@Test
void testEscapeQuotesAndEscapesBackslash() throws Exception {
final String ctx = "a\\c";
final String ctxName = Server.escape(ctx);
assertEquals("\"a\\\\c\"", ctxName);
new ObjectName(String.format(LoggerContextAdminMBean.PATTERN, ctxName));
// no MalformedObjectNameException = success
}
@Test
void testEscapeQuotesAndEscapesQuote() throws Exception {
final String ctx = "a\"c";
final String ctxName = Server.escape(ctx);
assertEquals("\"a\\\"c\"", ctxName);
new ObjectName(String.format(LoggerContextAdminMBean.PATTERN, ctxName));
// no MalformedObjectNameException = success
}
@Test
void testEscapeIgnoresSpaces() throws Exception {
final String ctx = "a c";
final String ctxName = Server.escape(ctx);
assertEquals("a c", ctxName);
new ObjectName(String.format(LoggerContextAdminMBean.PATTERN, ctxName));
// no MalformedObjectNameException = success
}
@Test
void testEscapeEscapesLineFeed() throws Exception {
final String ctx = "a\rc";
final String ctxName = Server.escape(ctx);
assertEquals("ac", ctxName);
new ObjectName(String.format(LoggerContextAdminMBean.PATTERN, ctxName));
// no MalformedObjectNameException = success
}
@Test
void testEscapeEscapesCarriageReturn() throws Exception {
final String ctx = "a\nc";
final String ctxName = Server.escape(ctx);
assertEquals("\"a\\nc\"", ctxName);
new ObjectName(String.format(LoggerContextAdminMBean.PATTERN, ctxName));
// no MalformedObjectNameException = success
}
}
|
ServerTest
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/jsontype/SealedTypesWithPolymorphicDeductionTest.java
|
{
"start": 1295,
"end": 1414
}
|
class ____ extends Cat {
public boolean angry;
}
// No distinguishing properties whatsoever
static final
|
LiveCat
|
java
|
spring-projects__spring-framework
|
spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java
|
{
"start": 5748,
"end": 6040
}
|
class ____ extends MessageHeaders {
public MyMH() {
super(null, new UUID(0, id.incrementAndGet()), -1L);
}
}
MessageHeaders headers = new MyMH();
assertThat(headers.getId().toString()).isEqualTo("00000000-0000-0000-0000-000000000001");
assertThat(headers).hasSize(1);
}
}
|
MyMH
|
java
|
apache__camel
|
components/camel-braintree/src/test/java/org/apache/camel/component/braintree/CustomerGatewayIT.java
|
{
"start": 2172,
"end": 8182
}
|
class ____ extends AbstractBraintreeTestSupport {
private static final String PATH_PREFIX = getApiNameAsString(CustomerGatewayApiMethod.class);
private static final Logger LOG = LoggerFactory.getLogger(CustomerGatewayIT.class);
/**
* Customers management workflow: - create a customer - lookup by id - update first name - delete by id - confirm
* deletion by searching again
*
*/
@Test
public void testCustomerManagementWorkflow() {
String customerLastName = UUID.randomUUID().toString();
String customerId = null;
// Create customer
Result<Customer> createResult = requestBody(
"direct://CREATE_IN_BODY",
new CustomerRequest()
.firstName("user")
.lastName(customerLastName)
.company("Apache")
.email("user@braintree.camel")
.website("http://user.braintree.camel"),
Result.class);
assertNotNull(createResult);
assertTrue(createResult.isSuccess());
assertNotNull(createResult.getTarget());
assertNotNull(createResult.getTarget().getId());
customerId = createResult.getTarget().getId();
// Find customer by ID
Customer customer1 = requestBody("direct://FIND_IN_BODY", customerId, Customer.class);
assertNotNull(customer1);
assertEquals("user", customer1.getFirstName());
assertEquals(customerLastName, customer1.getLastName());
assertEquals("Apache", customer1.getCompany());
assertEquals("user@braintree.camel", customer1.getEmail());
assertEquals("http://user.braintree.camel", customer1.getWebsite());
// Update customer
HashMap<String, Object> headers = new HashMap<>();
headers.put("CamelBraintree.id", customerId);
Result<Customer> updateResult = requestBodyAndHeaders(
"direct://UPDATE_IN_BODY",
new CustomerRequest().firstName("user-mod"),
headers,
Result.class);
assertNotNull(updateResult);
assertTrue(updateResult.isSuccess());
assertNotNull(updateResult.getTarget());
assertEquals("user-mod", updateResult.getTarget().getFirstName());
// Delete customer
Result<Customer> customerResult = requestBody("direct://DELETE_IN_BODY", customerId, Result.class);
assertNotNull(customerResult);
assertTrue(customerResult.isSuccess());
assertNull(customerResult.getTarget());
// Check if customer has been deleted customer
ResourceCollection<Customer> customers = requestBody(
"direct://SEARCH_IN_BODY",
new CustomerSearchRequest().id().is(customerId),
ResourceCollection.class);
assertNotNull(customers);
assertEquals(0, customers.getMaximumSize());
}
@Test
public void testUpdateUnknownCustomer() {
String id = "unknown-" + UUID.randomUUID().toString();
HashMap<String, Object> headers = new HashMap<>();
headers.put("CamelBraintree.id", id);
CustomerRequest customerRequest = new CustomerRequest().firstName(id);
Exception ex = assertThrows(CamelExecutionException.class,
() -> requestBodyAndHeaders("direct://UPDATE_IN_BODY", customerRequest, headers));
assertIsInstanceOf(NotFoundException.class, ex.getCause().getCause());
}
@Test
public void testSearchUnknownCustomer() {
String uuid = "unknown-" + UUID.randomUUID().toString();
Exception ex = assertThrows(CamelExecutionException.class,
() -> requestBody("direct://FIND_IN_BODY", uuid));
assertIsInstanceOf(NotFoundException.class, ex.getCause().getCause());
}
@Test
public void testWrongCustomerCreateRequest() {
// Create customer
Result<Customer> createResult = requestBody(
"direct://CREATE_IN_BODY",
new CustomerRequest()
.firstName("user")
.lastName(UUID.randomUUID().toString())
.company("Apache")
.email("wrongEmail")
.website("http://user.braintree.camel"),
Result.class);
assertNotNull(createResult);
assertFalse(createResult.isSuccess());
final ValidationErrors errors = createResult.getErrors();
assertNotNull(errors);
assertNotNull(errors.getAllDeepValidationErrors());
ValidationError invalidMailError = null;
for (ValidationError error : errors.getAllDeepValidationErrors()) {
if (error.getCode() == ValidationErrorCode.CUSTOMER_EMAIL_FORMAT_IS_INVALID) {
invalidMailError = error;
break;
}
}
assertNotNull(invalidMailError);
}
// *************************************************************************
// Routes
// *************************************************************************
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct://CREATE_IN_BODY")
.to("braintree://" + PATH_PREFIX + "/create?inBody=request");
from("direct://DELETE_IN_BODY")
.to("braintree://" + PATH_PREFIX + "/delete?inBody=id");
from("direct://FIND_IN_BODY")
.to("braintree://" + PATH_PREFIX + "/find?inBody=id");
from("direct://SEARCH_IN_BODY")
.to("braintree://" + PATH_PREFIX + "/search?inBody=query");
from("direct://UPDATE_IN_BODY")
.to("braintree://" + PATH_PREFIX + "/update?inBody=request");
}
};
}
}
|
CustomerGatewayIT
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/query/criteria/JpaJsonExistsNode.java
|
{
"start": 1215,
"end": 1524
}
|
enum ____ {
/**
* SQL/JDBC error should be raised.
*/
ERROR,
/**
* {@code true} should be returned on error.
*/
TRUE,
/**
* {@code false} should be returned on error.
*/
FALSE,
/**
* Unspecified behavior i.e. the default database behavior.
*/
UNSPECIFIED
}
}
|
ErrorBehavior
|
java
|
apache__camel
|
components/camel-salesforce/camel-salesforce-maven-plugin/src/test/resources/generated/With_External_Id__c_Lookup.java
|
{
"start": 323,
"end": 467
}
|
class ____ SObject With_External_Id__c_Lookup
*/
@Generated("org.apache.camel.maven.CamelSalesforceMojo")
@JsonInclude(Include.NON_NULL)
public
|
for
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/datatypes/util/DefaultJobPropertiesParser.java
|
{
"start": 1069,
"end": 1255
}
|
class ____ implements JobPropertyParser {
@Override
public DataType<?> parseJobProperty(String key, String value) {
return new DefaultDataType(value);
}
}
|
DefaultJobPropertiesParser
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/longarrays/LongArrays_assertStartsWith_Test.java
|
{
"start": 1702,
"end": 7551
}
|
class ____ extends LongArraysBaseTest {
@Override
protected void initActualArray() {
actual = arrayOf(6L, 8L, 10L, 12L);
}
@Test
void should_throw_error_if_sequence_is_null() {
assertThatNullPointerException().isThrownBy(() -> arrays.assertStartsWith(someInfo(), actual, null))
.withMessage(valuesToLookForIsNull());
}
@Test
void should_pass_if_actual_and_given_values_are_empty() {
actual = emptyArray();
arrays.assertStartsWith(someInfo(), actual, emptyArray());
}
@Test
void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertStartsWith(someInfo(), actual, emptyArray()));
}
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertStartsWith(someInfo(), null, arrayOf(8L)))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_sequence_is_bigger_than_actual() {
AssertionInfo info = someInfo();
long[] sequence = { 6L, 8L, 10L, 12L, 20L, 22L };
Throwable error = catchThrowable(() -> arrays.assertStartsWith(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldStartWith(actual, sequence));
}
@Test
void should_fail_if_actual_does_not_start_with_sequence() {
AssertionInfo info = someInfo();
long[] sequence = { 8L, 10L };
Throwable error = catchThrowable(() -> arrays.assertStartsWith(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldStartWith(actual, sequence));
}
@Test
void should_fail_if_actual_starts_with_first_elements_of_sequence_only() {
AssertionInfo info = someInfo();
long[] sequence = { 6L, 20L };
Throwable error = catchThrowable(() -> arrays.assertStartsWith(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldStartWith(actual, sequence));
}
@Test
void should_pass_if_actual_starts_with_sequence() {
arrays.assertStartsWith(someInfo(), actual, arrayOf(6L, 8L, 10L));
}
@Test
void should_pass_if_actual_and_sequence_are_equal() {
arrays.assertStartsWith(someInfo(), actual, arrayOf(6L, 8L, 10L, 12L));
}
@Test
void should_throw_error_if_sequence_is_null_whatever_custom_comparison_strategy_is() {
assertThatNullPointerException().isThrownBy(() -> arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(),
actual, null))
.withMessage(valuesToLookForIsNull());
}
@Test
void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(),
actual,
emptyArray()));
}
@Test
void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(),
null,
arrayOf(-8L)))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_sequence_is_bigger_than_actual_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
long[] sequence = { 6L, -8L, 10L, 12L, 20L, 22L };
Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertStartsWith(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldStartWith(actual, sequence, absValueComparisonStrategy));
}
@Test
void should_fail_if_actual_does_not_start_with_sequence_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
long[] sequence = { -8L, 10L };
Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertStartsWith(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldStartWith(actual, sequence, absValueComparisonStrategy));
}
@Test
void should_fail_if_actual_starts_with_first_elements_of_sequence_only_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
long[] sequence = { 6L, 20L };
Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertStartsWith(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldStartWith(actual, sequence, absValueComparisonStrategy));
}
@Test
void should_pass_if_actual_starts_with_sequence_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(), actual, arrayOf(6L, -8L, 10L));
}
@Test
void should_pass_if_actual_and_sequence_are_equal_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(), actual, arrayOf(6L, -8L, 10L, 12L));
}
}
|
LongArrays_assertStartsWith_Test
|
java
|
quarkusio__quarkus
|
extensions/oidc-client-registration/runtime/src/main/java/io/quarkus/oidc/client/registration/OidcClientRegistrationConfig.java
|
{
"start": 950,
"end": 2886
}
|
interface ____ {
/**
* Client name
*/
Optional<String> clientName();
/**
* Redirect URI
*/
Optional<String> redirectUri();
/**
* Post Logout URI
*/
Optional<String> postLogoutUri();
/**
* Additional metadata properties
*/
Map<String, String> extraProps();
}
/**
* Creates {@link OidcClientRegistrationConfig} builder populated with documented default values.
*
* @return OidcClientRegistrationConfigBuilder builder
*/
static OidcClientRegistrationConfigBuilder builder() {
return new OidcClientRegistrationConfigBuilder();
}
/**
* Creates {@link OidcClientRegistrationConfig} builder populated with {@code config} values.
*
* @param config client registration config; must not be null
* @return OidcClientRegistrationConfigBuilder
*/
static OidcClientRegistrationConfigBuilder builder(OidcClientRegistrationConfig config) {
return new OidcClientRegistrationConfigBuilder(config);
}
/**
* Creates {@link OidcClientRegistrationConfig} builder populated with documented default values.
*
* @param authServerUrl {@link OidcCommonConfig#authServerUrl()}
* @return OidcClientRegistrationConfigBuilder builder
*/
static OidcClientRegistrationConfigBuilder authServerUrl(String authServerUrl) {
return builder().authServerUrl(authServerUrl);
}
/**
* Creates {@link OidcClientRegistrationConfig} builder populated with documented default values.
*
* @param registrationPath {@link OidcCommonConfig#registrationPath()}
* @return OidcClientRegistrationConfigBuilder builder
*/
static OidcClientRegistrationConfigBuilder registrationPath(String registrationPath) {
return builder().registrationPath(registrationPath);
}
}
|
Metadata
|
java
|
google__dagger
|
javatests/dagger/hilt/android/processor/internal/GeneratorsTest.java
|
{
"start": 15028,
"end": 15744
}
|
class ____ extends FragmentActivity"
+ " implements GeneratedComponentManagerHolder {"));
});
}
@Test
public void copyTargetApiAnnotationOverView() {
Source myView =
HiltCompilerTests.javaSource(
"test.MyView",
"package test;",
"",
"import android.annotation.TargetApi;",
"import android.widget.LinearLayout;",
"import android.content.Context;",
"import android.util.AttributeSet;",
"import dagger.hilt.android.AndroidEntryPoint;",
"",
"@TargetApi(24)",
"@AndroidEntryPoint(LinearLayout.class)",
"public
|
Hilt_MyActivity
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/writeClassName/WriteClassNameTest5.java
|
{
"start": 1266,
"end": 1397
}
|
class ____ {
@JSONField(serialzeFeatures = SerializerFeature.WriteClassName)
public A a;
}
public static
|
Model
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.