language stringclasses 1
value | repo stringclasses 60
values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__flink | flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/FileSystemTableSink.java | {
"start": 28531,
"end": 29658
} | class ____ implements BulkWriter.Factory<RowData> {
private final BulkWriter.Factory<RowData> factory;
private final RowDataPartitionComputer computer;
public ProjectionBulkFactory(
BulkWriter.Factory<RowData> factory, RowDataPartitionComputer computer) {
this.factory = factory;
this.computer = computer;
}
@Override
public BulkWriter<RowData> create(FSDataOutputStream out) throws IOException {
BulkWriter<RowData> writer = factory.create(out);
return new BulkWriter<RowData>() {
@Override
public void addElement(RowData element) throws IOException {
writer.addElement(computer.projectColumnsToWrite(element));
}
@Override
public void flush() throws IOException {
writer.flush();
}
@Override
public void finish() throws IOException {
writer.finish();
}
};
}
}
}
| ProjectionBulkFactory |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/CreateCharDiscriminatorTest.java | {
"start": 1674,
"end": 1971
} | class ____ {
@Id
private Integer id;
@Column
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| Parent |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/records/RecordSerializationOrderTest.java | {
"start": 407,
"end": 5309
} | class ____ extends DatabindTestUtil
{
record NestedRecordOne(String id, String email, NestedRecordTwo nestedRecordTwo) {}
record NestedRecordOneWithJsonProperty(String id, String email,
@JsonProperty("nestedProperty") NestedRecordTwo nestedRecordTwo) {}
record NestedRecordOneWithJsonPropertyIndex(@JsonProperty(index = 2) String id,
@JsonProperty(index = 0) String email,
@JsonProperty(value = "nestedProperty", index = 1) NestedRecordTwo nestedRecordTwo) {}
@JsonPropertyOrder({"email", "nestedProperty", "id"})
record NestedRecordOneWithJsonPropertyOrder(String id,
String email,
@JsonProperty(value = "nestedProperty") NestedRecordTwo nestedRecordTwo) {}
record NestedRecordTwo(String id, String passport) {}
record CABRecord(String c, String a, String b) {}
record JsonPropertyRecord(@JsonProperty("aa") int a, int b) {}
record JsonPropertyRecord2(int a, @JsonProperty("bb") int b) {}
private final ObjectMapper MAPPER = newJsonMapper();
/*
/**********************************************************************
/* Test methods, alternate constructors
/**********************************************************************
*/
@Test
public void testSerializationOrder() throws Exception {
NestedRecordTwo nestedRecordTwo = new NestedRecordTwo("2", "111110");
NestedRecordOne nestedRecordOne = new NestedRecordOne("1", "test@records.com", nestedRecordTwo);
final String output = MAPPER.writeValueAsString(nestedRecordOne);
final String expected = a2q("{'id':'1','email':'test@records.com','nestedRecordTwo':{'id':'2','passport':'111110'}}");
assertEquals(expected, output);
}
@Test
public void testBasicSerializationOrderWithJsonProperty() throws Exception {
JsonPropertyRecord jsonPropertyRecord = new JsonPropertyRecord(1, 2);
final String output = MAPPER.writeValueAsString(jsonPropertyRecord);
final String expected = "{\"aa\":1,\"b\":2}";
assertEquals(expected, output);
}
@Test
public void testBasicSerializationOrderWithJsonProperty2() throws Exception {
JsonPropertyRecord2 jsonPropertyRecord = new JsonPropertyRecord2(1, 2);
final String output = MAPPER.writeValueAsString(jsonPropertyRecord);
final String expected = "{\"a\":1,\"bb\":2}";
assertEquals(expected, output);
}
@Test
public void testSerializationOrderWithJsonProperty() throws Exception {
NestedRecordTwo nestedRecordTwo = new NestedRecordTwo("2", "111110");
NestedRecordOneWithJsonProperty nestedRecordOne =
new NestedRecordOneWithJsonProperty("1", "test@records.com", nestedRecordTwo);
final String output = MAPPER.writeValueAsString(nestedRecordOne);
final String expected = a2q("{'id':'1','email':'test@records.com','nestedProperty':{'id':'2','passport':'111110'}}");
assertEquals(expected, output);
}
@Test
public void testSerializationOrderWithJsonPropertyIndexes() throws Exception {
NestedRecordTwo nestedRecordTwo = new NestedRecordTwo("2", "111110");
NestedRecordOneWithJsonPropertyIndex nestedRecordOne =
new NestedRecordOneWithJsonPropertyIndex("1", "test@records.com", nestedRecordTwo);
final String output = MAPPER.writeValueAsString(nestedRecordOne);
final String expected = "{\"email\":\"test@records.com\",\"nestedProperty\":{\"id\":\"2\",\"passport\":\"111110\"},\"id\":\"1\"}";
assertEquals(expected, output);
}
@Test
public void testSerializationOrderWithJsonPropertyOrder() throws Exception {
NestedRecordTwo nestedRecordTwo = new NestedRecordTwo("2", "111110");
NestedRecordOneWithJsonPropertyOrder nestedRecordOne =
new NestedRecordOneWithJsonPropertyOrder("1", "test@records.com", nestedRecordTwo);
final String output = MAPPER.writeValueAsString(nestedRecordOne);
final String expected = "{\"email\":\"test@records.com\",\"nestedProperty\":{\"id\":\"2\",\"passport\":\"111110\"},\"id\":\"1\"}";
assertEquals(expected, output);
}
// [databind#4580]
@Test
public void testSerializationOrderWrtCreatorAlphabetic() throws Exception {
// In 3.0, sorting by Alphabetic enabled by default BUT it won't affect Creator props
assertEquals(a2q("{'c':'c','a':'a','b':'b'}"),
MAPPER.writeValueAsString(new CABRecord("c", "a", "b")));
// Unless we disable Creator-props-first setting:
assertEquals(a2q("{'a':'a','b':'b','c':'c'}"),
jsonMapperBuilder()
.disable(MapperFeature.SORT_CREATOR_PROPERTIES_FIRST)
.build()
.writeValueAsString(new CABRecord("c", "a", "b")));
}
}
| RecordSerializationOrderTest |
java | elastic__elasticsearch | modules/ingest-attachment/src/test/java/org/elasticsearch/ingest/attachment/TikaImplTests.java | {
"start": 564,
"end": 737
} | class ____ extends ESTestCase {
public void testTikaLoads() throws Exception {
Class.forName("org.elasticsearch.ingest.attachment.TikaImpl");
}
}
| TikaImplTests |
java | apache__flink | flink-table/flink-sql-gateway/src/main/java/org/apache/flink/table/gateway/rest/util/SqlGatewayRestAPIVersion.java | {
"start": 1549,
"end": 1704
} | enum ____
implements RestAPIVersion<SqlGatewayRestAPIVersion>, EndpointVersion {
// The bigger the ordinal(its position in | SqlGatewayRestAPIVersion |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/authorization/OidcTests.java | {
"start": 33629,
"end": 34604
} | class ____
extends AuthorizationServerConfiguration {
// @formatter:off
@Bean
SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.tokenGenerator(tokenGenerator())
.oidc(Customizer.withDefaults())
)
.authorizeHttpRequests((authorize) ->
authorize.anyRequest().authenticated()
);
return http.build();
}
// @formatter:on
@Bean
OAuth2TokenGenerator<?> tokenGenerator() {
JwtGenerator jwtGenerator = new JwtGenerator(new NimbusJwtEncoder(jwkSource()));
jwtGenerator.setJwtCustomizer(jwtCustomizer());
OAuth2TokenGenerator<OAuth2RefreshToken> refreshTokenGenerator = new CustomRefreshTokenGenerator();
return new DelegatingOAuth2TokenGenerator(jwtGenerator, refreshTokenGenerator);
}
private static final | AuthorizationServerConfigurationWithCustomRefreshTokenGenerator |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/hbm/mappingexception/UnmappedAssociationExceptioTest.java | {
"start": 499,
"end": 948
} | class ____ {
@Test
@JiraKey( value = "HHH-15354")
public void mappingExceptionTest() {
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
assertThrows( MappingException.class, () -> {
new MetadataSources( ssr )
.addResource( "org/hibernate/orm/test/hbm/mappingexception/unmapped_association.hbm.xml" )
.buildMetadata();
} );
}
finally {
ssr.close();
}
}
}
| UnmappedAssociationExceptioTest |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/processor/SpringComponentProcessor.java | {
"start": 1282,
"end": 8069
} | class ____ extends AnnotationBasedComponentModelProcessor {
private static final String SPRING_COMPONENT_ANNOTATION = "org.springframework.stereotype.Component";
private static final String SPRING_PRIMARY_ANNOTATION = "org.springframework.context.annotation.Primary";
@Override
protected String getComponentModelIdentifier() {
return MappingConstantsGem.ComponentModelGem.SPRING;
}
@Override
protected List<Annotation> getTypeAnnotations(Mapper mapper) {
List<Annotation> typeAnnotations = new ArrayList<>();
if ( !isAlreadyAnnotatedAsSpringStereotype( mapper ) ) {
typeAnnotations.add( component() );
}
if ( mapper.getDecorator() != null ) {
typeAnnotations.add( qualifierDelegate() );
}
return typeAnnotations;
}
/**
* Returns the annotations that need to be added to the generated decorator, filtering out any annotations
* that are already present or represented as meta-annotations.
*
* @param decorator the decorator to process
* @return A list of annotations that should be added to the generated decorator.
*/
@Override
protected List<Annotation> getDecoratorAnnotations(Decorator decorator) {
Set<String> desiredAnnotationNames = new LinkedHashSet<>();
desiredAnnotationNames.add( SPRING_COMPONENT_ANNOTATION );
desiredAnnotationNames.add( SPRING_PRIMARY_ANNOTATION );
List<Annotation> decoratorAnnotations = decorator.getAnnotations();
if ( !decoratorAnnotations.isEmpty() ) {
Set<Element> handledElements = new HashSet<>();
for ( Annotation annotation : decoratorAnnotations ) {
removeAnnotationsPresentOnElement(
annotation.getType().getTypeElement(),
desiredAnnotationNames,
handledElements
);
if ( desiredAnnotationNames.isEmpty() ) {
// If all annotations are removed, we can stop further processing
return Collections.emptyList();
}
}
}
return desiredAnnotationNames.stream()
.map( this::createAnnotation )
.collect( Collectors.toList() );
}
@Override
protected List<Annotation> getMapperReferenceAnnotations() {
return Collections.singletonList(
autowired()
);
}
@Override
protected List<Annotation> getDelegatorReferenceAnnotations(Mapper mapper) {
return Arrays.asList(
autowired(),
qualifierDelegate()
);
}
@Override
protected boolean requiresGenerationOfDecoratorClass() {
return true;
}
private Annotation createAnnotation(String canonicalName) {
return new Annotation( getTypeFactory().getType( canonicalName ) );
}
private Annotation autowired() {
return createAnnotation( "org.springframework.beans.factory.annotation.Autowired" );
}
private Annotation qualifierDelegate() {
return new Annotation(
getTypeFactory().getType( "org.springframework.beans.factory.annotation.Qualifier" ),
Collections.singletonList(
new AnnotationElement(
AnnotationElementType.STRING,
Collections.singletonList( "delegate" )
) ) );
}
private Annotation component() {
return createAnnotation( SPRING_COMPONENT_ANNOTATION );
}
private boolean isAlreadyAnnotatedAsSpringStereotype(Mapper mapper) {
Set<String> desiredAnnotationNames = new LinkedHashSet<>();
desiredAnnotationNames.add( SPRING_COMPONENT_ANNOTATION );
List<Annotation> mapperAnnotations = mapper.getAnnotations();
if ( !mapperAnnotations.isEmpty() ) {
Set<Element> handledElements = new HashSet<>();
for ( Annotation annotation : mapperAnnotations ) {
removeAnnotationsPresentOnElement(
annotation.getType().getTypeElement(),
desiredAnnotationNames,
handledElements
);
if ( desiredAnnotationNames.isEmpty() ) {
// If all annotations are removed, we can stop further processing
return true;
}
}
}
return false;
}
/**
* Removes all the annotations and meta-annotations from {@code annotations} which are on the given element.
*
* @param element the element to check
* @param annotations the annotations to check for
* @param handledElements set of already handled elements to avoid infinite recursion
*/
private void removeAnnotationsPresentOnElement(Element element, Set<String> annotations,
Set<Element> handledElements) {
if ( annotations.isEmpty() ) {
return;
}
if ( element instanceof TypeElement &&
annotations.remove( ( (TypeElement) element ).getQualifiedName().toString() ) ) {
if ( annotations.isEmpty() ) {
// If all annotations are removed, we can stop further processing
return;
}
}
for ( AnnotationMirror annotationMirror : element.getAnnotationMirrors() ) {
Element annotationMirrorElement = annotationMirror.getAnnotationType().asElement();
// Bypass java lang annotations to improve performance avoiding unnecessary checks
if ( !isAnnotationInPackage( annotationMirrorElement, "java.lang.annotation" ) &&
!handledElements.contains( annotationMirrorElement ) ) {
handledElements.add( annotationMirrorElement );
if ( annotations.remove( ( (TypeElement) annotationMirrorElement ).getQualifiedName().toString() ) ) {
if ( annotations.isEmpty() ) {
// If all annotations are removed, we can stop further processing
return;
}
}
removeAnnotationsPresentOnElement( element, annotations, handledElements );
}
}
}
private PackageElement getPackageOf( Element element ) {
while ( element.getKind() != PACKAGE ) {
element = element.getEnclosingElement();
}
return (PackageElement) element;
}
private boolean isAnnotationInPackage(Element element, String packageFQN) {
return packageFQN.equals( getPackageOf( element ).getQualifiedName().toString() );
}
}
| SpringComponentProcessor |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/query/SimpleQueryStringFlag.java | {
"start": 702,
"end": 2536
} | enum ____ {
ALL(-1),
NONE(0),
AND(SimpleQueryStringQueryParser.AND_OPERATOR),
NOT(SimpleQueryStringQueryParser.NOT_OPERATOR),
OR(SimpleQueryStringQueryParser.OR_OPERATOR),
PREFIX(SimpleQueryStringQueryParser.PREFIX_OPERATOR),
PHRASE(SimpleQueryStringQueryParser.PHRASE_OPERATOR),
PRECEDENCE(SimpleQueryStringQueryParser.PRECEDENCE_OPERATORS),
ESCAPE(SimpleQueryStringQueryParser.ESCAPE_OPERATOR),
WHITESPACE(SimpleQueryStringQueryParser.WHITESPACE_OPERATOR),
FUZZY(SimpleQueryStringQueryParser.FUZZY_OPERATOR),
// NEAR and SLOP are synonymous, since "slop" is a more familiar term than "near"
NEAR(SimpleQueryStringQueryParser.NEAR_OPERATOR),
SLOP(SimpleQueryStringQueryParser.NEAR_OPERATOR);
final int value;
SimpleQueryStringFlag(int value) {
this.value = value;
}
public int value() {
return value;
}
static int resolveFlags(String flags) {
if (Strings.hasLength(flags) == false) {
return ALL.value();
}
int magic = NONE.value();
for (String s : Strings.delimitedListToStringArray(flags, "|")) {
if (s.isEmpty()) {
continue;
}
try {
SimpleQueryStringFlag flag = SimpleQueryStringFlag.valueOf(s.toUpperCase(Locale.ROOT));
switch (flag) {
case NONE:
return 0;
case ALL:
return -1;
default:
magic |= flag.value();
}
} catch (IllegalArgumentException iae) {
throw new IllegalArgumentException("Unknown " + SimpleQueryStringBuilder.NAME + " flag [" + s + "]");
}
}
return magic;
}
}
| SimpleQueryStringFlag |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/odps/OdpsSelectTest35.java | {
"start": 909,
"end": 3081
} | class ____ extends TestCase {
public void test_select() throws Exception {
// 1095288847322
String sql = "SELECT a.city, a.car_id, a.rrc_id, a.brand, a.car_series\n" +
" , a.title\n" +
"FROM dw_x001_cp_used_car_detail a\n" +
"WHERE status = 'PUBLISHED'\n" +
" AND model_id = 4419\n" +
" AND abs(datediff(licensed_date, '2013-07-01 00:00:00', 'mm')) <= 5;";
assertEquals("SELECT a.city, a.car_id, a.rrc_id, a.brand, a.car_series\n" +
"\t, a.title\n" +
"FROM dw_x001_cp_used_car_detail a\n" +
"WHERE status = 'PUBLISHED'\n" +
"\tAND model_id = 4419\n" +
"\tAND abs(datediff(licensed_date, '2013-07-01 00:00:00', 'mm')) <= 5;", SQLUtils.formatOdps(sql));
assertEquals("select a.city, a.car_id, a.rrc_id, a.brand, a.car_series\n" +
"\t, a.title\n" +
"from dw_x001_cp_used_car_detail a\n" +
"where status = 'PUBLISHED'\n" +
"\tand model_id = 4419\n" +
"\tand abs(datediff(licensed_date, '2013-07-01 00:00:00', 'mm')) <= 5;", SQLUtils.formatOdps(sql, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION));
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ODPS);
SQLStatement stmt = statementList.get(0);
assertEquals(1, statementList.size());
SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.ODPS);
stmt.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(9, visitor.getColumns().size());
assertEquals(2, visitor.getConditions().size());
// System.out.println(SQLUtils.formatOdps(sql));
// assertTrue(visitor.getColumns().contains(new Column("abc", "name")));
}
}
| OdpsSelectTest35 |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/model/source/selector/SelectionContext.java | {
"start": 818,
"end": 11944
} | class ____ {
private final Type sourceType;
private final SelectionCriteria selectionCriteria;
private final Method mappingMethod;
private final Type mappingTargetType;
private final Type returnType;
private final Supplier<List<ParameterBinding>> parameterBindingsProvider;
private List<ParameterBinding> parameterBindings;
private SelectionContext(Type sourceType, SelectionCriteria selectionCriteria, Method mappingMethod,
Type mappingTargetType, Type returnType,
Supplier<List<ParameterBinding>> parameterBindingsProvider) {
this.sourceType = sourceType;
this.selectionCriteria = selectionCriteria;
this.mappingMethod = mappingMethod;
this.mappingTargetType = mappingTargetType;
this.returnType = returnType;
this.parameterBindingsProvider = parameterBindingsProvider;
}
/**
* @return the source type that should be matched
*/
public Type getSourceType() {
return sourceType;
}
/**
* @return the criteria used in the selection process
*/
public SelectionCriteria getSelectionCriteria() {
return selectionCriteria;
}
/**
* @return the mapping target type that should be matched
*/
public Type getMappingTargetType() {
return mappingTargetType;
}
/**
* @return the return type that should be matched
*/
public Type getReturnType() {
return returnType;
}
/**
* @return the available parameter bindings for the matching
*/
public List<ParameterBinding> getAvailableParameterBindings() {
if ( this.parameterBindings == null ) {
this.parameterBindings = this.parameterBindingsProvider.get();
}
return parameterBindings;
}
/**
* @return the mapping method, defined in Mapper for which this selection is carried out
*/
public Method getMappingMethod() {
return mappingMethod;
}
public static SelectionContext forMappingMethods(Method mappingMethod, Type source, Type target,
SelectionCriteria criteria, TypeFactory typeFactory) {
return new SelectionContext(
source,
criteria,
mappingMethod,
target,
target,
() -> getAvailableParameterBindingsFromSourceType(
source,
target,
mappingMethod,
typeFactory
)
);
}
public static SelectionContext forLifecycleMethods(Method mappingMethod, Type targetType,
SelectionParameters selectionParameters,
TypeFactory typeFactory) {
SelectionCriteria criteria = SelectionCriteria.forLifecycleMethods( selectionParameters );
return new SelectionContext(
null,
criteria,
mappingMethod,
targetType,
mappingMethod.getResultType(),
() -> getAvailableParameterBindingsFromMethod(
mappingMethod,
targetType,
criteria.getSourceRHS(),
typeFactory
)
);
}
public static SelectionContext forFactoryMethods(Method mappingMethod, Type alternativeTarget,
SelectionParameters selectionParameters,
TypeFactory typeFactory) {
SelectionCriteria criteria = SelectionCriteria.forFactoryMethods( selectionParameters );
return new SelectionContext(
null,
criteria,
mappingMethod,
alternativeTarget,
alternativeTarget,
() -> getAvailableParameterBindingsFromMethod(
mappingMethod,
alternativeTarget,
criteria.getSourceRHS(),
typeFactory
)
);
}
public static SelectionContext forPresenceCheckMethods(Method mappingMethod,
SelectionParameters selectionParameters,
TypeFactory typeFactory) {
SelectionCriteria criteria = SelectionCriteria.forPresenceCheckMethods( selectionParameters );
Type booleanType = typeFactory.getType( Boolean.class );
return new SelectionContext(
null,
criteria,
mappingMethod,
booleanType,
booleanType,
() -> getAvailableParameterBindingsFromMethod(
mappingMethod,
booleanType,
criteria.getSourceRHS(),
typeFactory
)
);
}
public static SelectionContext forSourceParameterPresenceCheckMethods(Method mappingMethod,
SelectionParameters selectionParameters,
Parameter sourceParameter,
TypeFactory typeFactory) {
SelectionCriteria criteria = SelectionCriteria.forSourceParameterCheckMethods( selectionParameters );
Type booleanType = typeFactory.getType( Boolean.class );
return new SelectionContext(
null,
criteria,
mappingMethod,
booleanType,
booleanType,
() -> getParameterBindingsForSourceParameterPresenceCheck(
mappingMethod,
booleanType,
sourceParameter,
typeFactory
)
);
}
private static List<ParameterBinding> getParameterBindingsForSourceParameterPresenceCheck(Method method,
Type targetType,
Parameter sourceParameter,
TypeFactory typeFactory) {
List<ParameterBinding> availableParams = new ArrayList<>( method.getParameters().size() + 3 );
availableParams.add( ParameterBinding.fromParameter( sourceParameter ) );
availableParams.add( ParameterBinding.forTargetTypeBinding( typeFactory.classTypeOf( targetType ) ) );
for ( Parameter parameter : method.getParameters() ) {
if ( !parameter.isSourceParameter( ) ) {
availableParams.add( ParameterBinding.fromParameter( parameter ) );
}
}
return availableParams;
}
private static List<ParameterBinding> getAvailableParameterBindingsFromMethod(Method method, Type targetType,
SourceRHS sourceRHS,
TypeFactory typeFactory) {
List<ParameterBinding> availableParams = new ArrayList<>( method.getParameters().size() + 3 );
if ( sourceRHS != null ) {
availableParams.addAll( ParameterBinding.fromParameters( method.getParameters() ) );
availableParams.add( ParameterBinding.fromSourceRHS( sourceRHS ) );
addSourcePropertyNameBindings( availableParams, sourceRHS.getSourceType(), typeFactory );
}
else {
availableParams.addAll( ParameterBinding.fromParameters( method.getParameters() ) );
}
addTargetRelevantBindings( availableParams, targetType, typeFactory );
return availableParams;
}
private static List<ParameterBinding> getAvailableParameterBindingsFromSourceType(Type sourceType,
Type targetType,
Method mappingMethod,
TypeFactory typeFactory) {
List<ParameterBinding> availableParams = new ArrayList<>();
availableParams.add( ParameterBinding.forSourceTypeBinding( sourceType ) );
addSourcePropertyNameBindings( availableParams, sourceType, typeFactory );
for ( Parameter param : mappingMethod.getParameters() ) {
if ( param.isMappingContext() ) {
availableParams.add( ParameterBinding.fromParameter( param ) );
}
}
addTargetRelevantBindings( availableParams, targetType, typeFactory );
return availableParams;
}
private static void addSourcePropertyNameBindings(List<ParameterBinding> availableParams, Type sourceType,
TypeFactory typeFactory) {
boolean sourcePropertyNameAvailable = false;
for ( ParameterBinding pb : availableParams ) {
if ( pb.isSourcePropertyName() ) {
sourcePropertyNameAvailable = true;
break;
}
}
if ( !sourcePropertyNameAvailable ) {
availableParams.add( ParameterBinding.forSourcePropertyNameBinding( typeFactory.getType( String.class ) ) );
}
}
/**
* Adds default parameter bindings for the mapping-target and target-type if not already available.
*
* @param availableParams Already available params, new entries will be added to this list
* @param targetType Target type
*/
private static void addTargetRelevantBindings(List<ParameterBinding> availableParams, Type targetType,
TypeFactory typeFactory) {
boolean mappingTargetAvailable = false;
boolean targetTypeAvailable = false;
boolean targetPropertyNameAvailable = false;
// search available parameter bindings if mapping-target and/or target-type is available
for ( ParameterBinding pb : availableParams ) {
if ( pb.isMappingTarget() ) {
mappingTargetAvailable = true;
}
else if ( pb.isTargetType() ) {
targetTypeAvailable = true;
}
else if ( pb.isTargetPropertyName() ) {
targetPropertyNameAvailable = true;
}
}
if ( !mappingTargetAvailable ) {
availableParams.add( ParameterBinding.forMappingTargetBinding( targetType ) );
}
if ( !targetTypeAvailable ) {
availableParams.add( ParameterBinding.forTargetTypeBinding( typeFactory.classTypeOf( targetType ) ) );
}
if ( !targetPropertyNameAvailable ) {
availableParams.add( ParameterBinding.forTargetPropertyNameBinding( typeFactory.getType( String.class ) ) );
}
}
}
| SelectionContext |
java | square__moshi | moshi/src/test/java/com/squareup/moshi/internal/ClassJsonAdapterTest.java | {
"start": 12132,
"end": 12342
} | interface ____ {}
@Test
public void interfaceNotSupported() throws Exception {
assertThat(ClassJsonAdapter.Factory.create(Interface.class, NO_ANNOTATIONS, moshi)).isNull();
}
abstract static | Interface |
java | netty__netty | common/src/main/java/io/netty/util/LeakPresenceDetector.java | {
"start": 13704,
"end": 14859
} | class ____ extends Throwable {
final Thread thread = Thread.currentThread();
String message;
@Override
public synchronized String getMessage() {
if (message == null) {
if (inStaticInitializerSlow(getStackTrace())) {
message = "Resource created in static initializer. Please wrap the static initializer in " +
"LeakPresenceDetector.staticInitializer so that this resource is excluded.";
} else {
message = "Resource created outside static initializer on thread '" + thread.getName() + "' (" +
thread.getState() + "), likely leak.";
}
}
return message;
}
}
/**
* Special exception type to show that an allocation is prohibited at the moment, for example because the
* {@link ResourceScope} is closed, or because the current thread cannot be associated with a particular scope.
* <p>
* Some code in Netty will treat this exception specially to avoid allocation loops.
*/
public static final | LeakCreation |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/error/ShouldBeInSameMinute.java | {
"start": 892,
"end": 1565
} | class ____ extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldBeInSameMinute}</code>.
* @param actual the actual value in the failed assertion.
* @param other the value used in the failed assertion to compare the actual value to.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldBeInSameMinute(Date actual, Date other) {
return new ShouldBeInSameMinute(actual, other);
}
private ShouldBeInSameMinute(Date actual, Date other) {
super("%nExpecting actual:%n %s%nto have same year, month, day, hour and minute fields values as:%n %s", actual, other);
}
}
| ShouldBeInSameMinute |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/urls/UrlsBaseTest.java | {
"start": 1021,
"end": 1340
} | class ____ {
protected Failures failures;
protected Urls urls;
protected AssertionInfo info;
@BeforeEach
void setUp() throws IllegalAccessException {
failures = spy(Failures.instance());
urls = Urls.instance();
writeField(urls, "failures", failures, true);
info = someInfo();
}
}
| UrlsBaseTest |
java | spring-projects__spring-boot | module/spring-boot-graphql/src/test/java/org/springframework/boot/graphql/autoconfigure/DefaultGraphQlSchemaConditionTests.java | {
"start": 3849,
"end": 3996
} | class ____ {
@Bean
GraphQlSourceBuilderCustomizer myBuilderCustomizer() {
return (builder) -> {
};
}
}
}
| CustomCustomizerConfiguration |
java | apache__flink | flink-connectors/flink-connector-datagen/src/main/java/org/apache/flink/connector/datagen/source/GeneratorFunction.java | {
"start": 1779,
"end": 2170
} | interface ____<T, O> extends Function {
/**
* Initialization method for the function. It is called once before the actual data mapping
* methods.
*/
default void open(SourceReaderContext readerContext) throws Exception {}
/** Tear-down method for the function. */
default void close() throws Exception {}
O map(T value) throws Exception;
}
| GeneratorFunction |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/NonFinalStaticFieldTest.java | {
"start": 6971,
"end": 7149
} | interface ____ {}
""")
.addSourceLines(
"Test.java",
"""
import org.junit.jupiter.api.BeforeAll;
public | BeforeAll |
java | grpc__grpc-java | xds/src/main/java/io/grpc/xds/FilterChainSelectorManager.java | {
"start": 2532,
"end": 2823
} | class ____ {
private final long id = closerId.getAndIncrement();
private final Runnable closer;
/** {@code closer} may be run multiple times. */
public Closer(Runnable closer) {
this.closer = Preconditions.checkNotNull(closer, "closer");
}
}
private static | Closer |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/table/UnnestRowsFunction.java | {
"start": 1412,
"end": 2281
} | class ____ extends UnnestRowsFunctionBase {
public UnnestRowsFunction() {
super(false);
}
@Override
protected UserDefinedFunction createCollectionUnnestFunction(
SpecializedContext context,
LogicalType elementType,
ArrayData.ElementGetter elementGetter) {
return new CollectionUnnestFunction(context, elementType, elementGetter);
}
@Override
protected UserDefinedFunction createMapUnnestFunction(
SpecializedContext context,
RowType keyValTypes,
ArrayData.ElementGetter keyGetter,
ArrayData.ElementGetter valueGetter) {
return new MapUnnestFunction(context, keyValTypes, keyGetter, valueGetter);
}
/** Table function that unwraps the elements of a collection (array or multiset). */
public static final | UnnestRowsFunction |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/operators/BatchTask.java | {
"start": 69811,
"end": 70179
} | class ____ or implements, for type
* checking.
* @return An instance of the user code class.
*/
public static <T> T instantiateUserCode(
TaskConfig config, ClassLoader cl, Class<? super T> superClass) {
try {
T stub = config.<T>getStubWrapper(cl).getUserCodeObject(superClass, cl);
// check if the | extends |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/CamelObjectInputStream.java | {
"start": 1009,
"end": 1797
} | class ____ extends ObjectInputStream {
private final ClassLoader classLoader;
public CamelObjectInputStream(InputStream in, CamelContext context) throws IOException {
super(in);
if (context != null) {
this.classLoader = context.getApplicationContextClassLoader();
} else {
this.classLoader = null;
}
}
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws ClassNotFoundException, IOException {
if (classLoader != null) {
return Class.forName(desc.getName(), false, classLoader);
} else {
// If the application classloader is not set we just fallback to use old behaivor
return super.resolveClass(desc);
}
}
}
| CamelObjectInputStream |
java | apache__hadoop | hadoop-common-project/hadoop-kms/src/main/java/org/apache/hadoop/crypto/key/kms/server/KMSConfiguration.java | {
"start": 1151,
"end": 1228
} | class ____ load KMS configuration files.
*/
@InterfaceAudience.Private
public | to |
java | google__auto | value/src/main/java/com/google/auto/value/extension/toprettystring/processor/ClassNames.java | {
"start": 736,
"end": 901
} | class ____ {
static final String TO_PRETTY_STRING_NAME =
"com.google.auto.value.extension.toprettystring.ToPrettyString";
private ClassNames() {}
}
| ClassNames |
java | apache__flink | flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/operators/StreamSourceOperatorWatermarksTest.java | {
"start": 6720,
"end": 7094
} | class ____<T> implements SourceFunction<T> {
private volatile boolean running = true;
@Override
public void run(SourceContext<T> ctx) throws Exception {
while (running) {
Thread.sleep(20);
}
}
@Override
public void cancel() {
running = false;
}
}
}
| InfiniteSource |
java | micronaut-projects__micronaut-core | core/src/main/java/io/micronaut/core/reflect/GenericTypeUtils.java | {
"start": 1154,
"end": 1921
} | class ____ {
/**
* Resolves a single generic type argument for the given field.
*
* @param field The field
* @return The type argument or {@link Optional#empty()}
*/
public static Optional<Class<?>> resolveGenericTypeArgument(Field field) {
Type genericType = field != null ? field.getGenericType() : null;
if (genericType instanceof ParameterizedType type) {
Type[] typeArguments = type.getActualTypeArguments();
if (typeArguments.length > 0) {
Type typeArg = typeArguments[0];
return resolveParameterizedTypeArgument(typeArg);
}
}
return Optional.empty();
}
/**
* Resolve all type arguments for the given | GenericTypeUtils |
java | apache__camel | components/camel-aws/camel-aws2-ec2/src/main/java/org/apache/camel/component/aws2/ec2/client/impl/AWS2EC2ClientIAMProfileOptimizedImpl.java | {
"start": 1856,
"end": 4655
} | class ____ implements AWS2EC2InternalClient {
private static final Logger LOG = LoggerFactory.getLogger(AWS2EC2ClientIAMProfileOptimizedImpl.class);
private AWS2EC2Configuration configuration;
/**
* Constructor that uses the config file.
*/
public AWS2EC2ClientIAMProfileOptimizedImpl(AWS2EC2Configuration configuration) {
LOG.trace("Creating an AWS EC2 client for an ec2 instance with IAM temporary credentials (normal for ec2s).");
this.configuration = configuration;
}
/**
* Getting the EC2 aws client that is used.
*
* @return Ec2Client Client.
*/
@Override
public Ec2Client getEc2Client() {
Ec2Client client = null;
Ec2ClientBuilder clientBuilder = Ec2Client.builder();
ProxyConfiguration.Builder proxyConfig = null;
ApacheHttpClient.Builder httpClientBuilder = null;
if (ObjectHelper.isNotEmpty(configuration.getProxyHost()) && ObjectHelper.isNotEmpty(configuration.getProxyPort())) {
proxyConfig = ProxyConfiguration.builder();
URI proxyEndpoint = URI.create(configuration.getProxyProtocol() + "://" + configuration.getProxyHost() + ":"
+ configuration.getProxyPort());
proxyConfig.endpoint(proxyEndpoint);
httpClientBuilder = ApacheHttpClient.builder().proxyConfiguration(proxyConfig.build());
clientBuilder = clientBuilder.httpClientBuilder(httpClientBuilder);
}
if (configuration.getProfileCredentialsName() != null) {
clientBuilder = clientBuilder
.credentialsProvider(ProfileCredentialsProvider.create(configuration.getProfileCredentialsName()));
}
if (ObjectHelper.isNotEmpty(configuration.getRegion())) {
clientBuilder = clientBuilder.region(Region.of(configuration.getRegion()));
}
if (configuration.isOverrideEndpoint()) {
clientBuilder.endpointOverride(URI.create(configuration.getUriEndpointOverride()));
}
if (configuration.isTrustAllCertificates()) {
if (httpClientBuilder == null) {
httpClientBuilder = ApacheHttpClient.builder();
}
SdkHttpClient ahc = httpClientBuilder.buildWithDefaults(AttributeMap
.builder()
.put(
SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES,
Boolean.TRUE)
.build());
// set created http client to use instead of builder
clientBuilder.httpClient(ahc);
clientBuilder.httpClientBuilder(null);
}
client = clientBuilder.build();
return client;
}
}
| AWS2EC2ClientIAMProfileOptimizedImpl |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/security/authenticator/ClientAuthenticationFailureTest.java | {
"start": 2461,
"end": 6670
} | class ____ {
private static final MockTime TIME = new MockTime(50);
private NioEchoServer server;
private Map<String, Object> saslServerConfigs;
private Map<String, Object> saslClientConfigs;
private final String topic = "test";
@BeforeEach
public void setup() throws Exception {
LoginManager.closeAll();
SecurityProtocol securityProtocol = SecurityProtocol.SASL_PLAINTEXT;
saslServerConfigs = new HashMap<>();
saslServerConfigs.put(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG, Collections.singletonList("PLAIN"));
saslClientConfigs = new HashMap<>();
saslClientConfigs.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
saslClientConfigs.put(SaslConfigs.SASL_MECHANISM, "PLAIN");
TestJaasConfig testJaasConfig = TestJaasConfig.createConfiguration("PLAIN", Collections.singletonList("PLAIN"));
testJaasConfig.setClientOptions("PLAIN", TestJaasConfig.USERNAME, "anotherpassword");
server = createEchoServer(securityProtocol);
}
@AfterEach
public void teardown() throws Exception {
if (server != null)
server.close();
}
@Test
public void testConsumerWithInvalidCredentials() {
Map<String, Object> props = new HashMap<>(saslClientConfigs);
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:" + server.port());
StringDeserializer deserializer = new StringDeserializer();
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props, deserializer, deserializer)) {
assertThrows(SaslAuthenticationException.class, () -> {
consumer.assign(Collections.singleton(new TopicPartition(topic, 0)));
consumer.poll(Duration.ofSeconds(10));
});
}
}
@Test
public void testProducerWithInvalidCredentials() {
Map<String, Object> props = new HashMap<>(saslClientConfigs);
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:" + server.port());
StringSerializer serializer = new StringSerializer();
try (KafkaProducer<String, String> producer = new KafkaProducer<>(props, serializer, serializer)) {
ProducerRecord<String, String> record = new ProducerRecord<>(topic, "message");
Future<RecordMetadata> future = producer.send(record);
TestUtils.assertFutureThrows(SaslAuthenticationException.class, future);
}
}
@Test
public void testAdminClientWithInvalidCredentials() {
Map<String, Object> props = new HashMap<>(saslClientConfigs);
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:" + server.port());
try (Admin client = Admin.create(props)) {
KafkaFuture<Map<String, TopicDescription>> future = client.describeTopics(Collections.singleton("test")).allTopicNames();
TestUtils.assertFutureThrows(SaslAuthenticationException.class, future);
}
}
@Test
public void testTransactionalProducerWithInvalidCredentials() {
Map<String, Object> props = new HashMap<>(saslClientConfigs);
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:" + server.port());
props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "txclient-1");
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true");
StringSerializer serializer = new StringSerializer();
try (KafkaProducer<String, String> producer = new KafkaProducer<>(props, serializer, serializer)) {
assertThrows(SaslAuthenticationException.class, producer::initTransactions);
}
}
private NioEchoServer createEchoServer(SecurityProtocol securityProtocol) throws Exception {
return createEchoServer(ListenerName.forSecurityProtocol(securityProtocol), securityProtocol);
}
private NioEchoServer createEchoServer(ListenerName listenerName, SecurityProtocol securityProtocol) throws Exception {
return NetworkTestUtils.createEchoServer(listenerName, securityProtocol,
new TestSecurityConfig(saslServerConfigs), new CredentialCache(), TIME);
}
}
| ClientAuthenticationFailureTest |
java | apache__maven | impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/CWD.java | {
"start": 1257,
"end": 2483
} | class ____ implements Supplier<Path> {
/**
* Creates instance out of {@link Path}.
*/
public static CWD create(Path path) {
return new CWD(CliUtils.getCanonicalPath(path));
}
private Path directory;
private CWD(Path directory) {
this.directory = directory;
}
@Nonnull
@Override
public Path get() {
return directory;
}
/**
* Resolves against current cwd, resulting path is normalized.
*
* @throws NullPointerException if {@code seg} is {@code null}.
*/
@Nonnull
public Path resolve(String seg) {
requireNonNull(seg, "seg");
return directory.resolve(seg).normalize();
}
/**
* Changes current cwd, if the new path is existing directory.
*
* @throws NullPointerException if {@code seg} is {@code null}.
* @throws IllegalArgumentException if {@code seg} leads to non-existent directory.
*/
public void change(String seg) {
Path newCwd = resolve(seg);
if (Files.isDirectory(newCwd)) {
this.directory = newCwd;
} else {
throw new IllegalArgumentException("Directory '" + directory + "' does not exist");
}
}
}
| CWD |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_1100/Issue1165.java | {
"start": 424,
"end": 473
} | class ____ {
public Number __v;
}
}
| Model |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_3806/Issue3806Test.java | {
"start": 595,
"end": 3087
} | class ____ {
@ProcessorTest
void shouldNotClearGetterOnlyCollectionsInUpdateMapping() {
Map<String, String> booksByAuthor = new HashMap<>();
booksByAuthor.put( "author1", "book1" );
booksByAuthor.put( "author2", "book2" );
List<String> authors = new ArrayList<>();
authors.add( "author1" );
authors.add( "author2" );
List<String> books = new ArrayList<>();
books.add( "book1" );
books.add( "book2" );
Map<String, String> booksByPublisher = new HashMap<>();
booksByPublisher.put( "publisher1", "book1" );
booksByPublisher.put( "publisher2", "book2" );
Issue3806Mapper.Target target = new Issue3806Mapper.Target( authors, booksByAuthor );
target.setBooks( books );
target.setBooksByPublisher( booksByPublisher );
Issue3806Mapper.Target source = new Issue3806Mapper.Target( null, null );
Issue3806Mapper.INSTANCE.update( target, source );
assertThat( target.getAuthors() ).containsExactly( "author1", "author2" );
assertThat( target.getBooksByAuthor() )
.containsOnly(
entry( "author1", "book1" ),
entry( "author2", "book2" )
);
assertThat( target.getBooks() ).containsExactly( "book1", "book2" );
assertThat( target.getBooksByPublisher() )
.containsOnly(
entry( "publisher1", "book1" ),
entry( "publisher2", "book2" )
);
booksByAuthor = new HashMap<>();
booksByAuthor.put( "author3", "book3" );
authors = new ArrayList<>();
authors.add( "author3" );
books = new ArrayList<>();
books.add( "book3" );
booksByPublisher = new HashMap<>();
booksByPublisher.put( "publisher3", "book3" );
source = new Issue3806Mapper.Target( authors, booksByAuthor );
source.setBooks( books );
source.setBooksByPublisher( booksByPublisher );
Issue3806Mapper.INSTANCE.update( target, source );
assertThat( target.getAuthors() ).containsExactly( "author3" );
assertThat( target.getBooksByAuthor() )
.containsOnly(
entry( "author3", "book3" )
);
assertThat( target.getBooks() ).containsExactly( "book3" );
assertThat( target.getBooksByPublisher() )
.containsOnly(
entry( "publisher3", "book3" )
);
}
}
| Issue3806Test |
java | google__jimfs | jimfs/src/main/java/com/google/common/jimfs/PathService.java | {
"start": 1718,
"end": 9883
} | class ____ implements Comparator<JimfsPath> {
private static final Comparator<Name> DISPLAY_ROOT_COMPARATOR =
nullsLast(Name.displayComparator());
private static final Comparator<Iterable<Name>> DISPLAY_NAMES_COMPARATOR =
Comparators.lexicographical(Name.displayComparator());
private static final Comparator<Name> CANONICAL_ROOT_COMPARATOR =
nullsLast(Name.canonicalComparator());
private static final Comparator<Iterable<Name>> CANONICAL_NAMES_COMPARATOR =
Comparators.lexicographical(Name.canonicalComparator());
private final PathType type;
private final ImmutableSet<PathNormalization> displayNormalizations;
private final ImmutableSet<PathNormalization> canonicalNormalizations;
private final boolean equalityUsesCanonicalForm;
private final Comparator<Name> rootComparator;
private final Comparator<Iterable<Name>> namesComparator;
private volatile FileSystem fileSystem;
private volatile JimfsPath emptyPath;
PathService(Configuration config) {
this(
config.pathType,
config.nameDisplayNormalization,
config.nameCanonicalNormalization,
config.pathEqualityUsesCanonicalForm);
}
PathService(
PathType type,
Iterable<PathNormalization> displayNormalizations,
Iterable<PathNormalization> canonicalNormalizations,
boolean equalityUsesCanonicalForm) {
this.type = checkNotNull(type);
this.displayNormalizations = ImmutableSet.copyOf(displayNormalizations);
this.canonicalNormalizations = ImmutableSet.copyOf(canonicalNormalizations);
this.equalityUsesCanonicalForm = equalityUsesCanonicalForm;
this.rootComparator =
equalityUsesCanonicalForm ? CANONICAL_ROOT_COMPARATOR : DISPLAY_ROOT_COMPARATOR;
this.namesComparator =
equalityUsesCanonicalForm ? CANONICAL_NAMES_COMPARATOR : DISPLAY_NAMES_COMPARATOR;
}
/** Sets the file system to use for created paths. */
public void setFileSystem(FileSystem fileSystem) {
// allowed to not be JimfsFileSystem for testing purposes only
checkState(this.fileSystem == null, "may not set fileSystem twice");
this.fileSystem = checkNotNull(fileSystem);
}
/** Returns the file system this service is for. */
public FileSystem getFileSystem() {
return fileSystem;
}
/** Returns the default path separator. */
public String getSeparator() {
return type.getSeparator();
}
/** Returns an empty path which has a single name, the empty string. */
public JimfsPath emptyPath() {
JimfsPath result = emptyPath;
if (result == null) {
// use createPathInternal to avoid recursive call from createPath()
result = createPathInternal(null, ImmutableList.of(Name.EMPTY));
emptyPath = result;
return result;
}
return result;
}
/** Returns the {@link Name} form of the given string. */
public Name name(String name) {
switch (name) {
case "":
return Name.EMPTY;
case ".":
return Name.SELF;
case "..":
return Name.PARENT;
default:
String display = PathNormalization.normalize(name, displayNormalizations);
String canonical = PathNormalization.normalize(name, canonicalNormalizations);
return Name.create(display, canonical);
}
}
/** Returns the {@link Name} forms of the given strings. */
@VisibleForTesting
List<Name> names(Iterable<String> names) {
List<Name> result = new ArrayList<>();
for (String name : names) {
result.add(name(name));
}
return result;
}
/** Returns a root path with the given name. */
public JimfsPath createRoot(Name root) {
return createPath(checkNotNull(root), ImmutableList.<Name>of());
}
/** Returns a single filename path with the given name. */
public JimfsPath createFileName(Name name) {
return createPath(null, ImmutableList.of(name));
}
/** Returns a relative path with the given names. */
public JimfsPath createRelativePath(Iterable<Name> names) {
return createPath(null, ImmutableList.copyOf(names));
}
/** Returns a path with the given root (or no root, if null) and the given names. */
public JimfsPath createPath(@Nullable Name root, Iterable<Name> names) {
ImmutableList<Name> nameList = ImmutableList.copyOf(Iterables.filter(names, NOT_EMPTY));
if (root == null && nameList.isEmpty()) {
// ensure the canonical empty path (one empty string name) is used rather than a path with
// no root and no names
return emptyPath();
}
return createPathInternal(root, nameList);
}
/** Returns a path with the given root (or no root, if null) and the given names. */
final JimfsPath createPathInternal(@Nullable Name root, Iterable<Name> names) {
return new JimfsPath(this, root, names);
}
/** Parses the given strings as a path. */
public JimfsPath parsePath(String first, String... more) {
String joined = type.joiner().join(Iterables.filter(Lists.asList(first, more), NOT_EMPTY));
return toPath(type.parsePath(joined));
}
private JimfsPath toPath(ParseResult parsed) {
Name root = parsed.root() == null ? null : name(parsed.root());
Iterable<Name> names = names(parsed.names());
return createPath(root, names);
}
/** Returns the string form of the given path. */
public String toString(JimfsPath path) {
Name root = path.root();
String rootString = root == null ? null : root.toString();
Iterable<String> names = Iterables.transform(path.names(), Functions.toStringFunction());
return type.toString(rootString, names);
}
/** Creates a hash code for the given path. */
public int hash(JimfsPath path) {
// Note: JimfsPath.equals() is implemented using the compare() method below;
// equalityUsesCanonicalForm is taken into account there via the namesComparator, which is set
// at construction time.
int hash = 31;
hash = 31 * hash + getFileSystem().hashCode();
final Name root = path.root();
final ImmutableList<Name> names = path.names();
if (equalityUsesCanonicalForm) {
// use hash codes of names themselves, which are based on the canonical form
hash = 31 * hash + (root == null ? 0 : root.hashCode());
for (Name name : names) {
hash = 31 * hash + name.hashCode();
}
} else {
// use hash codes from toString() form of names
hash = 31 * hash + (root == null ? 0 : root.toString().hashCode());
for (Name name : names) {
hash = 31 * hash + name.toString().hashCode();
}
}
return hash;
}
@Override
public int compare(JimfsPath a, JimfsPath b) {
Comparator<JimfsPath> comparator =
Comparator.comparing(JimfsPath::root, rootComparator)
.thenComparing(JimfsPath::names, namesComparator);
return comparator.compare(a, b);
}
/**
* Returns the URI for the given path. The given file system URI is the base against which the
* path is resolved to create the returned URI.
*/
public URI toUri(URI fileSystemUri, JimfsPath path) {
checkArgument(path.isAbsolute(), "path (%s) must be absolute", path);
String root = String.valueOf(path.root());
Iterable<String> names = Iterables.transform(path.names(), Functions.toStringFunction());
return type.toUri(fileSystemUri, root, names, Files.isDirectory(path, NOFOLLOW_LINKS));
}
/** Converts the path of the given URI into a path for this file system. */
public JimfsPath fromUri(URI uri) {
return toPath(type.fromUri(uri));
}
/**
* Returns a {@link PathMatcher} for the given syntax and pattern as specified by {@link
* FileSystem#getPathMatcher(String)}.
*/
public PathMatcher createPathMatcher(String syntaxAndPattern) {
return PathMatchers.getPathMatcher(
syntaxAndPattern,
type.getSeparator() + type.getOtherSeparators(),
equalityUsesCanonicalForm ? canonicalNormalizations : displayNormalizations);
}
private static final Predicate<Object> NOT_EMPTY =
new Predicate<Object>() {
@Override
public boolean apply(Object input) {
return !input.toString().isEmpty();
}
};
}
| PathService |
java | quarkusio__quarkus | extensions/spring-data-jpa/deployment/src/main/java/io/quarkus/spring/data/deployment/MethodNameParser.java | {
"start": 35153,
"end": 35634
} | class ____
return fieldInfo.type().name();
}
TypeVariable typeVariable = fieldInfo.type().asTypeVariable();
// entire hierarchy as list: entityClass, superclass of entityClass, superclass of the latter, ...
List<ClassInfo> classInfos = new ArrayList<>();
classInfos.add(entityClass);
classInfos.addAll(parentSuperClassInfos.subList(0, superClassIndex + 1));
// go down the hierarchy until ideally a concrete | hierarchy |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/metrics/MicrometerOptions.java | {
"start": 1254,
"end": 4075
} | class ____ {
public static final boolean DEFAULT_ENABLED = true;
public static final boolean DEFAULT_HISTOGRAM = false;
public static final boolean DEFAULT_LOCAL_DISTINCTION = false;
public static final Duration DEFAULT_MAX_LATENCY = Duration.ofMinutes(5L);
public static final Duration DEFAULT_MIN_LATENCY = Duration.ofMillis(1L);
public static final double[] DEFAULT_TARGET_PERCENTILES = new double[] { 0.50, 0.90, 0.95, 0.99, 0.999 };
private static final MicrometerOptions DISABLED = builder().disable().build();
private final Builder builder;
private final boolean enabled;
private final boolean histogram;
private final boolean localDistinction;
private final Duration maxLatency;
private final Duration minLatency;
private final Predicate<RedisCommand<?, ?, ?>> metricsFilter;
private final Tags tags;
private final double[] targetPercentiles;
protected MicrometerOptions(Builder builder) {
this.builder = builder;
this.enabled = builder.enabled;
this.histogram = builder.histogram;
this.localDistinction = builder.localDistinction;
this.metricsFilter = builder.metricsFilter;
this.maxLatency = builder.maxLatency;
this.minLatency = builder.minLatency;
this.tags = builder.tags;
this.targetPercentiles = builder.targetPercentiles;
}
/**
* Create a new {@link MicrometerOptions} instance using default settings.
*
* @return a new instance of {@link MicrometerOptions} instance using default settings
*/
public static MicrometerOptions create() {
return builder().build();
}
/**
* Create a {@link MicrometerOptions} instance with disabled event emission.
*
* @return a new instance of {@link MicrometerOptions} with disabled event emission
*/
public static MicrometerOptions disabled() {
return DISABLED;
}
/**
* Returns a new {@link MicrometerOptions.Builder} to construct {@link MicrometerOptions}.
*
* @return a new {@link MicrometerOptions.Builder} to construct {@link MicrometerOptions}.
*/
public static MicrometerOptions.Builder builder() {
return new MicrometerOptions.Builder();
}
/**
* Returns a builder to create new {@link MicrometerOptions} whose settings are replicated from the current
* {@link MicrometerOptions}.
*
* @return a a {@link CommandLatencyCollectorOptions.Builder} to create new {@link MicrometerOptions} whose settings are
* replicated from the current {@link MicrometerOptions}
*/
public MicrometerOptions.Builder mutate() {
return this.builder;
}
/**
* Builder for {@link MicrometerOptions}.
*/
public static | MicrometerOptions |
java | apache__maven | compat/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ReleaseArtifactTransformation.java | {
"start": 1705,
"end": 3690
} | class ____ extends AbstractVersionTransformation {
@Override
public void transformForResolve(Artifact artifact, RepositoryRequest request)
throws ArtifactResolutionException, ArtifactNotFoundException {
if (Artifact.RELEASE_VERSION.equals(artifact.getVersion())) {
try {
String version = resolveVersion(artifact, request);
if (Artifact.RELEASE_VERSION.equals(version)) {
throw new ArtifactNotFoundException("Unable to determine the release version", artifact);
}
artifact.setBaseVersion(version);
artifact.updateVersion(version, request.getLocalRepository());
} catch (RepositoryMetadataResolutionException e) {
throw new ArtifactResolutionException(e.getMessage(), artifact, e);
}
}
}
@Override
public void transformForInstall(Artifact artifact, ArtifactRepository localRepository) {
ArtifactMetadata metadata = createMetadata(artifact);
artifact.addMetadata(metadata);
}
@Override
public void transformForDeployment(
Artifact artifact, ArtifactRepository remoteRepository, ArtifactRepository localRepository) {
ArtifactMetadata metadata = createMetadata(artifact);
artifact.addMetadata(metadata);
}
private ArtifactMetadata createMetadata(Artifact artifact) {
Versioning versioning = new Versioning();
// TODO Should this be changed for MNG-6754 too?
versioning.updateTimestamp();
versioning.addVersion(artifact.getVersion());
if (artifact.isRelease()) {
versioning.setRelease(artifact.getVersion());
}
return new ArtifactRepositoryMetadata(artifact, versioning);
}
@Override
protected String constructVersion(Versioning versioning, String baseVersion) {
return versioning.getRelease();
}
}
| ReleaseArtifactTransformation |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/java/typeutils/runtime/kryo/KryoSerializerSnapshotData.java | {
"start": 15555,
"end": 15831
} | class ____ class "
+ registeredClassname
+ " has changed and is no longer valid; using a dummy Kryo serializer that should be replaced"
+ " as soon as a new Kryo serializer for the | for |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java | {
"start": 41452,
"end": 41704
} | class ____ {
@RequestMapping("/unprotected")
String unprotected() {
return "ok";
}
@RequestMapping("/protected")
String protectedMethod(@AuthenticationPrincipal String name) {
return name;
}
}
@RestController
static | BasicController |
java | apache__flink | flink-table/flink-table-common/src/test/java/org/apache/flink/table/utils/LegacyRowResource.java | {
"start": 1123,
"end": 1505
} | class ____ extends ExternalResource {
public static final LegacyRowResource INSTANCE = new LegacyRowResource();
private LegacyRowResource() {
// singleton
}
@Override
public void before() {
RowUtils.USE_LEGACY_TO_STRING = true;
}
@Override
public void after() {
RowUtils.USE_LEGACY_TO_STRING = false;
}
}
| LegacyRowResource |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreRemoveAppEvent.java | {
"start": 973,
"end": 1287
} | class ____ extends RMStateStoreEvent {
ApplicationStateData appState;
RMStateStoreRemoveAppEvent(ApplicationStateData appState) {
super(RMStateStoreEventType.REMOVE_APP);
this.appState = appState;
}
public ApplicationStateData getAppState() {
return appState;
}
}
| RMStateStoreRemoveAppEvent |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/web/server/SessionManagementSpecTests.java | {
"start": 16517,
"end": 18176
} | class ____ {
static int maxSessions = 1;
static boolean preventLogin = true;
ReactiveAuthenticationManager manager = mock(ReactiveAuthenticationManager.class);
ServerAuthenticationConverter authenticationConverter = mock(ServerAuthenticationConverter.class);
ServerOAuth2AuthorizationRequestResolver resolver = mock(ServerOAuth2AuthorizationRequestResolver.class);
@Bean
SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http,
DefaultWebSessionManager webSessionManager) {
// @formatter:off
http
.authorizeExchange((authorize) -> authorize
.anyExchange().authenticated()
)
.oauth2Login((oauth2Login) -> oauth2Login
.authenticationConverter(this.authenticationConverter)
.authenticationManager(this.manager)
.authorizationRequestResolver(this.resolver)
)
.sessionManagement((sessionManagement) -> sessionManagement
.concurrentSessions((concurrentSessions) -> concurrentSessions
.maximumSessions(SessionLimit.of(maxSessions))
.maximumSessionsExceededHandler(preventLogin
? new PreventLoginServerMaximumSessionsExceededHandler()
: new InvalidateLeastUsedServerMaximumSessionsExceededHandler(webSessionManager.getSessionStore()))
)
);
// @formatter:on
return http.build();
}
@Bean
InMemoryReactiveClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryReactiveClientRegistrationRepository(
TestClientRegistrations.clientCredentials().build());
}
}
@Configuration
@EnableWebFlux
@EnableWebFluxSecurity
@Import(Config.class)
static | OAuth2LoginConcurrentSessionsConfig |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractPartitionAssignor.java | {
"start": 6474,
"end": 8310
} | class ____ implements Comparable<MemberInfo> {
public final String memberId;
public final Optional<String> groupInstanceId;
public final Optional<String> rackId;
public MemberInfo(String memberId, Optional<String> groupInstanceId, Optional<String> rackId) {
this.memberId = memberId;
this.groupInstanceId = groupInstanceId;
this.rackId = rackId;
}
public MemberInfo(String memberId, Optional<String> groupInstanceId) {
this(memberId, groupInstanceId, Optional.empty());
}
@Override
public int compareTo(MemberInfo otherMemberInfo) {
if (this.groupInstanceId.isPresent() &&
otherMemberInfo.groupInstanceId.isPresent()) {
return this.groupInstanceId.get()
.compareTo(otherMemberInfo.groupInstanceId.get());
} else if (this.groupInstanceId.isPresent()) {
return -1;
} else if (otherMemberInfo.groupInstanceId.isPresent()) {
return 1;
} else {
return this.memberId.compareTo(otherMemberInfo.memberId);
}
}
@Override
public boolean equals(Object o) {
return o instanceof MemberInfo && this.memberId.equals(((MemberInfo) o).memberId);
}
/**
* We could just use member.id to be the hashcode, since it's unique
* across the group.
*/
@Override
public int hashCode() {
return memberId.hashCode();
}
@Override
public String toString() {
return "MemberInfo [member.id: " + memberId
+ ", group.instance.id: " + groupInstanceId.orElse("{}")
+ "]";
}
}
}
| MemberInfo |
java | google__dagger | javatests/dagger/functional/membersinject/MembersInjectTest.java | {
"start": 3649,
"end": 3717
} | class ____ extends C {
// No injected members
}
public static | B |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/util/MoreAnnotationsTest.java | {
"start": 7538,
"end": 8598
} | class ____ {}
}
// BUG: Diagnostic contains: C
@A Outer.@B Middle.@C Inner x;
// BUG: Diagnostic contains: B
Outer.@A MiddleStatic.@B Inner y;
// BUG: Diagnostic contains: A
Outer.MiddleStatic.@A InnerStatic z;
// BUG: Diagnostic contains: C
abstract @A Outer.@B Middle.@C Inner f();
// BUG: Diagnostic contains: B
abstract Outer.@A MiddleStatic.@B Inner g();
// BUG: Diagnostic contains: A
abstract Outer.MiddleStatic.@A InnerStatic h();
}
""")
.doTest();
}
@Test
public void explicitlyAnnotatedLambdaTest() {
CompilationTestHelper.newInstance(GetTopLevelTypeAttributesTester.class, getClass())
.addSourceLines(
"Annos.java",
"""
import static java.lang.annotation.ElementType.TYPE_USE;
import java.lang.annotation.Target;
@Target(TYPE_USE)
@ | InnerStatic |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/FreeSlotTrackerTestUtils.java | {
"start": 1017,
"end": 1581
} | class ____ {
/**
* Create default free slot tracker for provided slots.
*
* @param freeSlots slots to track
* @return default free slot tracker
*/
public static DefaultFreeSlotTracker createDefaultFreeSlotTracker(
Map<AllocationID, PhysicalSlot> freeSlots) {
return new DefaultFreeSlotTracker(
freeSlots.keySet(),
freeSlots::get,
id -> new TestingFreeSlotTracker.TestingFreeSlotInfo(freeSlots.get(id)),
ignored -> 0d);
}
}
| FreeSlotTrackerTestUtils |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerIdempotentKeyChangedIssueTest.java | {
"start": 1108,
"end": 2508
} | class ____ extends ContextTestSupport {
private static final String TEST_FILE_NAME = "hello" + UUID.randomUUID() + ".txt";
private Endpoint endpoint;
@Test
public void testFile() throws Exception {
getMockEndpoint("mock:file").expectedBodiesReceived("Hello World");
template.sendBodyAndHeader(endpoint, "Hello World", Exchange.FILE_NAME, TEST_FILE_NAME);
context.getRouteController().startAllRoutes();
assertMockEndpointsSatisfied();
oneExchangeDone.matches(5, TimeUnit.SECONDS);
resetMocks();
getMockEndpoint("mock:file").expectedBodiesReceived("Hello World Again");
template.sendBodyAndHeader(endpoint, "Hello World Again", Exchange.FILE_NAME, TEST_FILE_NAME);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
endpoint = endpoint(
fileUri("?noop=true&readLock=changed&initialDelay=0&delay=10&readLockCheckInterval=100"
+ "&idempotentKey=${file:onlyname}-${file:size}-${date:file:yyyyMMddHHmmss}"));
from(endpoint).autoStartup(false).convertBodyTo(String.class).to("log:file").to("mock:file");
}
};
}
}
| FileConsumerIdempotentKeyChangedIssueTest |
java | apache__dubbo | dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2SecurityManager.java | {
"start": 6928,
"end": 8515
} | class ____ found
return null;
}
public boolean checkIfDisAllow(String typeName) {
return disAllowedList.stream().anyMatch(typeName::startsWith);
}
public boolean isCheckSerializable() {
return checkSerializable;
}
public Class<?> loadClassDirectly(String typeName) {
Class<?> clazz = classCache.get(typeName);
if (clazz == null && checkIfDisAllow(typeName)) {
clazz = DenyClass.class;
String msg = "[Serialization Security] Serialized class " + typeName + " is in disAllow list. "
+ "Current mode is `WARN`, will disallow to deserialize it by default. "
+ "Please add it into security/serialize.allowlist or follow FAQ to configure it.";
if (serializeSecurityManager.getWarnedClasses().add(typeName)) {
logger.warn(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg);
}
}
if (clazz == null) {
clazz = TypeUtils.getMapping(typeName);
}
if (clazz == null) {
clazz = loadClass(typeName);
}
if (clazz != null) {
Class<?> origin = classCache.putIfAbsent(typeName, clazz);
if (origin != null) {
clazz = origin;
}
}
if (clazz == DenyClass.class) {
return null;
}
return clazz;
}
}
private static | not |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/method/annotation/HandlerMethodValidator.java | {
"start": 6564,
"end": 7087
} | class ____ implements MethodValidationAdapter.ObjectNameResolver {
@Override
public String resolveName(MethodParameter param, @Nullable Object value) {
if (param.hasParameterAnnotation(RequestBody.class) || param.hasParameterAnnotation(RequestPart.class)) {
return Conventions.getVariableNameForParameter(param);
}
else {
return (param.getParameterIndex() != -1 ?
ModelFactory.getNameForParameter(param) :
ModelFactory.getNameForReturnValue(value, param));
}
}
}
}
| WebObjectNameResolver |
java | elastic__elasticsearch | x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/CcrSingleNodeTestCase.java | {
"start": 1944,
"end": 6817
} | class ____ extends ESSingleNodeTestCase {
@Override
protected Settings nodeSettings() {
Settings.Builder builder = Settings.builder();
builder.put(XPackSettings.SECURITY_ENABLED.getKey(), false);
builder.put(XPackSettings.WATCHER_ENABLED.getKey(), false);
builder.put(XPackSettings.MACHINE_LEARNING_ENABLED.getKey(), false);
builder.put(LicenseSettings.SELF_GENERATED_LICENSE_TYPE.getKey(), "trial");
// Let cluster state api return quickly in order to speed up auto follow tests:
builder.put(CcrSettings.CCR_WAIT_FOR_METADATA_TIMEOUT.getKey(), TimeValue.timeValueMillis(100));
return builder.build();
}
@Override
protected Collection<Class<? extends Plugin>> getPlugins() {
return Collections.singletonList(LocalStateCcr.class);
}
@Before
public void setupLocalRemote() throws Exception {
ClusterUpdateSettingsRequest updateSettingsRequest = new ClusterUpdateSettingsRequest(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT);
String address = getInstanceFromNode(TransportService.class).boundAddress().publishAddress().toString();
updateSettingsRequest.transientSettings(Settings.builder().put("cluster.remote.local.seeds", address));
assertAcked(client().admin().cluster().updateSettings(updateSettingsRequest).actionGet());
List<RemoteConnectionInfo> infos = client().execute(TransportRemoteInfoAction.TYPE, new RemoteInfoRequest()).get().getInfos();
assertThat(infos.size(), equalTo(1));
assertTrue(infos.get(0).isConnected());
}
@Before
public void waitForTrialLicenseToBeGenerated() throws Exception {
assertBusy(() -> assertNotNull(getInstanceFromNode(ClusterService.class).state().metadata().custom(LicensesMetadata.TYPE)));
}
@After
public void purgeCCRMetadata() throws Exception {
ClusterService clusterService = getInstanceFromNode(ClusterService.class);
removeCCRRelatedMetadataFromClusterState(clusterService);
}
@After
public void removeLocalRemote() throws Exception {
ClusterUpdateSettingsRequest updateSettingsRequest = new ClusterUpdateSettingsRequest(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT);
updateSettingsRequest.transientSettings(Settings.builder().put("cluster.remote.local.seeds", (String) null));
assertAcked(client().admin().cluster().updateSettings(updateSettingsRequest).actionGet());
assertBusy(() -> {
List<RemoteConnectionInfo> infos = client().execute(TransportRemoteInfoAction.TYPE, new RemoteInfoRequest()).get().getInfos();
assertThat(infos.size(), equalTo(0));
});
}
protected AutoFollowStats getAutoFollowStats() {
return client().execute(CcrStatsAction.INSTANCE, new CcrStatsAction.Request(TEST_REQUEST_TIMEOUT)).actionGet().getAutoFollowStats();
}
protected ResumeFollowAction.Request getResumeFollowRequest(String followerIndex) {
ResumeFollowAction.Request request = new ResumeFollowAction.Request(TEST_REQUEST_TIMEOUT);
request.setFollowerIndex(followerIndex);
request.getParameters().setMaxRetryDelay(TimeValue.timeValueMillis(1));
request.getParameters().setReadPollTimeout(TimeValue.timeValueMillis(1));
if (randomBoolean()) {
request.masterNodeTimeout(TimeValue.timeValueSeconds(randomFrom(10, 20, 30)));
}
return request;
}
protected PutFollowAction.Request getPutFollowRequest(String leaderIndex, String followerIndex) {
PutFollowAction.Request request = new PutFollowAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT);
request.setRemoteCluster("local");
request.setLeaderIndex(leaderIndex);
request.setFollowerIndex(followerIndex);
request.getParameters().setMaxRetryDelay(TimeValue.timeValueMillis(1));
request.getParameters().setReadPollTimeout(TimeValue.timeValueMillis(1));
request.waitForActiveShards(ActiveShardCount.ONE);
if (randomBoolean()) {
request.masterNodeTimeout(TimeValue.timeValueSeconds(randomFrom(10, 20, 30)));
}
return request;
}
protected void ensureEmptyWriteBuffers() throws Exception {
assertBusy(() -> {
FollowStatsAction.StatsResponses statsResponses = client().execute(
FollowStatsAction.INSTANCE,
new FollowStatsAction.StatsRequest()
).actionGet();
for (FollowStatsAction.StatsResponse statsResponse : statsResponses.getStatsResponses()) {
ShardFollowNodeTaskStatus status = statsResponse.status();
assertThat(status.writeBufferOperationCount(), equalTo(0));
assertThat(status.writeBufferSizeInBytes(), equalTo(0L));
}
});
}
}
| CcrSingleNodeTestCase |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/iterable/IterableAssert_first_Test.java | {
"start": 1294,
"end": 1927
} | class ____ {
private final Iterable<String> iterable = asList("Homer", "Marge", "Lisa", "Bart", "Maggie");
@Test
void should_fail_if_iterable_is_empty() {
// GIVEN
Iterable<String> iterable = emptyList();
// WHEN
var assertionError = expectAssertionError(() -> assertThat(iterable).first());
// THEN
then(assertionError).hasMessage(actualIsEmpty());
}
@Test
void should_pass_allowing_object_assertions_if_iterable_contains_at_least_one_element() {
// WHEN
ObjectAssert<String> result = assertThat(iterable).first();
// THEN
result.isEqualTo("Homer");
}
}
| IterableAssert_first_Test |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java | {
"start": 8173,
"end": 8514
} | class ____ implements ClientHttpRequestInterceptor {
private int invocationCount = 0;
@Override
public ClientHttpResponse intercept(
HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
invocationCount++;
return execution.execute(request, body);
}
}
private static | NoOpInterceptor |
java | google__auto | value/src/main/java/com/google/auto/value/processor/TemplateVars.java | {
"start": 1470,
"end": 1840
} | class ____ a set of fields that are template variables, and an implementation of the
* {@link #parsedTemplate()} method which is the template to substitute them into. Once the values
* of the fields have been assigned, the {@link #toText()} method returns the result of substituting
* them into the template.
*
* <p>The subclass may be a direct subclass of this | defines |
java | apache__spark | common/network-common/src/main/java/org/apache/spark/network/util/LevelDBProvider.java | {
"start": 1471,
"end": 3947
} | class ____ {
private static final SparkLogger logger = SparkLoggerFactory.getLogger(LevelDBProvider.class);
public static DB initLevelDB(File dbFile, StoreVersion version, ObjectMapper mapper) throws
IOException {
DB tmpDb = null;
if (dbFile != null) {
Options options = new Options();
options.createIfMissing(false);
options.logger(new LevelDBLogger());
try {
tmpDb = JniDBFactory.factory.open(dbFile, options);
} catch (NativeDB.DBException e) {
if (e.isNotFound() || e.getMessage().contains(" does not exist ")) {
logger.info("Creating state database at {}", MDC.of(LogKeys.PATH, dbFile));
options.createIfMissing(true);
try {
tmpDb = JniDBFactory.factory.open(dbFile, options);
} catch (NativeDB.DBException dbExc) {
throw new IOException("Unable to create state store", dbExc);
}
} else {
// the leveldb file seems to be corrupt somehow. Lets just blow it away and create a new
// one, so we can keep processing new apps
logger.error("error opening leveldb file {}. Creating new file, will not be able to " +
"recover state for existing applications", e, MDC.of(LogKeys.PATH, dbFile));
if (dbFile.isDirectory()) {
for (File f : dbFile.listFiles()) {
if (!f.delete()) {
logger.warn("error deleting {}", MDC.of(LogKeys.PATH, f.getPath()));
}
}
}
if (!dbFile.delete()) {
logger.warn("error deleting {}", MDC.of(LogKeys.PATH, dbFile.getPath()));
}
options.createIfMissing(true);
try {
tmpDb = JniDBFactory.factory.open(dbFile, options);
} catch (NativeDB.DBException dbExc) {
throw new IOException("Unable to create state store", dbExc);
}
}
}
// if there is a version mismatch, we throw an exception, which means the service is unusable
try {
checkVersion(tmpDb, version, mapper);
} catch (IOException ioe) {
tmpDb.close();
throw ioe;
}
}
return tmpDb;
}
@VisibleForTesting
static DB initLevelDB(File file) throws IOException {
Options options = new Options();
options.createIfMissing(true);
JniDBFactory factory = new JniDBFactory();
return factory.open(file, options);
}
private static | LevelDBProvider |
java | apache__camel | components/camel-grape/src/main/java/org/apache/camel/component/grape/FilePatchesRepository.java | {
"start": 1171,
"end": 2563
} | class ____ implements PatchesRepository {
private final File repository;
public FilePatchesRepository() {
this(Paths.get(SystemUtils.getUserHome().getAbsolutePath(), ".camel", "patches").toFile());
}
public FilePatchesRepository(File repository) {
try {
if (!repository.exists()) {
if (repository.getParentFile() != null) {
repository.getParentFile().mkdirs();
}
repository.createNewFile();
}
} catch (IOException e) {
throw new IOError(e);
}
this.repository = repository;
}
@Override
public void install(String coordinates) {
try {
FileUtils.writeStringToFile(repository, coordinates + "\n", StandardCharsets.UTF_8.name(), true);
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public List<String> listPatches() {
try (FileReader reader = new FileReader(repository)) {
return IOUtils.readLines(reader);
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void clear() {
try {
repository.delete();
repository.createNewFile();
} catch (IOException e) {
throw new IOError(e);
}
}
}
| FilePatchesRepository |
java | hibernate__hibernate-orm | hibernate-vector/src/test/java/org/hibernate/vector/DoubleVectorTest.java | {
"start": 1798,
"end": 9634
} | class ____ {
private static final double[] V1 = new double[]{ 1, 2, 3 };
private static final double[] V2 = new double[]{ 4, 5, 6 };
@BeforeEach
public void prepareData(SessionFactoryScope scope) {
scope.inTransaction( em -> {
em.persist( new VectorEntity( 1L, V1 ) );
em.persist( new VectorEntity( 2L, V2 ) );
} );
}
@AfterEach
public void cleanup(SessionFactoryScope scope) {
scope.inTransaction( em -> {
em.createMutationQuery( "delete from VectorEntity" ).executeUpdate();
} );
}
@Test
public void testRead(SessionFactoryScope scope) {
scope.inTransaction( em -> {
VectorEntity tableRecord;
tableRecord = em.find( VectorEntity.class, 1L );
assertArrayEquals( new double[]{ 1, 2, 3 }, tableRecord.getTheVector(), 0 );
tableRecord = em.find( VectorEntity.class, 2L );
assertArrayEquals( new double[]{ 4, 5, 6 }, tableRecord.getTheVector(), 0 );
} );
}
@Test
public void testCast(SessionFactoryScope scope) {
scope.inTransaction( em -> {
final Tuple vector = em.createSelectionQuery( "select cast(e.theVector as string), cast('[1, 1, 1]' as double_vector(3)) from VectorEntity e where e.id = 1", Tuple.class )
.getSingleResult();
assertArrayEquals( new double[]{ 1, 2, 3 }, VectorHelper.parseDoubleVector( vector.get( 0, String.class ) ) );
assertArrayEquals( new double[]{ 1, 1, 1 }, vector.get( 1, double[].class ) );
} );
}
@Test
@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsCosineDistance.class)
public void testCosineDistance(SessionFactoryScope scope) {
scope.inTransaction( em -> {
final double[] vector = new double[]{ 1, 1, 1 };
final List<Tuple> results = em.createSelectionQuery( "select e.id, cosine_distance(e.theVector, :vec) from VectorEntity e order by e.id", Tuple.class )
.setParameter( "vec", vector )
.getResultList();
assertEquals( 2, results.size() );
assertEquals( 1L, results.get( 0 ).get( 0 ) );
assertEquals( cosineDistance( V1, vector ), results.get( 0 ).get( 1, double.class ), 0.0000001D );
assertEquals( 2L, results.get( 1 ).get( 0 ) );
assertEquals( cosineDistance( V2, vector ), results.get( 1 ).get( 1, double.class ), 0.0000001D );
} );
}
@Test
@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsEuclideanDistance.class)
public void testEuclideanDistance(SessionFactoryScope scope) {
scope.inTransaction( em -> {
final double[] vector = new double[]{ 1, 1, 1 };
final List<Tuple> results = em.createSelectionQuery( "select e.id, euclidean_distance(e.theVector, :vec) from VectorEntity e order by e.id", Tuple.class )
.setParameter( "vec", vector )
.getResultList();
assertEquals( 2, results.size() );
assertEquals( 1L, results.get( 0 ).get( 0 ) );
assertEquals( euclideanDistance( V1, vector ), results.get( 0 ).get( 1, double.class ), 0.00002D );
assertEquals( 2L, results.get( 1 ).get( 0 ) );
assertEquals( euclideanDistance( V2, vector ), results.get( 1 ).get( 1, double.class ), 0.00002D);
} );
}
@Test
@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsEuclideanSquaredDistance.class)
public void testEuclideanSquaredDistance(SessionFactoryScope scope) {
scope.inTransaction( em -> {
final double[] vector = new double[]{ 1, 1, 1 };
final List<Tuple> results = em.createSelectionQuery( "select e.id, euclidean_squared_distance(e.theVector, :vec) from VectorEntity e order by e.id", Tuple.class )
.setParameter( "vec", vector )
.getResultList();
assertEquals( 2, results.size() );
assertEquals( 1L, results.get( 0 ).get( 0 ) );
assertEquals( euclideanSquaredDistance( V1, vector ), results.get( 0 ).get( 1, double.class ), 0.00002D );
assertEquals( 2L, results.get( 1 ).get( 0 ) );
assertEquals( euclideanSquaredDistance( V2, vector ), results.get( 1 ).get( 1, double.class ), 0.00002D);
} );
}
@Test
@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsTaxicabDistance.class)
public void testTaxicabDistance(SessionFactoryScope scope) {
scope.inTransaction( em -> {
final double[] vector = new double[]{ 1, 1, 1 };
final List<Tuple> results = em.createSelectionQuery( "select e.id, taxicab_distance(e.theVector, :vec) from VectorEntity e order by e.id", Tuple.class )
.setParameter( "vec", vector )
.getResultList();
assertEquals( 2, results.size() );
assertEquals( 1L, results.get( 0 ).get( 0 ) );
assertEquals( taxicabDistance( V1, vector ), results.get( 0 ).get( 1, double.class ), 0D );
assertEquals( 2L, results.get( 1 ).get( 0 ) );
assertEquals( taxicabDistance( V2, vector ), results.get( 1 ).get( 1, double.class ), 0D );
} );
}
@Test
@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsInnerProduct.class)
public void testInnerProduct(SessionFactoryScope scope) {
scope.inTransaction( em -> {
final double[] vector = new double[]{ 1, 1, 1 };
final List<Tuple> results = em.createSelectionQuery( "select e.id, inner_product(e.theVector, :vec), negative_inner_product(e.theVector, :vec) from VectorEntity e order by e.id", Tuple.class )
.setParameter( "vec", vector )
.getResultList();
assertEquals( 2, results.size() );
assertEquals( 1L, results.get( 0 ).get( 0 ) );
assertEquals( innerProduct( V1, vector ), results.get( 0 ).get( 1, double.class ), 0D );
assertEquals( innerProduct( V1, vector ) * -1, results.get( 0 ).get( 2, double.class ), 0D );
assertEquals( 2L, results.get( 1 ).get( 0 ) );
assertEquals( innerProduct( V2, vector ), results.get( 1 ).get( 1, double.class ), 0D );
assertEquals( innerProduct( V2, vector ) * -1, results.get( 1 ).get( 2, double.class ), 0D );
} );
}
@Test
@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsHammingDistance.class)
public void testHammingDistance(SessionFactoryScope scope) {
scope.inTransaction( em -> {
final double[] vector = new double[]{ 1, 1, 1 };
final List<Tuple> results = em.createSelectionQuery( "select e.id, hamming_distance(e.theVector, :vec) from VectorEntity e order by e.id", Tuple.class )
.setParameter( "vec", vector )
.getResultList();
assertEquals( 2, results.size() );
assertEquals( 1L, results.get( 0 ).get( 0 ) );
assertEquals( hammingDistance( V1, vector ), results.get( 0 ).get( 1, double.class ), 0D );
assertEquals( hammingDistance( V2, vector ), results.get( 1 ).get( 1, double.class ), 0D );
} );
}
@Test
@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsVectorDims.class)
public void testVectorDims(SessionFactoryScope scope) {
scope.inTransaction( em -> {
final List<Tuple> results = em.createSelectionQuery( "select e.id, vector_dims(e.theVector) from VectorEntity e order by e.id", Tuple.class )
.getResultList();
assertEquals( 2, results.size() );
assertEquals( 1L, results.get( 0 ).get( 0 ) );
assertEquals( V1.length, results.get( 0 ).get( 1 ) );
assertEquals( 2L, results.get( 1 ).get( 0 ) );
assertEquals( V2.length, results.get( 1 ).get( 1 ) );
} );
}
@Test
@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsVectorNorm.class)
@SkipForDialect(dialectClass = OracleDialect.class, reason = "Oracle 23.9 bug")
public void testVectorNorm(SessionFactoryScope scope) {
scope.inTransaction( em -> {
final List<Tuple> results = em.createSelectionQuery( "select e.id, vector_norm(e.theVector) from VectorEntity e order by e.id", Tuple.class )
.getResultList();
assertEquals( 2, results.size() );
assertEquals( 1L, results.get( 0 ).get( 0 ) );
assertEquals( euclideanNorm( V1 ), results.get( 0 ).get( 1, double.class ), 0D );
assertEquals( 2L, results.get( 1 ).get( 0 ) );
assertEquals( euclideanNorm( V2 ), results.get( 1 ).get( 1, double.class ), 0D );
} );
}
@Entity( name = "VectorEntity" )
public static | DoubleVectorTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/User.java | {
"start": 481,
"end": 1099
} | class ____ {
private Long id;
private String name;
private Forum forum;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, insertable = false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne(optional=false,fetch=FetchType.LAZY)
@JoinColumn(name="FK_ForumId", nullable=false, updatable=false)
public Forum getForum() {
return forum;
}
public void setForum(Forum forum) {
this.forum = forum;
}
}
| User |
java | quarkusio__quarkus | extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/runtime/MongoClientBeanUtil.java | {
"start": 198,
"end": 1049
} | class ____ {
public static final String REACTIVE_CLIENT_NAME_SUFFIX = "reactive";
private MongoClientBeanUtil() {
throw new UnsupportedOperationException();
}
public static String namedQualifier(String clientName, boolean isReactive) {
if (MongoConfig.isDefaultClient(clientName)) {
throw new IllegalArgumentException("The default client should not have a named qualifier");
}
return isReactive ? clientName + REACTIVE_CLIENT_NAME_SUFFIX : clientName;
}
@SuppressWarnings("rawtypes")
public static AnnotationLiteral clientLiteral(String clientName, boolean isReactive) {
if (MongoConfig.isDefaultClient(clientName)) {
return Default.Literal.INSTANCE;
}
return NamedLiteral.of(namedQualifier(clientName, isReactive));
}
}
| MongoClientBeanUtil |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SplunkHECEndpointBuilderFactory.java | {
"start": 16542,
"end": 16874
} | class ____ extends AbstractEndpointBuilder implements SplunkHECEndpointBuilder, AdvancedSplunkHECEndpointBuilder {
public SplunkHECEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new SplunkHECEndpointBuilderImpl(path);
}
} | SplunkHECEndpointBuilderImpl |
java | quarkusio__quarkus | integration-tests/jackson/src/main/java/io/quarkus/it/jackson/model/ModelWithSerializerAndDeserializerOnField.java | {
"start": 2206,
"end": 2545
} | class ____ extends JsonSerializer<Inner> {
@Override
public void serialize(Inner value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField("someValue", "unchangeable");
gen.writeEndObject();
}
}
}
| InnerSerializer |
java | bumptech__glide | testutil/src/main/java/com/bumptech/glide/testutil/WaitModelLoader.java | {
"start": 1145,
"end": 2779
} | class ____<ModelT> {
private final CountDownLatch latch = new CountDownLatch(1);
private final ModelT wrapped;
WaitModel(ModelT wrapped) {
this.wrapped = wrapped;
}
public void countDown() {
if (latch.getCount() != 1) {
throw new IllegalStateException();
}
latch.countDown();
}
}
/**
* @deprecated Use {@link WaitModelLoaderRule#waitOn(Object)} instead
*/
@Deprecated
public static synchronized <T> WaitModel<T> waitOn(T model) {
@SuppressWarnings("unchecked")
ModelLoaderFactory<WaitModel<T>, InputStream> streamFactory =
new Factory<>((Class<T>) model.getClass(), InputStream.class);
Glide.get(ApplicationProvider.getApplicationContext())
.getRegistry()
.replace(WaitModel.class, InputStream.class, streamFactory);
return new WaitModel<>(model);
}
private final ModelLoader<ModelT, DataT> wrapped;
private WaitModelLoader(ModelLoader<ModelT, DataT> wrapped) {
this.wrapped = wrapped;
}
@Nullable
@Override
public LoadData<DataT> buildLoadData(
@NonNull WaitModel<ModelT> waitModel, int width, int height, @NonNull Options options) {
LoadData<DataT> wrappedLoadData =
wrapped.buildLoadData(waitModel.wrapped, width, height, options);
if (wrappedLoadData == null) {
return null;
}
return new LoadData<>(
wrappedLoadData.sourceKey, new WaitFetcher<>(wrappedLoadData.fetcher, waitModel.latch));
}
@Override
public boolean handles(@NonNull WaitModel<ModelT> waitModel) {
return wrapped.handles(waitModel.wrapped);
}
private static final | WaitModel |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/type/format/StringJsonDocumentWriter.java | {
"start": 945,
"end": 13730
} | class ____ extends StringJsonDocument implements JsonDocumentWriter {
private final JsonAppender appender;
/**
* Creates a new StringJsonDocumentWriter.
*/
public StringJsonDocumentWriter() {
this( new StringBuilder() );
}
/**
* Creates a new StringJsonDocumentWriter.
*
* @param sb the StringBuilder to receive the serialized JSON
*/
public StringJsonDocumentWriter(StringBuilder sb) {
this.processingStates.push( JsonProcessingState.NONE );
this.appender = new JsonAppender( sb );
}
/**
* Callback to be called when the start of an JSON object is encountered.
*/
@Override
public JsonDocumentWriter startObject() {
// Note: startArray and startObject must not call moveProcessingStateMachine()
if ( this.processingStates.getCurrent() == JsonProcessingState.STARTING_ARRAY ) {
// are we building an array of objects?
// i.e, [{},...]
// move to JsonProcessingState.ARRAY first
this.processingStates.push( JsonProcessingState.ARRAY );
}
else if ( this.processingStates.getCurrent() == JsonProcessingState.ARRAY ) {
// That means that we ae building an array of object ([{},...])
// JSON object hee are treat as array item.
// -> add the marker first
this.appender.append( StringJsonDocumentMarker.SEPARATOR.getMarkerCharacter() );
}
this.appender.append( StringJsonDocumentMarker.OBJECT_START.getMarkerCharacter() );
this.processingStates.push( JsonProcessingState.STARTING_OBJECT );
return this;
}
/**
* Callback to be called when the end of an JSON object is encountered.
*/
@Override
public JsonDocumentWriter endObject() {
this.appender.append( StringJsonDocumentMarker.OBJECT_END.getMarkerCharacter() );
this.processingStates.push( JsonProcessingState.ENDING_OBJECT );
moveProcessingStateMachine();
return this;
}
/**
* Callback to be called when the start of an array is encountered.
*/
@Override
public JsonDocumentWriter startArray() {
this.processingStates.push( JsonProcessingState.STARTING_ARRAY );
// Note: startArray and startObject do not call moveProcessingStateMachine()
this.appender.append( StringJsonDocumentMarker.ARRAY_START.getMarkerCharacter() );
return this;
}
/**
* Callback to be called when the end of an array is encountered.
*/
@Override
public JsonDocumentWriter endArray() {
this.appender.append( StringJsonDocumentMarker.ARRAY_END.getMarkerCharacter() );
this.processingStates.push( JsonProcessingState.ENDING_ARRAY );
moveProcessingStateMachine();
return this;
}
@Override
public JsonDocumentWriter objectKey(String key) {
if ( key == null || key.isEmpty() ) {
throw new IllegalArgumentException( "key cannot be null or empty" );
}
if ( JsonProcessingState.OBJECT.equals( this.processingStates.getCurrent() ) ) {
// we have started an object, and we are adding an item key: we do add a separator.
this.appender.append( StringJsonDocumentMarker.SEPARATOR.getMarkerCharacter() );
}
this.appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
this.appender.append( key );
this.appender.append( "\":" );
moveProcessingStateMachine();
return this;
}
/**
* Adds a separator if needed.
* The logic here is know if we have to prepend a separator
* as such, it must be called at the beginning of all methods
* Separator is to separate array items or key/value pairs in an object.
*/
private void addItemsSeparator() {
if ( this.processingStates.getCurrent().equals( JsonProcessingState.ARRAY ) ) {
// We started to serialize an array and already added item to it:add a separator anytime.
this.appender.append( StringJsonDocumentMarker.SEPARATOR.getMarkerCharacter() );
}
}
/**
* Changes the current processing state.
* we are called after an item (array item or object item) has been added,
* do whatever it takes to move away from the current state by picking up the next logical one.
* <p>
* We have to deal with two kinds of (possibly empty) structure
* <ul>
* <li>array of objects and values [{},null,{},"foo", ...]</li>
* <li>objects than have array as attribute value {k1:v1, k2:[v21,v22,..], k3:v3, k4:null, ...}</li>
* </ul>
* <pre>
* NONE -> SA -> (A,...) --> SO -> O -> EO -> A
* --> EA -> NONE
* -> EA -> NONE
*
* -> SO -> (O,...) ------------------> SA -> A -> EA -> O
* --> EO -> NONE -> EA -> O
* -> EO -> NONE
*
* </pre>
*/
private void moveProcessingStateMachine() {
switch ( this.processingStates.getCurrent() ) {
case STARTING_OBJECT:
//after starting an object, we start adding key/value pairs
this.processingStates.push( JsonProcessingState.OBJECT );
break;
case STARTING_ARRAY:
//after starting an array, we start adding value to it
this.processingStates.push( JsonProcessingState.ARRAY );
break;
case ENDING_ARRAY:
// when ending an array, we have one or two states.
// ARRAY (unless this is an empty array)
// STARTING_ARRAY
// first pop ENDING_ARRAY
this.processingStates.pop();
// if we have ARRAY, so that's not an empty array. pop that state
if ( this.processingStates.getCurrent().equals( JsonProcessingState.ARRAY ) ) {
this.processingStates.pop();
}
final JsonProcessingState arrayStart = this.processingStates.pop();
assert arrayStart.equals( JsonProcessingState.STARTING_ARRAY );
break;
case ENDING_OBJECT:
// when ending an object, we have one or two states.
// OBJECT (unless this is an empty object)
// STARTING_OBJECT
// first pop ENDING_OBJECT
this.processingStates.pop();
// if we have OBJECT, so that's not an empty object. pop that state
if ( this.processingStates.getCurrent().equals( JsonProcessingState.OBJECT ) ) {
this.processingStates.pop();
}
final JsonProcessingState objectStart = this.processingStates.pop();
assert objectStart.equals( JsonProcessingState.STARTING_OBJECT );
break;
default:
//nothing to do for the other ones.
}
}
@Override
public JsonDocumentWriter nullValue() {
addItemsSeparator();
this.appender.append( "null" );
moveProcessingStateMachine();
return this;
}
@Override
public JsonDocumentWriter numericValue(Number value) {
addItemsSeparator();
appender.append( value.toString() );
moveProcessingStateMachine();
return this;
}
@Override
public JsonDocumentWriter booleanValue(boolean value) {
addItemsSeparator();
BooleanJavaType.INSTANCE.appendEncodedString( this.appender, value );
moveProcessingStateMachine();
return this;
}
@Override
public JsonDocumentWriter stringValue(String value) {
addItemsSeparator();
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
appender.startEscaping();
appender.append( value );
appender.endEscaping();
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
moveProcessingStateMachine();
return this;
}
@Override
public <T> JsonDocumentWriter serializeJsonValue(Object value, JavaType<T> javaType, JdbcType jdbcType, WrapperOptions options) {
addItemsSeparator();
convertedBasicValueToString( value, options, this.appender, javaType, jdbcType );
moveProcessingStateMachine();
return this;
}
private <T> void convertedCastBasicValueToString(Object value, WrapperOptions options, JsonAppender appender, JavaType<T> javaType, JdbcType jdbcType) {
assert javaType.isInstance( value );
//noinspection unchecked
convertedBasicValueToString( (T) value, options, appender, javaType, jdbcType );
}
/**
* Converts a value to String according to its mapping type.
* This method serializes the value and writes it into the underlying appender
*
* @param value the value
* @param javaType the Java type of the value
* @param jdbcType the JDBC SQL type of the value
* @param options the wapping options.
*/
private <T> void convertedBasicValueToString(
Object value,
WrapperOptions options,
JsonAppender appender,
JavaType<T> javaType,
JdbcType jdbcType) {
assert javaType.isInstance( value );
switch ( jdbcType.getDefaultSqlTypeCode() ) {
case SqlTypes.TINYINT:
case SqlTypes.SMALLINT:
case SqlTypes.INTEGER:
if ( value instanceof Boolean ) {
// BooleanJavaType has this as an implicit conversion
appender.append( (Boolean) value ? '1' : '0' );
break;
}
if ( value instanceof Enum ) {
appender.appendSql( ((Enum<?>) value).ordinal() );
break;
}
case SqlTypes.BOOLEAN:
case SqlTypes.BIT:
case SqlTypes.BIGINT:
case SqlTypes.FLOAT:
case SqlTypes.REAL:
case SqlTypes.DOUBLE:
// These types fit into the native representation of JSON, so let's use that
javaType.appendEncodedString( appender, (T) value );
break;
case SqlTypes.CHAR:
case SqlTypes.NCHAR:
case SqlTypes.VARCHAR:
case SqlTypes.NVARCHAR:
if ( value instanceof Boolean ) {
// BooleanJavaType has this as an implicit conversion
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
appender.append( (Boolean) value ? 'Y' : 'N' );
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
break;
}
case SqlTypes.LONGVARCHAR:
case SqlTypes.LONGNVARCHAR:
case SqlTypes.LONG32VARCHAR:
case SqlTypes.LONG32NVARCHAR:
case SqlTypes.CLOB:
case SqlTypes.MATERIALIZED_CLOB:
case SqlTypes.NCLOB:
case SqlTypes.MATERIALIZED_NCLOB:
case SqlTypes.ENUM:
case SqlTypes.NAMED_ENUM:
// These literals can contain the '"' character, so we need to escape it
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
appender.startEscaping();
javaType.appendEncodedString( appender, (T) value );
appender.endEscaping();
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
break;
case SqlTypes.DATE:
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
JdbcDateJavaType.INSTANCE.appendEncodedString(
appender,
javaType.unwrap( (T) value, java.sql.Date.class, options )
);
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
break;
case SqlTypes.TIME:
case SqlTypes.TIME_WITH_TIMEZONE:
case SqlTypes.TIME_UTC:
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
JdbcTimeJavaType.INSTANCE.appendEncodedString(
appender,
javaType.unwrap( (T) value, java.sql.Time.class, options )
);
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
break;
case SqlTypes.TIMESTAMP:
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
JdbcTimestampJavaType.INSTANCE.appendEncodedString(
appender,
javaType.unwrap( (T) value, java.sql.Timestamp.class, options )
);
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
break;
case SqlTypes.TIMESTAMP_WITH_TIMEZONE:
case SqlTypes.TIMESTAMP_UTC:
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
DateTimeFormatter.ISO_OFFSET_DATE_TIME.formatTo(
javaType.unwrap( (T) value, OffsetDateTime.class, options ),
appender
);
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
break;
case SqlTypes.DECIMAL:
case SqlTypes.NUMERIC:
case SqlTypes.DURATION:
case SqlTypes.UUID:
// These types need to be serialized as JSON string, but don't have a need for escaping
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
javaType.appendEncodedString( appender, (T) value );
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
break;
case SqlTypes.BINARY:
case SqlTypes.VARBINARY:
case SqlTypes.LONGVARBINARY:
case SqlTypes.LONG32VARBINARY:
case SqlTypes.BLOB:
case SqlTypes.MATERIALIZED_BLOB:
// These types need to be serialized as JSON string, and for efficiency uses appendString directly
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
appender.write( javaType.unwrap( (T) value, byte[].class, options ) );
appender.append( StringJsonDocumentMarker.QUOTE.getMarkerCharacter() );
break;
case SqlTypes.ARRAY:
case SqlTypes.JSON_ARRAY:
// Caller handles this. We should never end up here actually.
throw new IllegalStateException( "unexpected JSON array type" );
default:
throw new UnsupportedOperationException( "Unsupported JdbcType nested in JSON: " + jdbcType );
}
}
public String getJson() {
return appender.toString();
}
@Override
public String toString() {
return appender.toString();
}
private static | StringJsonDocumentWriter |
java | elastic__elasticsearch | libs/x-content/src/main/java/org/elasticsearch/xcontent/support/MapXContentParser.java | {
"start": 1007,
"end": 6917
} | class ____ extends AbstractXContentParser {
private final XContentType xContentType;
private TokenIterator iterator;
private boolean closed;
public MapXContentParser(
NamedXContentRegistry xContentRegistry,
DeprecationHandler deprecationHandler,
Map<String, Object> map,
XContentType xContentType
) {
super(xContentRegistry, deprecationHandler);
this.xContentType = xContentType;
this.iterator = new MapIterator(null, null, map);
}
@Override
protected boolean doBooleanValue() throws IOException {
if (iterator != null && iterator.currentValue() instanceof Boolean aBoolean) {
return aBoolean;
} else {
throw new IllegalStateException("Cannot get boolean value for the current token " + currentToken());
}
}
@Override
protected short doShortValue() throws IOException {
return numberValue().shortValue();
}
@Override
protected int doIntValue() throws IOException {
return numberValue().intValue();
}
@Override
protected long doLongValue() throws IOException {
return numberValue().longValue();
}
@Override
protected float doFloatValue() throws IOException {
return numberValue().floatValue();
}
@Override
protected double doDoubleValue() throws IOException {
return numberValue().doubleValue();
}
@Override
public XContentType contentType() {
return xContentType;
}
@Override
public void allowDuplicateKeys(boolean allowDuplicateKeys) {
throw new UnsupportedOperationException("Allowing duplicate keys is not possible for maps");
}
@Override
public Token nextToken() throws IOException {
if (iterator == null) {
return null;
} else {
iterator = iterator.next();
}
return currentToken();
}
@Override
public void skipChildren() throws IOException {
Token token = currentToken();
if (token == Token.START_OBJECT || token == Token.START_ARRAY) {
iterator = iterator.skipChildren();
}
}
@Override
public Token currentToken() {
if (iterator == null) {
return null;
} else {
return iterator.currentToken();
}
}
@Override
public String currentName() throws IOException {
if (iterator == null) {
return null;
} else {
return iterator.currentName();
}
}
@Override
public String text() throws IOException {
if (iterator != null) {
if (currentToken() == Token.VALUE_STRING || currentToken() == Token.VALUE_NUMBER || currentToken() == Token.VALUE_BOOLEAN) {
return iterator.currentValue().toString();
} else if (currentToken() == Token.FIELD_NAME) {
return iterator.currentName();
} else {
return null;
}
} else {
throw new IllegalStateException("Cannot get text for the current token " + currentToken());
}
}
@Override
public CharBuffer charBuffer() throws IOException {
throw new UnsupportedOperationException("use text() instead");
}
@Override
public Object objectText() throws IOException {
throw new UnsupportedOperationException("use text() instead");
}
@Override
public Object objectBytes() throws IOException {
throw new UnsupportedOperationException("use text() instead");
}
@Override
public boolean hasTextCharacters() {
return false;
}
@Override
public char[] textCharacters() throws IOException {
throw new UnsupportedOperationException("use text() instead");
}
@Override
public int textLength() throws IOException {
throw new UnsupportedOperationException("use text() instead");
}
@Override
public int textOffset() throws IOException {
throw new UnsupportedOperationException("use text() instead");
}
@Override
public Number numberValue() throws IOException {
if (iterator != null && currentToken() == Token.VALUE_NUMBER) {
return (Number) iterator.currentValue();
} else {
throw new IllegalStateException("Cannot get numeric value for the current token " + currentToken());
}
}
@Override
public NumberType numberType() throws IOException {
Number number = numberValue();
if (number instanceof Integer) {
return NumberType.INT;
} else if (number instanceof BigInteger) {
return NumberType.BIG_INTEGER;
} else if (number instanceof Long) {
return NumberType.LONG;
} else if (number instanceof Float) {
return NumberType.FLOAT;
} else if (number instanceof Double) {
return NumberType.DOUBLE;
} else if (number instanceof BigDecimal) {
return NumberType.BIG_DECIMAL;
}
throw new IllegalStateException("No matching token for number_type [" + number.getClass() + "]");
}
@Override
public byte[] binaryValue() throws IOException {
if (iterator != null && iterator.currentValue() instanceof byte[] bytes) {
return bytes;
} else {
throw new IllegalStateException("Cannot get binary value for the current token " + currentToken());
}
}
@Override
public XContentLocation getTokenLocation() {
return new XContentLocation(0, 0);
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public void close() throws IOException {
closed = true;
}
/**
* Iterator over the elements of the map
*/
private abstract static | MapXContentParser |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/lucene/search/function/FunctionScoreQuery.java | {
"start": 16854,
"end": 23202
} | class ____ extends FilterScorer {
private final ScoreFunction[] functions;
private final ScoreMode scoreMode;
private final LeafScoreFunction[] leafFunctions;
private final Bits[] docSets;
private final CombineFunction scoreCombiner;
private final float maxBoost;
private final boolean needsScores;
private FunctionFactorScorer(
Scorer scorer,
ScoreMode scoreMode,
ScoreFunction[] functions,
float maxBoost,
LeafScoreFunction[] leafFunctions,
Bits[] docSets,
CombineFunction scoreCombiner,
boolean needsScores
) throws IOException {
super(scorer);
this.scoreMode = scoreMode;
this.functions = functions;
this.leafFunctions = leafFunctions;
this.docSets = docSets;
this.scoreCombiner = scoreCombiner;
this.maxBoost = maxBoost;
this.needsScores = needsScores;
}
@Override
public float score() throws IOException {
int docId = docID();
// Even if the weight is created with needsScores=false, it might
// be costly to call score(), so we explicitly check if scores
// are needed
float subQueryScore = needsScores ? super.score() : 0f;
if (leafFunctions.length == 0) {
return subQueryScore;
}
double factor = computeScore(docId, subQueryScore);
float finalScore = scoreCombiner.combine(subQueryScore, factor, maxBoost);
if (finalScore < 0f || Float.isNaN(finalScore)) {
/*
These scores are invalid for score based {@link org.apache.lucene.search.TopDocsCollector}s.
See {@link org.apache.lucene.search.TopScoreDocCollector} for details.
*/
throw new IllegalArgumentException(
"function score query returned an invalid score: "
+ finalScore
+ " for doc: "
+ docId
+ "; score must be a non-negative real number"
);
}
return finalScore;
}
protected double computeScore(int docId, float subQueryScore) throws IOException {
double factor = 1d;
switch (scoreMode) {
case FIRST:
for (int i = 0; i < leafFunctions.length; i++) {
if (docSets[i].get(docId)) {
factor = leafFunctions[i].score(docId, subQueryScore);
break;
}
}
break;
case MAX:
double maxFactor = Double.NEGATIVE_INFINITY;
for (int i = 0; i < leafFunctions.length; i++) {
if (docSets[i].get(docId)) {
maxFactor = Math.max(leafFunctions[i].score(docId, subQueryScore), maxFactor);
}
}
if (maxFactor != Float.NEGATIVE_INFINITY) {
factor = maxFactor;
}
break;
case MIN:
double minFactor = Double.POSITIVE_INFINITY;
for (int i = 0; i < leafFunctions.length; i++) {
if (docSets[i].get(docId)) {
minFactor = Math.min(leafFunctions[i].score(docId, subQueryScore), minFactor);
}
}
if (minFactor != Float.POSITIVE_INFINITY) {
factor = minFactor;
}
break;
case MULTIPLY:
for (int i = 0; i < leafFunctions.length; i++) {
if (docSets[i].get(docId)) {
factor *= leafFunctions[i].score(docId, subQueryScore);
}
}
break;
default: // Avg / Total
double totalFactor = 0.0f;
double weightSum = 0;
for (int i = 0; i < leafFunctions.length; i++) {
if (docSets[i].get(docId)) {
totalFactor += leafFunctions[i].score(docId, subQueryScore);
weightSum += functions[i].getWeight();
}
}
if (weightSum != 0) {
factor = totalFactor;
if (scoreMode == ScoreMode.AVG) {
factor /= weightSum;
}
}
break;
}
return factor;
}
@Override
public float getMaxScore(int upTo) throws IOException {
return Float.MAX_VALUE; // TODO: what would be a good upper bound?
}
}
@Override
public String toString(String field) {
StringBuilder sb = new StringBuilder();
sb.append("function score (").append(subQuery.toString(field)).append(", functions: [");
for (ScoreFunction function : functions) {
sb.append("{" + (function == null ? "" : function.toString()) + "}");
}
sb.append("])");
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (sameClassAs(o) == false) {
return false;
}
FunctionScoreQuery other = (FunctionScoreQuery) o;
return Objects.equals(this.subQuery, other.subQuery)
&& this.maxBoost == other.maxBoost
&& Objects.equals(this.combineFunction, other.combineFunction)
&& Objects.equals(this.minScore, other.minScore)
&& Objects.equals(this.scoreMode, other.scoreMode)
&& Arrays.equals(this.functions, other.functions);
}
@Override
public int hashCode() {
return Objects.hash(classHash(), subQuery, maxBoost, combineFunction, minScore, scoreMode, Arrays.hashCode(functions));
}
}
| FunctionFactorScorer |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/aggregate/H2AggregateSupport.java | {
"start": 13029,
"end": 13547
} | class ____ implements JsonWriteExpression {
private final SelectableMapping selectableMapping;
PassThroughExpression(SelectableMapping selectableMapping) {
this.selectableMapping = selectableMapping;
}
@Override
public void append(
SqlAppender sb,
String path,
SqlAstTranslator<?> translator,
AggregateColumnWriteExpression expression) {
sb.append( '\'' );
sb.append( selectableMapping.getSelectableName() );
sb.append( "':" );
sb.append( path );
}
}
}
| PassThroughExpression |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/GenericsParamConverterTest.java | {
"start": 636,
"end": 1536
} | class ____ {
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(TestEnum.class, Wrapper.class,
WrapperParamConverterProvider.class, WrapperParamConverterProvider.WrapperParamConverter.class,
TestResource.class));
@Test
public void wrapper() {
given()
.when().get("/test/single?wrapper=ACTIVE")
.then()
.statusCode(200)
.body(is("ACTIVE"));
}
@Test
public void wrapperList() {
given()
.when().get("/test/list?wrapperList=INACTIVE&wrapperList=ACTIVE")
.then()
.statusCode(200)
.body(is("INACTIVE,ACTIVE"));
}
@Path("/test")
public static | GenericsParamConverterTest |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/impl/pb/ReplaceLabelsOnNodeResponsePBImpl.java | {
"start": 1137,
"end": 2254
} | class ____ extends
ReplaceLabelsOnNodeResponse {
ReplaceLabelsOnNodeResponseProto proto = ReplaceLabelsOnNodeResponseProto
.getDefaultInstance();
ReplaceLabelsOnNodeResponseProto.Builder builder = null;
boolean viaProto = false;
public ReplaceLabelsOnNodeResponsePBImpl() {
builder = ReplaceLabelsOnNodeResponseProto.newBuilder();
}
public ReplaceLabelsOnNodeResponsePBImpl(
ReplaceLabelsOnNodeResponseProto proto) {
this.proto = proto;
viaProto = true;
}
public ReplaceLabelsOnNodeResponseProto getProto() {
proto = viaProto ? proto : builder.build();
viaProto = true;
return proto;
}
@Override
public int hashCode() {
return getProto().hashCode();
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other.getClass().isAssignableFrom(this.getClass())) {
return this.getProto().equals(this.getClass().cast(other).getProto());
}
return false;
}
@Override
public String toString() {
return TextFormat.shortDebugString(getProto());
}
}
| ReplaceLabelsOnNodeResponsePBImpl |
java | elastic__elasticsearch | x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/rules/action/RestDeleteQueryRulesetActionTests.java | {
"start": 771,
"end": 1397
} | class ____ extends AbstractRestEnterpriseSearchActionTests {
public void testWithNonCompliantLicense() throws Exception {
checkLicenseForRequest(
new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withMethod(RestRequest.Method.DELETE)
.withParams(Map.of("ruleset_id", "ruleset-id"))
.build(),
LicenseUtils.Product.QUERY_RULES
);
}
@Override
protected EnterpriseSearchBaseRestHandler getRestAction(XPackLicenseState licenseState) {
return new RestDeleteQueryRulesetAction(licenseState);
}
}
| RestDeleteQueryRulesetActionTests |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/deser/jdk/JDKMiscDeserializers.java | {
"start": 354,
"end": 536
} | class ____ contains serializers for miscellaneous JDK types
* that require special handling and are not grouped along with a set of
* other serializers (like date/time)
*/
public | that |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/NumberSeriesGenerateSeriesFunction.java | {
"start": 7702,
"end": 12824
} | class ____ implements QueryTransformer {
protected final FunctionTableGroup functionTableGroup;
protected final TableGroup targetTableGroup;
protected final String positionColumnName;
protected final boolean coerceToTimestamp;
public NumberSeriesQueryTransformer(FunctionTableGroup functionTableGroup, TableGroup targetTableGroup, String positionColumnName, boolean coerceToTimestamp) {
this.functionTableGroup = functionTableGroup;
this.targetTableGroup = targetTableGroup;
this.positionColumnName = positionColumnName;
this.coerceToTimestamp = coerceToTimestamp;
}
@Override
public QuerySpec transform(CteContainer cteContainer, QuerySpec querySpec, SqmToSqlAstConverter converter) {
//noinspection unchecked
final List<SqlAstNode> arguments = (List<SqlAstNode>) functionTableGroup.getPrimaryTableReference()
.getFunctionExpression()
.getArguments();
final JdbcType boundType = ((Expression) arguments.get( 0 )).getExpressionType().getSingleJdbcMapping().getJdbcType();
final boolean castTimestamp = coerceToTimestamp
&& (boundType.getDdlTypeCode() == SqlTypes.DATE || boundType.getDdlTypeCode() == SqlTypes.TIME);
final Expression start = castTimestamp
? castToTimestamp( arguments.get( 0 ), converter )
: (Expression) arguments.get( 0 );
final Expression stop = castTimestamp
? castToTimestamp( arguments.get( 1 ), converter )
: (Expression) arguments.get( 1 );
final Expression explicitStep = arguments.size() > 2
? (Expression) arguments.get( 2 )
: null;
final TableGroup parentTableGroup = querySpec.getFromClause().queryTableGroups(
tg -> tg.findTableGroupJoin( targetTableGroup ) == null ? null : tg
);
final PredicateContainer predicateContainer;
if ( parentTableGroup != null ) {
predicateContainer = parentTableGroup.findTableGroupJoin( targetTableGroup );
}
else {
predicateContainer = querySpec;
}
final BasicType<Integer> integerType = converter.getSqmCreationContext()
.getNodeBuilder()
.getIntegerType();
final Expression oneBasedOrdinal = new ColumnReference(
functionTableGroup.getPrimaryTableReference().getIdentificationVariable(),
positionColumnName,
false,
null,
integerType
);
final Expression one = new QueryLiteral<>( 1, integerType );
final Expression zeroBasedOrdinal = new BinaryArithmeticExpression(
oneBasedOrdinal,
BinaryArithmeticOperator.SUBTRACT,
one,
integerType
);
final Expression stepExpression = explicitStep != null
? multiply( explicitStep, zeroBasedOrdinal )
: zeroBasedOrdinal;
final Expression nextValue = add( start, stepExpression, converter );
// Add a predicate to ensure the current value is valid
if ( explicitStep == null ) {
// The default step is 1, so just check if value <= stop
predicateContainer.applyPredicate(
new ComparisonPredicate(
nextValue,
ComparisonOperator.LESS_THAN_OR_EQUAL,
stop
)
);
}
else {
// When start < stop, step must be positive and value is only valid if it's less than or equal to stop
final BasicType<Boolean> booleanType = converter.getSqmCreationContext()
.getNodeBuilder()
.getBooleanType();
final Predicate positiveProgress = new Junction(
Junction.Nature.CONJUNCTION,
List.of(
new ComparisonPredicate(
start,
ComparisonOperator.LESS_THAN,
stop
),
new ComparisonPredicate(
explicitStep,
ComparisonOperator.GREATER_THAN,
multiply( explicitStep, -1, integerType )
),
new ComparisonPredicate(
nextValue,
ComparisonOperator.LESS_THAN_OR_EQUAL,
stop
)
),
booleanType
);
// When start > stop, step must be negative and value is only valid if it's greater than or equal to stop
final Predicate negativeProgress = new Junction(
Junction.Nature.CONJUNCTION,
List.of(
new ComparisonPredicate(
start,
ComparisonOperator.GREATER_THAN,
stop
),
new ComparisonPredicate(
explicitStep,
ComparisonOperator.LESS_THAN,
multiply( explicitStep, -1, integerType )
),
new ComparisonPredicate(
nextValue,
ComparisonOperator.GREATER_THAN_OR_EQUAL,
stop
)
),
booleanType
);
final Predicate initialValue = new Junction(
Junction.Nature.CONJUNCTION,
List.of(
new ComparisonPredicate(
start,
ComparisonOperator.EQUAL,
stop
),
new ComparisonPredicate(
oneBasedOrdinal,
ComparisonOperator.EQUAL,
one
)
),
booleanType
);
predicateContainer.applyPredicate(
new Junction(
Junction.Nature.DISJUNCTION,
List.of( positiveProgress, negativeProgress, initialValue ),
booleanType
)
);
}
return querySpec;
}
}
protected static | NumberSeriesQueryTransformer |
java | redisson__redisson | redisson/src/main/java/org/redisson/connection/balancer/RandomLoadBalancer.java | {
"start": 829,
"end": 1220
} | class ____ extends BaseLoadBalancer {
@Override
public ClientConnectionsEntry getEntry(List<ClientConnectionsEntry> clientsCopy) {
clientsCopy = filter(clientsCopy);
if (clientsCopy.isEmpty()) {
return null;
}
int ind = ThreadLocalRandom.current().nextInt(clientsCopy.size());
return clientsCopy.get(ind);
}
}
| RandomLoadBalancer |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/sql/ast/tree/expression/SelfRenderingExpression.java | {
"start": 379,
"end": 670
} | interface ____ extends Expression {
@Override
default void accept(SqlAstWalker sqlTreeWalker) {
sqlTreeWalker.visitSelfRenderingExpression( this );
}
void renderToSql(SqlAppender sqlAppender, SqlAstTranslator<?> walker, SessionFactoryImplementor sessionFactory);
}
| SelfRenderingExpression |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/support/AbstractDispatcherServletInitializer.java | {
"start": 2009,
"end": 9196
} | class ____ extends AbstractContextLoaderInitializer {
/**
* The default servlet name. Can be customized by overriding {@link #getServletName}.
*/
public static final String DEFAULT_SERVLET_NAME = "dispatcher";
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
registerDispatcherServlet(servletContext);
}
/**
* Register a {@link DispatcherServlet} against the given servlet context.
* <p>This method will create a {@code DispatcherServlet} with the name returned by
* {@link #getServletName()}, initializing it with the application context returned
* from {@link #createServletApplicationContext()}, and mapping it to the patterns
* returned from {@link #getServletMappings()}.
* <p>Further customization can be achieved by overriding {@link
* #customizeRegistration(ServletRegistration.Dynamic)} or
* {@link #createDispatcherServlet(WebApplicationContext)}.
* @param servletContext the context to register the servlet against
*/
protected void registerDispatcherServlet(ServletContext servletContext) {
String servletName = getServletName();
Assert.state(StringUtils.hasLength(servletName), "getServletName() must not return null or empty");
WebApplicationContext servletAppContext = createServletApplicationContext();
Assert.state(servletAppContext != null, "createServletApplicationContext() must not return null");
FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
Assert.state(dispatcherServlet != null, "createDispatcherServlet(WebApplicationContext) must not return null");
dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());
ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
if (registration == null) {
throw new IllegalStateException("Failed to register servlet with name '" + servletName + "'. " +
"Check if there is another servlet registered under the same name.");
}
registration.setLoadOnStartup(1);
registration.addMapping(getServletMappings());
registration.setAsyncSupported(isAsyncSupported());
Filter[] filters = getServletFilters();
if (!ObjectUtils.isEmpty(filters)) {
for (Filter filter : filters) {
registerServletFilter(servletContext, filter);
}
}
customizeRegistration(registration);
}
/**
* Return the name under which the {@link DispatcherServlet} will be registered.
* Defaults to {@link #DEFAULT_SERVLET_NAME}.
* @see #registerDispatcherServlet(ServletContext)
*/
protected String getServletName() {
return DEFAULT_SERVLET_NAME;
}
/**
* Create a servlet application context to be provided to the {@code DispatcherServlet}.
* <p>The returned context is delegated to Spring's
* {@link DispatcherServlet#DispatcherServlet(WebApplicationContext)}. As such,
* it typically contains controllers, view resolvers, locale resolvers, and other
* web-related beans.
* @see #registerDispatcherServlet(ServletContext)
*/
protected abstract WebApplicationContext createServletApplicationContext();
/**
* Create a {@link DispatcherServlet} (or other kind of {@link FrameworkServlet}-derived
* dispatcher) with the specified {@link WebApplicationContext}.
* <p>Note: This allows for any {@link FrameworkServlet} subclass as of 4.2.3.
* Previously, it insisted on returning a {@link DispatcherServlet} or subclass thereof.
*/
protected FrameworkServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
return new DispatcherServlet(servletAppContext);
}
/**
* Specify application context initializers to be applied to the servlet-specific
* application context that the {@code DispatcherServlet} is being created with.
* @since 4.2
* @see #createServletApplicationContext()
* @see DispatcherServlet#setContextInitializers
* @see #getRootApplicationContextInitializers()
*/
protected ApplicationContextInitializer<?> @Nullable [] getServletApplicationContextInitializers() {
return null;
}
/**
* Specify the servlet mapping(s) for the {@code DispatcherServlet} —
* for example {@code "/"}, {@code "/app"}, etc.
* @see #registerDispatcherServlet(ServletContext)
*/
protected abstract String[] getServletMappings();
/**
* Specify filters to add and map to the {@code DispatcherServlet}.
* @return an array of filters or {@code null}
* @see #registerServletFilter(ServletContext, Filter)
*/
protected Filter @Nullable [] getServletFilters() {
return null;
}
/**
* Add the given filter to the ServletContext and map it to the
* {@code DispatcherServlet} as follows:
* <ul>
* <li>a default filter name is chosen based on its concrete type
* <li>the {@code asyncSupported} flag is set depending on the
* return value of {@link #isAsyncSupported() asyncSupported}
* <li>a filter mapping is created with dispatcher types {@code REQUEST},
* {@code FORWARD}, {@code INCLUDE}, and conditionally {@code ASYNC} depending
* on the return value of {@link #isAsyncSupported() asyncSupported}
* </ul>
* <p>If the above defaults are not suitable or insufficient, override this
* method and register filters directly with the {@code ServletContext}.
* @param servletContext the servlet context to register filters with
* @param filter the filter to be registered
* @return the filter registration
*/
protected FilterRegistration.Dynamic registerServletFilter(ServletContext servletContext, Filter filter) {
String filterName = Conventions.getVariableName(filter);
Dynamic registration = servletContext.addFilter(filterName, filter);
if (registration == null) {
int counter = 0;
while (registration == null) {
if (counter == 100) {
throw new IllegalStateException("Failed to register filter with name '" + filterName + "'. " +
"Check if there is another filter registered under the same name.");
}
registration = servletContext.addFilter(filterName + "#" + counter, filter);
counter++;
}
}
registration.setAsyncSupported(isAsyncSupported());
registration.addMappingForServletNames(getDispatcherTypes(), false, getServletName());
return registration;
}
private EnumSet<DispatcherType> getDispatcherTypes() {
return (isAsyncSupported() ?
EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC) :
EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE));
}
/**
* A single place to control the {@code asyncSupported} flag for the
* {@code DispatcherServlet} and all filters added via {@link #getServletFilters()}.
* <p>The default value is "true".
*/
protected boolean isAsyncSupported() {
return true;
}
/**
* Optionally perform further registration customization once
* {@link #registerDispatcherServlet(ServletContext)} has completed.
* @param registration the {@code DispatcherServlet} registration to be customized
* @see #registerDispatcherServlet(ServletContext)
*/
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
}
}
| AbstractDispatcherServletInitializer |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/data/Worker.java | {
"start": 716,
"end": 993
} | class ____ extends Person {
public String job;
public Worker(String name, String job) {
super(name);
this.job = job;
}
@Override
public String toString() {
return format("Employee[name=%s, company=%s, home=%s]", this.name, this.job, this.home);
}
}
| Worker |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/jobgraph/JobGraphTest.java | {
"start": 2297,
"end": 19288
} | class ____ extends TestLogger {
@Test
public void testSerialization() {
try {
JobGraph jg = new JobGraph("The graph");
// add some configuration values
{
jg.getJobConfiguration().setString("some key", "some value");
jg.getJobConfiguration().set(getDoubleConfigOption("Life of "), Math.PI);
}
// add some vertices
{
JobVertex source1 = new JobVertex("source1");
JobVertex source2 = new JobVertex("source2");
JobVertex target = new JobVertex("target");
connectNewDataSetAsInput(
target,
source1,
DistributionPattern.POINTWISE,
ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
target,
source2,
DistributionPattern.ALL_TO_ALL,
ResultPartitionType.PIPELINED);
jg.addVertex(source1);
jg.addVertex(source2);
jg.addVertex(target);
}
// de-/serialize and compare
JobGraph copy = CommonTestUtils.createCopySerializable(jg);
assertEquals(jg.getName(), copy.getName());
assertEquals(jg.getJobID(), copy.getJobID());
assertEquals(jg.getJobConfiguration(), copy.getJobConfiguration());
assertEquals(jg.getNumberOfVertices(), copy.getNumberOfVertices());
for (JobVertex vertex : copy.getVertices()) {
JobVertex original = jg.findVertexByID(vertex.getID());
assertNotNull(original);
assertEquals(original.getName(), vertex.getName());
assertEquals(original.getNumberOfInputs(), vertex.getNumberOfInputs());
assertEquals(
original.getNumberOfProducedIntermediateDataSets(),
vertex.getNumberOfProducedIntermediateDataSets());
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testTopologicalSort1() {
JobVertex source1 = new JobVertex("source1");
JobVertex source2 = new JobVertex("source2");
JobVertex target1 = new JobVertex("target1");
JobVertex target2 = new JobVertex("target2");
JobVertex intermediate1 = new JobVertex("intermediate1");
JobVertex intermediate2 = new JobVertex("intermediate2");
connectNewDataSetAsInput(
target1, source1, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
target2, source1, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
target2,
intermediate2,
DistributionPattern.POINTWISE,
ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
intermediate2,
intermediate1,
DistributionPattern.POINTWISE,
ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
intermediate1,
source2,
DistributionPattern.POINTWISE,
ResultPartitionType.PIPELINED);
JobGraph graph =
JobGraphTestUtils.streamingJobGraph(
source1, source2, intermediate1, intermediate2, target1, target2);
List<JobVertex> sorted = graph.getVerticesSortedTopologicallyFromSources();
assertEquals(6, sorted.size());
assertBefore(source1, target1, sorted);
assertBefore(source1, target2, sorted);
assertBefore(source2, target2, sorted);
assertBefore(source2, intermediate1, sorted);
assertBefore(source2, intermediate2, sorted);
assertBefore(intermediate1, target2, sorted);
assertBefore(intermediate2, target2, sorted);
}
@Test
public void testTopologicalSort2() {
try {
JobVertex source1 = new JobVertex("source1");
JobVertex source2 = new JobVertex("source2");
JobVertex root = new JobVertex("root");
JobVertex l11 = new JobVertex("layer 1 - 1");
JobVertex l12 = new JobVertex("layer 1 - 2");
JobVertex l13 = new JobVertex("layer 1 - 3");
JobVertex l2 = new JobVertex("layer 2");
connectNewDataSetAsInput(
root, l13, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
root, source2, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
root, l2, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
l2, l11, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
l2, l12, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
l11, source1, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
l12, source1, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
l12, source2, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
l13, source2, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
JobGraph graph =
JobGraphTestUtils.streamingJobGraph(source1, source2, root, l11, l13, l12, l2);
List<JobVertex> sorted = graph.getVerticesSortedTopologicallyFromSources();
assertEquals(7, sorted.size());
assertBefore(source1, root, sorted);
assertBefore(source2, root, sorted);
assertBefore(l11, root, sorted);
assertBefore(l12, root, sorted);
assertBefore(l13, root, sorted);
assertBefore(l2, root, sorted);
assertBefore(l11, l2, sorted);
assertBefore(l12, l2, sorted);
assertBefore(l2, root, sorted);
assertBefore(source1, l2, sorted);
assertBefore(source2, l2, sorted);
assertBefore(source2, l13, sorted);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testTopologicalSort3() {
// --> op1 --
// / \
// (source) - +-> op2 -> op3
// \ /
// ---------
try {
JobVertex source = new JobVertex("source");
JobVertex op1 = new JobVertex("op4");
JobVertex op2 = new JobVertex("op2");
JobVertex op3 = new JobVertex("op3");
connectNewDataSetAsInput(
op1, source, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
op2, op1, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
op2, source, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
op3, op2, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
JobGraph graph = JobGraphTestUtils.streamingJobGraph(source, op1, op2, op3);
List<JobVertex> sorted = graph.getVerticesSortedTopologicallyFromSources();
assertEquals(4, sorted.size());
assertBefore(source, op1, sorted);
assertBefore(source, op2, sorted);
assertBefore(op1, op2, sorted);
assertBefore(op2, op3, sorted);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testTopoSortCyclicGraphNoSources() {
try {
JobVertex v1 = new JobVertex("1");
JobVertex v2 = new JobVertex("2");
JobVertex v3 = new JobVertex("3");
JobVertex v4 = new JobVertex("4");
connectNewDataSetAsInput(
v1, v4, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
v2, v1, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
v3, v2, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
v4, v3, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
JobGraph jg = JobGraphTestUtils.streamingJobGraph(v1, v2, v3, v4);
try {
jg.getVerticesSortedTopologicallyFromSources();
fail("Failed to raise error on topologically sorting cyclic graph.");
} catch (InvalidProgramException e) {
// that what we wanted
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testTopoSortCyclicGraphIntermediateCycle() {
try {
JobVertex source = new JobVertex("source");
JobVertex v1 = new JobVertex("1");
JobVertex v2 = new JobVertex("2");
JobVertex v3 = new JobVertex("3");
JobVertex v4 = new JobVertex("4");
JobVertex target = new JobVertex("target");
connectNewDataSetAsInput(
v1, source, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
v1, v4, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
v2, v1, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
v3, v2, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
v4, v3, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
target, v3, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
JobGraph jg = JobGraphTestUtils.streamingJobGraph(v1, v2, v3, v4, source, target);
try {
jg.getVerticesSortedTopologicallyFromSources();
fail("Failed to raise error on topologically sorting cyclic graph.");
} catch (InvalidProgramException e) {
// that what we wanted
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private static final void assertBefore(JobVertex v1, JobVertex v2, List<JobVertex> list) {
boolean seenFirst = false;
for (JobVertex v : list) {
if (v == v1) {
seenFirst = true;
} else if (v == v2) {
if (!seenFirst) {
fail(
"The first vertex ("
+ v1
+ ") is not before the second vertex ("
+ v2
+ ")");
}
break;
}
}
}
@Test
public void testSetUserArtifactBlobKey() throws IOException, ClassNotFoundException {
JobGraph jb = JobGraphTestUtils.emptyJobGraph();
final DistributedCache.DistributedCacheEntry[] entries = {
new DistributedCache.DistributedCacheEntry("p1", true, true),
new DistributedCache.DistributedCacheEntry("p2", true, false),
new DistributedCache.DistributedCacheEntry("p3", false, true),
new DistributedCache.DistributedCacheEntry("p4", true, false),
};
for (DistributedCache.DistributedCacheEntry entry : entries) {
jb.addUserArtifact(entry.filePath, entry);
}
for (DistributedCache.DistributedCacheEntry entry : entries) {
PermanentBlobKey blobKey = new PermanentBlobKey();
jb.setUserArtifactBlobKey(entry.filePath, blobKey);
DistributedCache.DistributedCacheEntry jobGraphEntry =
jb.getUserArtifacts().get(entry.filePath);
assertNotNull(jobGraphEntry);
assertEquals(
blobKey,
InstantiationUtil.deserializeObject(
jobGraphEntry.blobKey, ClassLoader.getSystemClassLoader()));
assertEquals(entry.isExecutable, jobGraphEntry.isExecutable);
assertEquals(entry.isZipped, jobGraphEntry.isZipped);
assertEquals(entry.filePath, jobGraphEntry.filePath);
}
}
@Test
public void checkpointingIsDisabledByDefaultForStreamingJobGraph() {
final JobGraph jobGraph = JobGraphBuilder.newStreamingJobGraphBuilder().build();
assertFalse(jobGraph.isCheckpointingEnabled());
}
@Test
public void checkpointingIsDisabledByDefaultForBatchJobGraph() {
final JobGraph jobGraph = JobGraphBuilder.newBatchJobGraphBuilder().build();
assertFalse(jobGraph.isCheckpointingEnabled());
}
@Test
public void checkpointingIsEnabledIfIntervalIsqAndLegal() {
final JobGraph jobGraph =
JobGraphBuilder.newStreamingJobGraphBuilder()
.setJobCheckpointingSettings(createCheckpointSettingsWithInterval(10))
.build();
assertTrue(jobGraph.isCheckpointingEnabled());
}
@Test
public void checkpointingIsDisabledIfIntervalIsMaxValue() {
final JobGraph jobGraph =
JobGraphBuilder.newStreamingJobGraphBuilder()
.setJobCheckpointingSettings(
createCheckpointSettingsWithInterval(Long.MAX_VALUE))
.build();
assertFalse(jobGraph.isCheckpointingEnabled());
}
private static JobCheckpointingSettings createCheckpointSettingsWithInterval(
final long checkpointInterval) {
final CheckpointCoordinatorConfiguration checkpointCoordinatorConfiguration =
new CheckpointCoordinatorConfiguration(
checkpointInterval,
Long.MAX_VALUE,
Long.MAX_VALUE,
Integer.MAX_VALUE,
CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION,
true,
false,
0,
0);
return new JobCheckpointingSettings(checkpointCoordinatorConfiguration, null);
}
@Test
public void testGetSlotSharingGroups() {
final JobVertex v1 = new JobVertex("1");
final JobVertex v2 = new JobVertex("2");
final JobVertex v3 = new JobVertex("3");
final JobVertex v4 = new JobVertex("4");
final SlotSharingGroup group1 = new SlotSharingGroup();
v1.setSlotSharingGroup(group1);
v2.setSlotSharingGroup(group1);
final SlotSharingGroup group2 = new SlotSharingGroup();
v3.setSlotSharingGroup(group2);
v4.setSlotSharingGroup(group2);
final JobGraph jobGraph =
JobGraphBuilder.newStreamingJobGraphBuilder()
.addJobVertices(Arrays.asList(v1, v2, v3, v4))
.build();
assertThat(jobGraph.getSlotSharingGroups(), containsInAnyOrder(group1, group2));
}
@Test
public void testGetCoLocationGroups() {
final JobVertex v1 = new JobVertex("1");
final JobVertex v2 = new JobVertex("2");
final JobVertex v3 = new JobVertex("3");
final JobVertex v4 = new JobVertex("4");
final SlotSharingGroup slotSharingGroup = new SlotSharingGroup();
v1.setSlotSharingGroup(slotSharingGroup);
v2.setSlotSharingGroup(slotSharingGroup);
v1.setStrictlyCoLocatedWith(v2);
final JobGraph jobGraph =
JobGraphBuilder.newStreamingJobGraphBuilder()
.addJobVertices(Arrays.asList(v1, v2, v3, v4))
.build();
assertThat(jobGraph.getCoLocationGroups(), hasSize(1));
final CoLocationGroup onlyCoLocationGroup =
jobGraph.getCoLocationGroups().iterator().next();
assertThat(onlyCoLocationGroup.getVertexIds(), containsInAnyOrder(v1.getID(), v2.getID()));
}
}
| JobGraphTest |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/annotation/ProfileValueUtilsTests.java | {
"start": 9983,
"end": 10072
} | class ____ {
}
@SuppressWarnings("unused")
@MetaEnabled
private static | MetaDisabledClass |
java | apache__rocketmq | tools/src/main/java/org/apache/rocketmq/tools/command/broker/CleanExpiredCQSubCommand.java | {
"start": 1200,
"end": 2945
} | class ____ implements SubCommand {
@Override
public String commandName() {
return "cleanExpiredCQ";
}
@Override
public String commandDesc() {
return "Clean expired ConsumeQueue on broker.";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("b", "brokerAddr", true, "Broker address");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "cluster", true, "clustername");
opt.setRequired(false);
options.addOption(opt);
return options;
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
boolean result = false;
defaultMQAdminExt.start();
if (commandLine.hasOption('b')) {
String addr = commandLine.getOptionValue('b').trim();
result = defaultMQAdminExt.cleanExpiredConsumerQueueByAddr(addr);
} else {
String cluster = commandLine.getOptionValue('c');
if (null != cluster)
cluster = cluster.trim();
result = defaultMQAdminExt.cleanExpiredConsumerQueue(cluster);
}
System.out.printf(result ? "success" : "false");
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
| CleanExpiredCQSubCommand |
java | quarkusio__quarkus | extensions/logging-json/deployment/src/test/java/io/quarkus/logging/json/SyslogJsonFormatterCustomConfigTest.java | {
"start": 753,
"end": 3660
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar.addClasses(SyslogJsonFormatterDefaultConfigTest.class))
.withConfigurationResource("application-syslog-json-formatter-custom.properties");
@Test
public void jsonFormatterCustomConfigurationTest() {
JsonFormatter jsonFormatter = getJsonFormatter();
assertThat(jsonFormatter.isPrettyPrint()).isTrue();
assertThat(jsonFormatter.getDateTimeFormatter().toString())
.isEqualTo("Value(DayOfMonth)' 'Text(MonthOfYear,SHORT)' 'Value(Year,4,19,EXCEEDS_PAD)");
assertThat(jsonFormatter.getDateTimeFormatter().getZone()).isEqualTo(ZoneId.of("UTC+05:00"));
assertThat(jsonFormatter.getExceptionOutputType())
.isEqualTo(StructuredFormatter.ExceptionOutputType.DETAILED_AND_FORMATTED);
assertThat(jsonFormatter.getRecordDelimiter()).isEqualTo("\n;");
assertThat(jsonFormatter.isPrintDetails()).isTrue();
assertThat(jsonFormatter.getExcludedKeys()).containsExactlyInAnyOrder("timestamp", "sequence");
assertThat(jsonFormatter.getAdditionalFields().size()).isEqualTo(2);
assertThat(jsonFormatter.getAdditionalFields().containsKey("foo")).isTrue();
assertThat(jsonFormatter.getAdditionalFields().get("foo").type()).isEqualTo(AdditionalFieldConfig.Type.INT);
assertThat(jsonFormatter.getAdditionalFields().get("foo").value()).isEqualTo("42");
assertThat(jsonFormatter.getAdditionalFields().containsKey("bar")).isTrue();
assertThat(jsonFormatter.getAdditionalFields().get("bar").type()).isEqualTo(AdditionalFieldConfig.Type.STRING);
assertThat(jsonFormatter.getAdditionalFields().get("bar").value()).isEqualTo("baz");
}
@Test
public void jsonFormatterOutputTest() throws Exception {
JsonFormatter jsonFormatter = getJsonFormatter();
String line = jsonFormatter.format(new LogRecord(Level.INFO, "Hello, World!"));
JsonNode node = new ObjectMapper().readTree(line);
// "level" has been renamed to HEY
Assertions.assertThat(node.has("level")).isFalse();
Assertions.assertThat(node.has("HEY")).isTrue();
Assertions.assertThat(node.get("HEY").asText()).isEqualTo("INFO");
// excluded fields
Assertions.assertThat(node.has("timestamp")).isFalse();
Assertions.assertThat(node.has("sequence")).isFalse();
// additional fields
Assertions.assertThat(node.has("foo")).isTrue();
Assertions.assertThat(node.get("foo").asInt()).isEqualTo(42);
Assertions.assertThat(node.has("bar")).isTrue();
Assertions.assertThat(node.get("bar").asText()).isEqualTo("baz");
Assertions.assertThat(node.get("message").asText()).isEqualTo("Hello, World!");
}
}
| SyslogJsonFormatterCustomConfigTest |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/factories/RpcServerFactory.java | {
"start": 1207,
"end": 1462
} | interface ____ {
public Server getServer(Class<?> protocol, Object instance,
InetSocketAddress addr, Configuration conf,
SecretManager<? extends TokenIdentifier> secretManager,
int numHandlers, String portRangeConfig);
} | RpcServerFactory |
java | spring-projects__spring-framework | integration-tests/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java | {
"start": 6738,
"end": 6858
} | interface ____ {
int getInvocationCount();
void scheduled();
}
@Repository
static | MyRepositoryWithScheduledMethod |
java | google__guava | android/guava-tests/test/com/google/common/collect/MultimapsTest.java | {
"start": 22439,
"end": 22649
} | class ____<E> implements Supplier<E>, Serializable {
int count;
abstract E getImpl();
@Override
public E get() {
count++;
return getImpl();
}
}
private static | CountingSupplier |
java | spring-projects__spring-boot | module/spring-boot-thymeleaf/src/main/java/org/springframework/boot/thymeleaf/autoconfigure/TemplateEngineConfigurations.java | {
"start": 2483,
"end": 3185
} | class ____ {
@Bean
@ConditionalOnMissingBean(ISpringWebFluxTemplateEngine.class)
SpringWebFluxTemplateEngine templateEngine(ThymeleafProperties properties,
ObjectProvider<ITemplateResolver> templateResolvers, ObjectProvider<IDialect> dialects) {
SpringWebFluxTemplateEngine engine = new SpringWebFluxTemplateEngine();
engine.setEnableSpringELCompiler(properties.isEnableSpringElCompiler());
engine.setRenderHiddenMarkersBeforeCheckboxes(properties.isRenderHiddenMarkersBeforeCheckboxes());
templateResolvers.orderedStream().forEach(engine::addTemplateResolver);
dialects.orderedStream().forEach(engine::addDialect);
return engine;
}
}
}
| ReactiveTemplateEngineConfiguration |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/util/Arrays_hasOnlyNullElements_Test.java | {
"start": 927,
"end": 1615
} | class ____ {
@Test
void should_throw_error_if_array_is_null() {
assertThatNullPointerException().isThrownBy(() -> Arrays.hasOnlyNullElements(null));
}
@Test
void should_return_true_if_array_has_only_null_elements() {
String[] array = { null, null };
assertThat(Arrays.hasOnlyNullElements(array)).isTrue();
}
@Test
void should_return_false_if_array_has_at_least_one_element_not_null() {
String[] array = { null, "Frodo", null };
assertThat(Arrays.hasOnlyNullElements(array)).isFalse();
}
@Test
void should_return_false_if_array_is_empty() {
assertThat(Arrays.hasOnlyNullElements(new String[0])).isFalse();
}
}
| Arrays_hasOnlyNullElements_Test |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AtmosphereWebsocketEndpointBuilderFactory.java | {
"start": 61552,
"end": 64377
} | interface ____
extends
AdvancedAtmosphereWebsocketEndpointConsumerBuilder,
AdvancedAtmosphereWebsocketEndpointProducerBuilder {
default AtmosphereWebsocketEndpointBuilder basic() {
return (AtmosphereWebsocketEndpointBuilder) this;
}
/**
* To use a custom HeaderFilterStrategy to filter header to and from
* Camel message.
*
* The option is a:
* <code>org.apache.camel.spi.HeaderFilterStrategy</code> type.
*
* Group: common (advanced)
*
* @param headerFilterStrategy the value to set
* @return the dsl builder
*/
default AdvancedAtmosphereWebsocketEndpointBuilder headerFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy headerFilterStrategy) {
doSetProperty("headerFilterStrategy", headerFilterStrategy);
return this;
}
/**
* To use a custom HeaderFilterStrategy to filter header to and from
* Camel message.
*
* The option will be converted to a
* <code>org.apache.camel.spi.HeaderFilterStrategy</code> type.
*
* Group: common (advanced)
*
* @param headerFilterStrategy the value to set
* @return the dsl builder
*/
default AdvancedAtmosphereWebsocketEndpointBuilder headerFilterStrategy(String headerFilterStrategy) {
doSetProperty("headerFilterStrategy", headerFilterStrategy);
return this;
}
/**
* To use a custom HttpBinding to control the mapping between Camel
* message and HttpClient.
*
* The option is a:
* <code>org.apache.camel.http.common.HttpBinding</code> type.
*
* Group: common (advanced)
*
* @param httpBinding the value to set
* @return the dsl builder
*/
default AdvancedAtmosphereWebsocketEndpointBuilder httpBinding(org.apache.camel.http.common.HttpBinding httpBinding) {
doSetProperty("httpBinding", httpBinding);
return this;
}
/**
* To use a custom HttpBinding to control the mapping between Camel
* message and HttpClient.
*
* The option will be converted to a
* <code>org.apache.camel.http.common.HttpBinding</code> type.
*
* Group: common (advanced)
*
* @param httpBinding the value to set
* @return the dsl builder
*/
default AdvancedAtmosphereWebsocketEndpointBuilder httpBinding(String httpBinding) {
doSetProperty("httpBinding", httpBinding);
return this;
}
}
public | AdvancedAtmosphereWebsocketEndpointBuilder |
java | apache__camel | core/camel-management/src/test/java/org/apache/camel/management/ManagedMBeansLevelTestSupport.java | {
"start": 1346,
"end": 3124
} | class ____ extends ManagementTestSupport {
private final ManagementMBeansLevel level;
public ManagedMBeansLevelTestSupport(ManagementMBeansLevel level) {
this.level = level;
}
abstract void assertResults(Set<ObjectName> contexts, Set<ObjectName> routes, Set<ObjectName> processors);
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
//set level if provided
if (level != null) {
context.getManagementStrategy().getManagementAgent().setMBeansLevel(level);
}
return context;
}
@Test
public void test() throws Exception {
MockEndpoint result = getMockEndpoint("mock:result");
result.expectedMessageCount(1);
template.sendBodyAndHeader("direct:start", "Hello World", "foo", "123");
assertMockEndpointsSatisfied();
// get the stats for the route
MBeanServer mbeanServer = getMBeanServer();
assertMBeans(mbeanServer);
}
void assertMBeans(MBeanServer mbeanServer) throws MalformedObjectNameException {
Set<ObjectName> contexts = mbeanServer.queryNames(new ObjectName("*:type=context,*"), null);
Set<ObjectName> routes = mbeanServer.queryNames(new ObjectName("*:type=routes,*"), null);
Set<ObjectName> processors = mbeanServer.queryNames(new ObjectName("*:type=processors,*"), null);
assertResults(contexts, routes, processors);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").to("mock:result");
}
};
}
}
| ManagedMBeansLevelTestSupport |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/naming/remote/NamingRemoteConstants.java | {
"start": 775,
"end": 1488
} | class ____ {
public static final String REGISTER_INSTANCE = "registerInstance";
public static final String BATCH_REGISTER_INSTANCE = "batchRegisterInstance";
public static final String DE_REGISTER_INSTANCE = "deregisterInstance";
public static final String QUERY_SERVICE = "queryService";
public static final String SUBSCRIBE_SERVICE = "subscribeService";
public static final String NOTIFY_SUBSCRIBER = "notifySubscriber";
public static final String LIST_SERVICE = "listService";
public static final String FORWARD_INSTANCE = "forwardInstance";
public static final String FORWARD_HEART_BEAT = "forwardHeartBeat";
}
| NamingRemoteConstants |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/leaderelection/DefaultLeaderElectionTest.java | {
"start": 8934,
"end": 11919
} | class ____
extends DefaultLeaderElection.ParentService {
private final BiConsumerWithException<String, LeaderContender, Exception> registerConsumer;
private final Consumer<String> removeConsumer;
private final TriFunction<String, UUID, String, CompletableFuture<Void>>
confirmLeadershipConsumer;
private final BiFunction<String, UUID, CompletableFuture<Boolean>> hasLeadershipFunction;
private TestingAbstractLeaderElectionService(
BiConsumerWithException<String, LeaderContender, Exception> registerConsumer,
Consumer<String> removeConsumer,
TriFunction<String, UUID, String, CompletableFuture<Void>>
confirmLeadershipConsumer,
BiFunction<String, UUID, CompletableFuture<Boolean>> hasLeadershipFunction) {
super();
this.registerConsumer = registerConsumer;
this.removeConsumer = removeConsumer;
this.confirmLeadershipConsumer = confirmLeadershipConsumer;
this.hasLeadershipFunction = hasLeadershipFunction;
}
@Override
protected void register(String componentId, LeaderContender contender) throws Exception {
registerConsumer.accept(componentId, contender);
}
@Override
protected void remove(String componentId) {
removeConsumer.accept(componentId);
}
@Override
protected CompletableFuture<Void> confirmLeadershipAsync(
String componentId, UUID leaderSessionID, String leaderAddress) {
return confirmLeadershipConsumer.apply(componentId, leaderSessionID, leaderAddress);
}
@Override
protected CompletableFuture<Boolean> hasLeadershipAsync(
String componentId, UUID leaderSessionId) {
return hasLeadershipFunction.apply(componentId, leaderSessionId);
}
public static Builder newBuilder() {
return new Builder()
.setRegisterConsumer(
(componentId, contender) -> {
throw new UnsupportedOperationException("register not supported");
})
.setRemoveConsumer(componentId -> {})
.setConfirmLeadershipConsumer(
(componentId, leaderSessionID, address) -> {
throw new UnsupportedOperationException(
"confirmLeadership not supported");
})
.setHasLeadershipFunction(
(componentId, leaderSessionID) -> {
throw new UnsupportedOperationException(
"hasLeadership not supported");
});
}
private static | TestingAbstractLeaderElectionService |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/autodetect/ProcessContext.java | {
"start": 2798,
"end": 4849
} | class ____ {
private boolean awaitCompletion;
private boolean finish;
private boolean silent;
private boolean shouldFinalizeJob = true;
private String reason;
KillBuilder setAwaitCompletion(boolean awaitCompletion) {
this.awaitCompletion = awaitCompletion;
return this;
}
KillBuilder setFinish(boolean finish) {
this.finish = finish;
return this;
}
KillBuilder setSilent(boolean silent) {
this.silent = silent;
return this;
}
KillBuilder setReason(String reason) {
this.reason = reason;
return this;
}
KillBuilder setShouldFinalizeJob(boolean shouldFinalizeJob) {
this.shouldFinalizeJob = shouldFinalizeJob;
return this;
}
void kill() {
if (autodetectCommunicator == null) {
// Killing a connected process would also complete the persistent task if `finish` was true,
// so we should do the same here even though the process wasn't yet connected at the time of
// the kill
if (finish) {
jobTask.markAsCompleted();
}
return;
}
String jobId = jobTask.getJobId();
if (silent == false) {
String extraInfo = (state.getName() == ProcessStateName.DYING) ? " while closing" : "";
if (reason == null) {
LOGGER.info("Killing job [{}]{}", jobId, extraInfo);
} else {
LOGGER.info("Killing job [{}]{}, because [{}]", jobId, extraInfo, reason);
}
}
try {
autodetectCommunicator.killProcess(awaitCompletion, finish, shouldFinalizeJob);
} catch (IOException e) {
LOGGER.error("[{}] Failed to kill autodetect process for job", jobId);
}
}
}
| KillBuilder |
java | quarkusio__quarkus | extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/MessageBundleProcessor.java | {
"start": 4525,
"end": 8874
} | class ____ {
private static final Logger LOG = Logger.getLogger(MessageBundleProcessor.class);
private static final String SUFFIX = "_Bundle";
private static final String BUNDLE_DEFAULT_KEY = "defaultKey";
private static final String BUNDLE_LOCALE = "locale";
private static final String MESSAGES = "messages";
private static final String MESSAGE = "message";
@BuildStep
AdditionalBeanBuildItem beans() {
return new AdditionalBeanBuildItem(MessageBundles.class, MessageBundle.class, Message.class, Localized.class,
MessageTemplateLocator.class);
}
@BuildStep
List<MessageBundleBuildItem> processBundles(BeanArchiveIndexBuildItem beanArchiveIndex,
ApplicationArchivesBuildItem applicationArchivesBuildItem,
BuildProducer<GeneratedClassBuildItem> generatedClasses,
BuildProducer<GeneratedResourceBuildItem> generatedResources,
BeanRegistrationPhaseBuildItem beanRegistration,
BuildProducer<BeanConfiguratorBuildItem> configurators,
BuildProducer<MessageBundleMethodBuildItem> messageTemplateMethods,
BuildProducer<HotDeploymentWatchedFileBuildItem> watchedFiles,
LocalesBuildTimeConfig locales) throws IOException {
IndexView index = beanArchiveIndex.getIndex();
Map<String, ClassInfo> found = new HashMap<>();
List<MessageBundleBuildItem> bundles = new ArrayList<>();
List<DotName> localizedInterfaces = new ArrayList<>();
// Message files sorted by priority
List<MessageFile> messageFiles = findMessageFiles(applicationArchivesBuildItem, watchedFiles);
// First collect all interfaces annotated with @MessageBundle
for (AnnotationInstance bundleAnnotation : index.getAnnotations(Names.BUNDLE)) {
if (bundleAnnotation.target().kind() == Kind.CLASS) {
ClassInfo bundleClass = bundleAnnotation.target().asClass();
if (Modifier.isInterface(bundleClass.flags())) {
AnnotationValue nameValue = bundleAnnotation.value();
String name = nameValue != null ? nameValue.asString() : MessageBundle.DEFAULTED_NAME;
if (name.equals(MessageBundle.DEFAULTED_NAME)) {
if (bundleClass.nestingType() == NestingType.TOP_LEVEL) {
name = MessageBundle.DEFAULT_NAME;
} else {
// The name starts with the DEFAULT_NAME followed by an underscore, followed by simple names of all
// declaring classes in the hierarchy seperated by underscores
List<String> names = new ArrayList<>();
names.add(DotNames.simpleName(bundleClass));
DotName enclosingName = bundleClass.enclosingClass();
while (enclosingName != null) {
ClassInfo enclosingClass = index.getClassByName(enclosingName);
if (enclosingClass != null) {
names.add(DotNames.simpleName(enclosingClass));
enclosingName = enclosingClass.nestingType() == NestingType.TOP_LEVEL ? null
: enclosingClass.enclosingClass();
}
}
Collections.reverse(names);
name = String.join("_", names);
}
LOG.debugf("Message bundle %s: name defaulted to %s", bundleClass, name);
}
if (!Namespaces.isValidNamespace(name)) {
throw new MessageBundleException(
String.format(
"Message bundle name [%s] declared on %s must be a valid namespace - the value can only consist of alphanumeric characters and underscores",
name, bundleClass));
}
if (found.containsKey(name)) {
throw new MessageBundleException(
String.format("Message bundle | MessageBundleProcessor |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/enums/EnumMapDeserializationTest.java | {
"start": 2267,
"end": 3447
} | class ____ {
public Map<Enum1988, Number> mapHolder;
public Enum1988 enumHolder;
}
/*
/**********************************************************
/* Test methods, basic
/**********************************************************
*/
protected final ObjectMapper MAPPER = newJsonMapper();
@Test
public void testEnumMaps() throws Exception
{
EnumMap<TestEnum,String> value = MAPPER.readValue("{\"OK\":\"value\"}",
new TypeReference<EnumMap<TestEnum,String>>() { });
assertEquals("value", value.get(TestEnum.OK));
}
@Test
public void testToStringEnumMaps() throws Exception
{
// can't reuse global one due to reconfig
ObjectReader r = MAPPER.reader()
.with(EnumFeature.READ_ENUMS_USING_TO_STRING);
EnumMap<LowerCaseEnum,String> value = r.forType(
new TypeReference<EnumMap<LowerCaseEnum,String>>() { })
.readValue("{\"a\":\"value\"}");
assertEquals("value", value.get(LowerCaseEnum.A));
}
/*
/**********************************************************
/* Test methods: custom | Holder1988 |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingDynamicUpdateAndInheritanceTest.java | {
"start": 6237,
"end": 6472
} | class ____ extends AbstractVersion {
@Column(name = "FILESIZE")
private Long fileSize;
public Long getFileSize() {
return fileSize;
}
public void setFileSize(Long fileSize) {
this.fileSize = fileSize;
}
}
}
| FileVersion |
java | grpc__grpc-java | core/src/test/java/io/grpc/internal/ReadableBuffersArrayTest.java | {
"start": 1112,
"end": 1712
} | class ____ extends ReadableBufferTestBase {
@Test
public void bufferShouldExposeArray() {
byte[] array = msg.getBytes(UTF_8);
ReadableBuffer buffer = wrap(array, 1, msg.length() - 1);
assertTrue(buffer.hasArray());
assertSame(array, buffer.array());
assertEquals(1, buffer.arrayOffset());
// Now read a byte and verify that the offset changes.
buffer.readUnsignedByte();
assertEquals(2, buffer.arrayOffset());
}
@Override
protected ReadableBuffer buffer() {
return ReadableBuffers.wrap(msg.getBytes(UTF_8), 0, msg.length());
}
}
| ReadableBuffersArrayTest |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/google/MapGenerators.java | {
"start": 4458,
"end": 5598
} | class ____
implements TestListGenerator<Entry<String, Integer>> {
@Override
public SampleElements<Entry<String, Integer>> samples() {
return new SampleElements<>(
mapEntry("foo", 5),
mapEntry("bar", 3),
mapEntry("baz", 17),
mapEntry("quux", 1),
mapEntry("toaster", -2));
}
@SuppressWarnings("unchecked")
@Override
public Entry<String, Integer>[] createArray(int length) {
return (Entry<String, Integer>[]) new Entry<?, ?>[length];
}
@Override
public Iterable<Entry<String, Integer>> order(List<Entry<String, Integer>> insertionOrder) {
return insertionOrder;
}
@Override
public List<Entry<String, Integer>> create(Object... elements) {
ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder();
for (Object o : elements) {
@SuppressWarnings("unchecked")
Entry<String, Integer> entry = (Entry<String, Integer>) checkNotNull(o);
builder.put(entry);
}
return builder.buildOrThrow().entrySet().asList();
}
}
public static | ImmutableMapEntryListGenerator |
java | apache__dubbo | dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/SpringDemoServiceImpl.java | {
"start": 1216,
"end": 2910
} | class ____ implements SpringRestDemoService {
private static Map<String, Object> context;
private boolean called;
@Override
public String sayHello(String name) {
called = true;
return "Hello, " + name;
}
@Override
public boolean isCalled() {
return called;
}
@Override
public String testFormBody(User user) {
return user.getName();
}
@Override
public List<String> testFormMapBody(LinkedMultiValueMap map) {
return map.get("form");
}
@Override
public String testHeader(String header) {
return header;
}
@Override
public String testHeaderInt(int header) {
return String.valueOf(header);
}
@Override
public Integer hello(Integer a, Integer b) {
context = RpcContext.getServerAttachment().getObjectAttachments();
return a + b;
}
@Override
public String error() {
throw new RuntimeException();
}
@ExceptionHandler(RuntimeException.class)
public String onError(HttpRequest request, Throwable t) {
return "ok";
}
@ExceptionHandler(Exception.class)
public String onError1() {
return "ok1";
}
public static Map<String, Object> getAttachments() {
return context;
}
@Override
public int primitiveInt(int a, int b) {
return a + b;
}
@Override
public long primitiveLong(long a, Long b) {
return a + b;
}
@Override
public long primitiveByte(byte a, Long b) {
return a + b;
}
@Override
public long primitiveShort(short a, Long b, int c) {
return a + b;
}
}
| SpringDemoServiceImpl |
java | apache__kafka | server/src/main/java/org/apache/kafka/server/share/fetch/PartitionMaxBytesStrategy.java | {
"start": 1038,
"end": 1169
} | interface ____ identify the max bytes for topic partitions in a share fetch request based on different strategy types.
*/
public | helps |
java | quarkusio__quarkus | integration-tests/injectmock/src/main/java/io/quarkus/it/mockbean/DummyServiceProducer.java | {
"start": 166,
"end": 338
} | class ____ {
@Produces
@ApplicationScoped
@Named("first")
public DummyService dummyService() {
return new DummyService1();
}
}
| DummyServiceProducer |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSOpsCountStatistics.java | {
"start": 1474,
"end": 1552
} | class ____ thread safe, and is generally shared by multiple threads.
*/
public | is |
java | apache__camel | components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/LimitsManualIT.java | {
"start": 1195,
"end": 4384
} | class ____ extends AbstractSalesforceTestBase {
private static final Object NOT_USED = null;
@Test
public void shouldFetchLimitsForOrganization() {
final Limits limits = template.requestBody("direct:test-limits", NOT_USED, Limits.class);
assertNotNull(limits, "Should fetch limits from Salesforce REST API");
assertLimitIsFetched("ConcurrentAsyncGetReportInstances", limits.getConcurrentAsyncGetReportInstances());
assertLimitIsFetched("ConcurrentSyncReportRuns", limits.getConcurrentSyncReportRuns());
assertLimitIsFetched("DailyApiRequests", limits.getDailyApiRequests());
assertLimitIsFetched("DailyAsyncApexExecutions", limits.getDailyAsyncApexExecutions());
assertLimitIsFetched("DailyBulkApiRequests", limits.getDailyBulkApiRequests());
assertLimitIsFetched("DailyDurableGenericStreamingApiEvents", limits.getDailyDurableGenericStreamingApiEvents());
assertLimitIsFetched("DailyDurableStreamingApiEvents", limits.getDailyDurableStreamingApiEvents());
assertLimitIsFetched("DailyGenericStreamingApiEvents", limits.getDailyGenericStreamingApiEvents());
assertLimitIsFetched("DailyStreamingApiEvents", limits.getDailyStreamingApiEvents());
assertLimitIsFetched("DailyWorkflowEmails", limits.getDailyWorkflowEmails());
assertLimitIsFetched("DataStorageMB", limits.getDataStorageMB());
assertLimitIsFetched("DurableStreamingApiConcurrentClients", limits.getDurableStreamingApiConcurrentClients());
assertLimitIsFetched("FileStorageMB", limits.getFileStorageMB());
assertLimitIsFetched("HourlyAsyncReportRuns", limits.getHourlyAsyncReportRuns());
assertLimitIsFetched("HourlyDashboardRefreshes", limits.getHourlyDashboardRefreshes());
assertLimitIsFetched("HourlyDashboardResults", limits.getHourlyDashboardResults());
assertLimitIsFetched("HourlyDashboardStatuses", limits.getHourlyDashboardStatuses());
assertLimitIsFetched("HourlyODataCallout", limits.getHourlyODataCallout());
assertLimitIsFetched("HourlySyncReportRuns", limits.getHourlySyncReportRuns());
assertLimitIsFetched("HourlyTimeBasedWorkflow", limits.getHourlyTimeBasedWorkflow());
assertLimitIsFetched("MassEmail", limits.getMassEmail());
assertLimitIsFetched("SingleEmail", limits.getSingleEmail());
assertLimitIsFetched("StreamingApiConcurrentClients", limits.getStreamingApiConcurrentClients());
}
private static void assertLimitIsFetched(String property, Usage usage) {
assertNotNull(usage, "Usage for `" + property + "` should be defined");
assertNotEquals(0, usage.getMax(), "Max usage for `" + property + "` should be defined");
assertNotEquals(0, usage.getRemaining(), "Remaining usage for `" + property + "` should be defined");
}
@Override
protected RouteBuilder doCreateRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:test-limits").to("salesforce:limits");
}
};
}
}
| LimitsManualIT |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java | {
"start": 160093,
"end": 161437
} | class ____ {
public Test() {}
public void foo() {
int z = 0;
switch (z) {
case 0:
// Fall thru
case 1:
var anotherString = "salut";
double dontHoistMe = 2.0d;
break;
case 2:
anotherString = "bonjour";
if (anotherString.length() > 0) {
// Note that this would pose a naming conflict with `foo` below (if hoisted)
String foo = "salut salut";
anotherString = foo;
}
String foo = "there";
break;
case 3:
anotherString = "just this var";
foo = "baz";
int staysHere;
}
return;
}
}
""")
.setArgs("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")
.doTest();
}
@Test
public void directConversion_hoistIntersectionType_noError() {
// The type of foo is an intersection type, which is not supported for hoisting.
helper
.addSourceLines(
"Test.java",
"""
| Test |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/config/composite/DefaultMergeStrategy.java | {
"start": 3113,
"end": 15798
} | class ____ implements MergeStrategy {
private static final String APPENDERS = "appenders";
private static final String PROPERTIES = "properties";
private static final String LOGGERS = "loggers";
private static final String SCRIPTS = "scripts";
private static final String FILTERS = "filters";
private static final String STATUS = "status";
private static final String NAME = "name";
private static final String REF = "ref";
/**
* Merge the root properties.
* @param rootNode The composite root node.
* @param configuration The configuration to merge.
*/
@Override
public void mergeRootProperties(final Node rootNode, final AbstractConfiguration configuration) {
for (final Map.Entry<String, String> attribute :
configuration.getRootNode().getAttributes().entrySet()) {
boolean isFound = false;
for (final Map.Entry<String, String> targetAttribute :
rootNode.getAttributes().entrySet()) {
if (targetAttribute.getKey().equalsIgnoreCase(attribute.getKey())) {
if (attribute.getKey().equalsIgnoreCase(STATUS)) {
final Level targetLevel = Level.getLevel(toRootUpperCase(targetAttribute.getValue()));
final Level sourceLevel = Level.getLevel(toRootUpperCase(attribute.getValue()));
if (targetLevel != null && sourceLevel != null) {
if (sourceLevel.isLessSpecificThan(targetLevel)) {
targetAttribute.setValue(attribute.getValue());
}
} else if (sourceLevel != null) {
targetAttribute.setValue(attribute.getValue());
}
} else if (attribute.getKey().equalsIgnoreCase("monitorInterval")) {
final int sourceInterval = Integers.parseInt(attribute.getValue());
final int targetInterval = Integers.parseInt(targetAttribute.getValue());
if (targetInterval == 0 || sourceInterval < targetInterval) {
targetAttribute.setValue(attribute.getValue());
}
} else if (attribute.getKey().equalsIgnoreCase("packages")) {
final String sourcePackages = attribute.getValue();
final String targetPackages = targetAttribute.getValue();
if (sourcePackages != null) {
if (targetPackages != null) {
targetAttribute.setValue(targetPackages + "," + sourcePackages);
} else {
targetAttribute.setValue(sourcePackages);
}
}
} else {
targetAttribute.setValue(attribute.getValue());
}
isFound = true;
}
}
if (!isFound) {
rootNode.getAttributes().put(attribute.getKey(), attribute.getValue());
}
}
}
/**
* Merge the source Configuration into the target Configuration.
*
* @param target The target node to merge into.
* @param source The source node.
* @param pluginManager The PluginManager.
*/
@Override
public void mergConfigurations(final Node target, final Node source, final PluginManager pluginManager) {
for (final Node sourceChildNode : source.getChildren()) {
final boolean isFilter = isFilterNode(sourceChildNode);
boolean isMerged = false;
for (final Node targetChildNode : target.getChildren()) {
if (isFilter) {
if (isFilterNode(targetChildNode)) {
updateFilterNode(target, targetChildNode, sourceChildNode, pluginManager);
isMerged = true;
break;
}
continue;
}
if (!targetChildNode.getName().equalsIgnoreCase(sourceChildNode.getName())) {
continue;
}
switch (toRootLowerCase(targetChildNode.getName())) {
case PROPERTIES:
case SCRIPTS:
case APPENDERS: {
for (final Node node : sourceChildNode.getChildren()) {
for (final Node targetNode : targetChildNode.getChildren()) {
if (Objects.equals(
targetNode.getAttributes().get(NAME),
node.getAttributes().get(NAME))) {
targetChildNode.getChildren().remove(targetNode);
break;
}
}
targetChildNode.getChildren().add(node);
}
isMerged = true;
break;
}
case LOGGERS: {
final Map<String, Node> targetLoggers = new HashMap<>();
for (final Node node : targetChildNode.getChildren()) {
targetLoggers.put(node.getName(), node);
}
for (final Node node : sourceChildNode.getChildren()) {
final Node targetNode = getLoggerNode(
targetChildNode, node.getAttributes().get(NAME));
final Node loggerNode = new Node(targetChildNode, node.getName(), node.getType());
if (targetNode != null) {
targetNode.getAttributes().putAll(node.getAttributes());
for (final Node sourceLoggerChild : node.getChildren()) {
if (isFilterNode(sourceLoggerChild)) {
boolean foundFilter = false;
for (final Node targetChild : targetNode.getChildren()) {
if (isFilterNode(targetChild)) {
updateFilterNode(
loggerNode, targetChild, sourceLoggerChild, pluginManager);
foundFilter = true;
break;
}
}
if (!foundFilter) {
final Node childNode = new Node(
loggerNode,
sourceLoggerChild.getName(),
sourceLoggerChild.getType());
childNode.getAttributes().putAll(sourceLoggerChild.getAttributes());
childNode.getChildren().addAll(sourceLoggerChild.getChildren());
targetNode.getChildren().add(childNode);
}
} else {
final Node childNode = new Node(
loggerNode, sourceLoggerChild.getName(), sourceLoggerChild.getType());
childNode.getAttributes().putAll(sourceLoggerChild.getAttributes());
childNode.getChildren().addAll(sourceLoggerChild.getChildren());
if (childNode.getName().equalsIgnoreCase("AppenderRef")) {
for (final Node targetChild : targetNode.getChildren()) {
if (isSameReference(targetChild, childNode)) {
targetNode.getChildren().remove(targetChild);
break;
}
}
} else {
for (final Node targetChild : targetNode.getChildren()) {
if (isSameName(targetChild, childNode)) {
targetNode.getChildren().remove(targetChild);
break;
}
}
}
targetNode.getChildren().add(childNode);
}
}
} else {
loggerNode.getAttributes().putAll(node.getAttributes());
loggerNode.getChildren().addAll(node.getChildren());
targetChildNode.getChildren().add(loggerNode);
}
}
isMerged = true;
break;
}
default: {
targetChildNode.getChildren().addAll(sourceChildNode.getChildren());
isMerged = true;
break;
}
}
}
if (!isMerged) {
if (sourceChildNode.getName().equalsIgnoreCase("Properties")) {
target.getChildren().add(0, sourceChildNode);
} else {
target.getChildren().add(sourceChildNode);
}
}
}
}
private Node getLoggerNode(final Node parentNode, final String name) {
for (final Node node : parentNode.getChildren()) {
final String nodeName = node.getAttributes().get(NAME);
if (name == null && nodeName == null) {
return node;
}
if (nodeName != null && nodeName.equals(name)) {
return node;
}
}
return null;
}
private void updateFilterNode(
final Node target,
final Node targetChildNode,
final Node sourceChildNode,
final PluginManager pluginManager) {
if (CompositeFilter.class.isAssignableFrom(targetChildNode.getType().getPluginClass())) {
final Node node = new Node(targetChildNode, sourceChildNode.getName(), sourceChildNode.getType());
node.getChildren().addAll(sourceChildNode.getChildren());
node.getAttributes().putAll(sourceChildNode.getAttributes());
targetChildNode.getChildren().add(node);
} else {
final PluginType pluginType = pluginManager.getPluginType(FILTERS);
final Node filtersNode = new Node(targetChildNode, FILTERS, pluginType);
final Node node = new Node(filtersNode, sourceChildNode.getName(), sourceChildNode.getType());
node.getAttributes().putAll(sourceChildNode.getAttributes());
final List<Node> children = filtersNode.getChildren();
children.add(targetChildNode);
children.add(node);
final List<Node> nodes = target.getChildren();
nodes.remove(targetChildNode);
nodes.add(filtersNode);
}
}
private boolean isFilterNode(final Node node) {
return Filter.class.isAssignableFrom(node.getType().getPluginClass());
}
private boolean isSameName(final Node node1, final Node node2) {
final String value = node1.getAttributes().get(NAME);
return value != null
&& toRootLowerCase(value)
.equals(toRootLowerCase(node2.getAttributes().get(NAME)));
}
private boolean isSameReference(final Node node1, final Node node2) {
final String value = node1.getAttributes().get(REF);
return value != null
&& toRootLowerCase(value)
.equals(toRootLowerCase(node2.getAttributes().get(REF)));
}
}
| DefaultMergeStrategy |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/Aws2SesComponentBuilderFactory.java | {
"start": 1365,
"end": 1865
} | interface ____ {
/**
* AWS Simple Email Service (SES) (camel-aws2-ses)
* Send e-mails through AWS SES service.
*
* Category: cloud,mail
* Since: 3.1
* Maven coordinates: org.apache.camel:camel-aws2-ses
*
* @return the dsl builder
*/
static Aws2SesComponentBuilder aws2Ses() {
return new Aws2SesComponentBuilderImpl();
}
/**
* Builder for the AWS Simple Email Service (SES) component.
*/
| Aws2SesComponentBuilderFactory |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/sql/exec/manytoone/EntityWithLazyManyToOneTest.java | {
"start": 1178,
"end": 2927
} | class ____ {
private Integer abstractEntityReferenceId;
private Integer concreteEntityReferenceId;
@BeforeEach
public void setUp(SessionFactoryScope scope) {
scope.inTransaction( session -> {
ConcreteEntity entity = new ConcreteEntity();
session.persist( entity );
LazyAbstractEntityReference reference = new LazyAbstractEntityReference( entity );
session.persist( reference );
this.abstractEntityReferenceId = reference.getId();
LazyConcreteEntityReference concreteReference = new LazyConcreteEntityReference( entity );
session.persist( concreteReference );
this.concreteEntityReferenceId = concreteReference.getId();
} );
}
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
public void containsLazyAbstractEntity(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
LazyAbstractEntityReference reference = session.get(
LazyAbstractEntityReference.class, abstractEntityReferenceId );
assertThat( reference ).isNotNull();
assertThat( Hibernate.isInitialized( reference.getEntity() ) ).isFalse();
}
);
}
@Test
public void containsLazyConcreteEntity(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
LazyConcreteEntityReference reference = session.get(
LazyConcreteEntityReference.class, concreteEntityReferenceId );
assertThat( reference ).isNotNull();
assertThat( Hibernate.isInitialized( reference.getEntity() ) ).isFalse();
}
);
}
@Entity(name = "AbstractEntity")
@Cacheable // NOTE that all these entities are cacheable - if removed from the entities both tests above - pass.
public static abstract | EntityWithLazyManyToOneTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.