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
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/array/HANAUnnestFunction.java
{ "start": 3133, "end": 11478 }
class ____ extends UnnestFunction { public HANAUnnestFunction() { super( "v", "i" ); } @Override protected <T> SelfRenderingSqmSetReturningFunction<T> generateSqmSetReturningFunctionExpression( List<? extends SqmTypedNode<?>> arguments, QueryEngine queryEngine) { return new SelfRenderingSqmSetReturningFunction<>( this, this, arguments, getArgumentsValidator(), getSetReturningTypeResolver(), queryEngine.getCriteriaBuilder(), getName() ) { @Override public TableGroup convertToSqlAst( NavigablePath navigablePath, String identifierVariable, boolean lateral, boolean canUseInnerJoins, boolean withOrdinality, SqmToSqlAstConverter walker) { // SAP HANA only supports table column references i.e. `TABLE_NAME.COLUMN_NAME` // or constants as arguments to xmltable/json_table, so it's impossible to do lateral joins. // There is a nice trick we can apply to make this work though, which is to figure out // the table group an expression belongs to and render a special CTE returning xml/json that can be joined. // The xml/json of that CTE needs to be extended by table group primary key data, // so we can join it later. final FunctionTableGroup functionTableGroup = (FunctionTableGroup) super.convertToSqlAst( navigablePath, identifierVariable, lateral, canUseInnerJoins, withOrdinality, walker ); //noinspection unchecked final List<SqlAstNode> sqlArguments = (List<SqlAstNode>) functionTableGroup.getPrimaryTableReference() .getFunctionExpression() .getArguments(); final Expression argument = (Expression) sqlArguments.get( 0 ); final Set<String> qualifiers = ColumnQualifierCollectorSqlAstWalker.determineColumnQualifiers( argument ); // Can only do this transformation if the argument contains a single column reference qualifier if ( qualifiers.size() == 1 ) { final String tableQualifier = qualifiers.iterator().next(); // Find the table group which the unnest argument refers to final FromClauseAccess fromClauseAccess = walker.getFromClauseAccess(); final TableGroup sourceTableGroup = fromClauseAccess.findTableGroupByIdentificationVariable( tableQualifier ); if ( sourceTableGroup != null ) { final List<ColumnInfo> idColumns = new ArrayList<>(); addIdColumns( sourceTableGroup.getModelPart(), idColumns ); // Register a query transformer to register the CTE and rewrite the array argument walker.registerQueryTransformer( (cteContainer, querySpec, converter) -> { // Determine a CTE name that is available final String baseName = "_data"; String cteName; int index = 0; do { cteName = baseName + ( index++ ); } while ( cteContainer.getCteStatement( cteName ) != null ); final TableGroup parentTableGroup = querySpec.getFromClause().queryTableGroups( tg -> tg.findTableGroupJoin( functionTableGroup ) == null ? null : tg ); final TableGroupJoin join = parentTableGroup.findTableGroupJoin( functionTableGroup ); final Expression lhs = createExpression( tableQualifier, idColumns ); final Expression rhs = createExpression( functionTableGroup.getPrimaryTableReference().getIdentificationVariable(), idColumns ); join.applyPredicate( new ComparisonPredicate( lhs, ComparisonOperator.EQUAL, rhs ) ); final String tableName = cteName; final List<CteColumn> cteColumns = List.of( new CteColumn( "v", argument.getExpressionType().getSingleJdbcMapping() ) ); final QuerySpec cteQuery = new QuerySpec( false ); cteQuery.getFromClause().addRoot( new StandardTableGroup( true, sourceTableGroup.getNavigablePath(), (TableGroupProducer) sourceTableGroup.getModelPart(), false, null, sourceTableGroup.findTableReference( tableQualifier ), false, null, joinTableName -> false, (joinTableName, tg) -> null, null ) ); final Expression wrapperExpression; if ( ExpressionTypeHelper.isXml( argument ) ) { wrapperExpression = new XmlWrapperExpression( idColumns, tableQualifier, argument ); // xmltable is allergic to null values and produces no result if one occurs, // so we must filter them out cteQuery.applyPredicate( new NullnessPredicate( argument, true ) ); } else { wrapperExpression = new JsonWrapperExpression( idColumns, tableQualifier, argument ); } cteQuery.getSelectClause().addSqlSelection( new SqlSelectionImpl( wrapperExpression ) ); cteContainer.addCteStatement( new CteStatement( new CteTable( tableName, cteColumns ), new SelectStatement( cteQuery ) ) ); sqlArguments.set( 0, new TableColumnReferenceExpression( argument, tableName, idColumns ) ); return querySpec; } ); } } return functionTableGroup; } private Expression createExpression(String qualifier, List<ColumnInfo> idColumns) { if ( idColumns.size() == 1 ) { final ColumnInfo columnInfo = idColumns.get( 0 ); return new ColumnReference( qualifier, columnInfo.name(), false, null, columnInfo.jdbcMapping() ); } else { final ArrayList<Expression> expressions = new ArrayList<>( idColumns.size() ); for ( ColumnInfo columnInfo : idColumns ) { expressions.add( new ColumnReference( qualifier, columnInfo.name(), false, null, columnInfo.jdbcMapping() ) ); } return new SqlTuple( expressions, null ); } } private void addIdColumns(ModelPartContainer modelPartContainer, List<ColumnInfo> idColumns) { if ( modelPartContainer instanceof EntityValuedModelPart entityValuedModelPart ) { addIdColumns( entityValuedModelPart.getEntityMappingType(), idColumns ); } else if ( modelPartContainer instanceof PluralAttributeMapping pluralAttributeMapping ) { addIdColumns( pluralAttributeMapping, idColumns ); } else if ( modelPartContainer instanceof EmbeddableValuedModelPart embeddableModelPart ) { addIdColumns( embeddableModelPart, idColumns ); } else { throw new QueryException( "Unsupported model part container: " + modelPartContainer ); } } private void addIdColumns(EmbeddableValuedModelPart embeddableModelPart, List<ColumnInfo> idColumns) { if ( embeddableModelPart instanceof EmbeddedCollectionPart collectionPart ) { addIdColumns( collectionPart.getCollectionAttribute(), idColumns ); } else { addIdColumns( embeddableModelPart.asAttributeMapping().getDeclaringType(), idColumns ); } } private void addIdColumns(PluralAttributeMapping pluralAttributeMapping, List<ColumnInfo> idColumns) { final DdlTypeRegistry ddlTypeRegistry = pluralAttributeMapping.getCollectionDescriptor() .getFactory() .getTypeConfiguration() .getDdlTypeRegistry(); addIdColumns( pluralAttributeMapping.getKeyDescriptor().getKeyPart(), ddlTypeRegistry, idColumns ); } private void addIdColumns(EntityMappingType entityMappingType, List<ColumnInfo> idColumns) { final DdlTypeRegistry ddlTypeRegistry = entityMappingType.getEntityPersister() .getFactory() .getTypeConfiguration() .getDdlTypeRegistry(); addIdColumns( entityMappingType.getIdentifierMapping(), ddlTypeRegistry, idColumns ); } private void addIdColumns( ValuedModelPart modelPart, DdlTypeRegistry ddlTypeRegistry, List<ColumnInfo> idColumns) { modelPart.forEachSelectable( (selectionIndex, selectableMapping) -> { final JdbcMapping jdbcMapping = selectableMapping.getJdbcMapping().getSingleJdbcMapping(); idColumns.add( new ColumnInfo( selectableMapping.getSelectionExpression(), jdbcMapping, ddlTypeRegistry.getTypeName( jdbcMapping.getJdbcType().getDefaultSqlTypeCode(), selectableMapping.toSize(), (Type) jdbcMapping ) ) ); } ); } }; } record ColumnInfo(String name, JdbcMapping jdbcMapping, String ddlType) {} static
HANAUnnestFunction
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/convert/UpdateViaObjectReaderTest.java
{ "start": 3740, "end": 4310 }
class ____ extends StdNodeBasedDeserializer<Bean3814A> { public Custom3814DeserializerA() { super(Bean3814A.class); } @Override public Bean3814A convert(JsonNode root, DeserializationContext ctxt) { return null; } @Override public Bean3814A convert(JsonNode root, DeserializationContext ctxt, Bean3814A oldValue) { oldValue.updateTo(root); return oldValue; } } @JsonDeserialize(using = Custom3814DeserializerB.class) static
Custom3814DeserializerA
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLCreateTriggerStatement.java
{ "start": 5043, "end": 5121 }
enum ____ { BEFORE, AFTER, INSTEAD_OF } public static
TriggerType
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/metrics/Cardinality.java
{ "start": 609, "end": 755 }
interface ____ extends NumericMetricsAggregation.SingleValue { /** * The number of unique terms. */ long getValue(); }
Cardinality
java
netty__netty
example/src/main/java/io/netty/example/dns/dot/DoTClient.java
{ "start": 1987, "end": 5219 }
class ____ { private static final String QUERY_DOMAIN = "www.example.com"; private static final int DNS_SERVER_PORT = 853; private static final String DNS_SERVER_HOST = "8.8.8.8"; private DoTClient() { } private static void handleQueryResp(DefaultDnsResponse msg) { if (msg.count(DnsSection.QUESTION) > 0) { DnsQuestion question = msg.recordAt(DnsSection.QUESTION, 0); System.out.printf("name: %s%n", question.name()); } for (int i = 0, count = msg.count(DnsSection.ANSWER); i < count; i++) { DnsRecord record = msg.recordAt(DnsSection.ANSWER, i); if (record.type() == DnsRecordType.A) { //just print the IP after query DnsRawRecord raw = (DnsRawRecord) record; System.out.println(NetUtil.bytesToIpAddress(ByteBufUtil.getBytes(raw.content()))); } } } public static void main(String[] args) throws Exception { EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); try { final SslContext sslContext = SslContextBuilder.forClient() .protocols("TLSv1.3", "TLSv1.2") .build(); Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast(sslContext.newHandler(ch.alloc(), DNS_SERVER_HOST, DNS_SERVER_PORT)) .addLast(new TcpDnsQueryEncoder()) .addLast(new TcpDnsResponseDecoder()) .addLast(new SimpleChannelInboundHandler<DefaultDnsResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, DefaultDnsResponse msg) { try { handleQueryResp(msg); } finally { ctx.close(); } } }); } }); final Channel ch = b.connect(DNS_SERVER_HOST, DNS_SERVER_PORT).sync().channel(); int randomID = new Random().nextInt(60000 - 1000) + 1000; DnsQuery query = new DefaultDnsQuery(randomID, DnsOpCode.QUERY) .setRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.A)); ch.writeAndFlush(query).sync(); boolean success = ch.closeFuture().await(10, TimeUnit.SECONDS); if (!success) { System.err.println("dns query timeout!"); ch.close().sync(); } } finally { group.shutdownGracefully(); } } }
DoTClient
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/codec/FindInputCodec.java
{ "start": 735, "end": 1483 }
class ____ implements TextMessageCodec<Object> { @Override public boolean supports(Type type) { return true; } @Override public String encode(Object value) { return value.toString(); } @Override public Object decode(Type type, String value) { JsonArray json = new JsonArray(value); List<Item> items = new ArrayList<>(); for (int i = 0; i < 3; i++) { Item item = new Item(); JsonObject jsonObject = json.getJsonObject(i); item.setCount(2 * jsonObject.getInteger("count")); items.add(item); } return items; } } }
MyInputCodec
java
quarkusio__quarkus
integration-tests/google-cloud-functions/src/test/java/io/quarkus/gcp/function/test/CloudEventStorageTestCase.java
{ "start": 382, "end": 1817 }
class ____ { @Test public void test() { // test the function using RestAssured given() .body("{\n" + " \"bucket\": \"MY_BUCKET\",\n" + " \"contentType\": \"text/plain\",\n" + " \"kind\": \"storage#object\",\n" + " \"md5Hash\": \"...\",\n" + " \"metageneration\": \"1\",\n" + " \"name\": \"MY_FILE.txt\",\n" + " \"size\": \"352\",\n" + " \"storageClass\": \"MULTI_REGIONAL\",\n" + " \"timeCreated\": \"2020-04-23T07:38:57.230Z\",\n" + " \"timeStorageClassUpdated\": \"2020-04-23T07:38:57.230Z\",\n" + " \"updated\": \"2020-04-23T07:38:57.230Z\"\n" + " }") .header("ce-specversion", "1.0") .header("ce-id", "1234567890") .header("ce-type", "google.cloud.storage.object.v1.finalized") .header("ce-source", "//storage.googleapis.com/projects/_/buckets/MY-BUCKET-NAME") .header("ce-subject", "objects/MY_FILE.txt") .when() .post() .then() .statusCode(200); } }
CloudEventStorageTestCase
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/support/DelegatingTransactionDefinition.java
{ "start": 1244, "end": 2521 }
class ____ implements TransactionDefinition, Serializable { private final TransactionDefinition targetDefinition; /** * Create a DelegatingTransactionAttribute for the given target attribute. * @param targetDefinition the target TransactionAttribute to delegate to */ public DelegatingTransactionDefinition(TransactionDefinition targetDefinition) { Assert.notNull(targetDefinition, "Target definition must not be null"); this.targetDefinition = targetDefinition; } @Override public int getPropagationBehavior() { return this.targetDefinition.getPropagationBehavior(); } @Override public int getIsolationLevel() { return this.targetDefinition.getIsolationLevel(); } @Override public int getTimeout() { return this.targetDefinition.getTimeout(); } @Override public boolean isReadOnly() { return this.targetDefinition.isReadOnly(); } @Override public @Nullable String getName() { return this.targetDefinition.getName(); } @Override public boolean equals(@Nullable Object other) { return this.targetDefinition.equals(other); } @Override public int hashCode() { return this.targetDefinition.hashCode(); } @Override public String toString() { return this.targetDefinition.toString(); } }
DelegatingTransactionDefinition
java
google__auto
common/src/main/java/com/google/auto/common/MoreTypes.java
{ "start": 28447, "end": 29111 }
class ____ extends CastingTypeVisitor<TypeVariable> { private static final TypeVariableVisitor INSTANCE = new TypeVariableVisitor(); TypeVariableVisitor() { super("type variable"); } @Override public TypeVariable visitTypeVariable(TypeVariable type, Void ignore) { return type; } } /** * Returns a {@link WildcardType} if the {@link TypeMirror} represents a wildcard type or throws * an {@link IllegalArgumentException}. */ public static WildcardType asWildcard(TypeMirror maybeWildcardType) { return maybeWildcardType.accept(WildcardTypeVisitor.INSTANCE, null); } private static final
TypeVariableVisitor
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
{ "start": 17474, "end": 18681 }
class ____ { @Nullable abstract String nullableString(); abstract int randomInt(); static NullableProperties create(@Nullable String nullableString, int randomInt) { return new AutoValue_AutoValueTest_NullableProperties(nullableString, randomInt); } } @Test public void testNullablePropertiesCanBeNull() { NullableProperties instance = NullableProperties.create(null, 23); assertNull(instance.nullableString()); assertThat(instance.randomInt()).isEqualTo(23); String expectedString = omitIdentifiers ? "{null, 23}" : "NullableProperties{nullableString=null, randomInt=23}"; assertThat(instance.toString()).isEqualTo(expectedString); } @AutoAnnotation static Nullable nullable() { return new AutoAnnotation_AutoValueTest_nullable(); } @Test public void testNullablePropertyConstructorParameterIsNullable() throws NoSuchMethodException { Constructor<?> constructor = AutoValue_AutoValueTest_NullableProperties.class.getDeclaredConstructor( String.class, int.class); assertThat(constructor.getParameterAnnotations()[0]).asList().contains(nullable()); } @AutoValue abstract static
NullableProperties
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StringSplitterTest.java
{ "start": 9711, "end": 10055 }
class ____ {", " void f() {", " String[] pieces = \"\".split(\":\");", " System.err.println(pieces);", // escapes " }", "}") .doTest(); } @Test public void mutation() { testHelper .addInputLines( "Test.java", """
Test
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/JsonIncludeTestResource.java
{ "start": 311, "end": 765 }
class ____ { @GET @Path("/my-object-empty") public MyObject getEmptyObject() { return new MyObject(); } @GET @Path("/my-object") public MyObject getObject() { MyObject myObject = new MyObject(); myObject.setName("name"); myObject.setDescription("description"); myObject.setStrings("test"); myObject.getMap().put("test", 1); return myObject; } }
JsonIncludeTestResource
java
redisson__redisson
redisson/src/main/java/org/redisson/RedissonMultimapCacheNative.java
{ "start": 1006, "end": 5011 }
class ____<K> { private final CommandAsyncExecutor commandExecutor; private final RedissonMultimap<K, ?> object; private final String prefix; RedissonMultimapCacheNative(CommandAsyncExecutor commandExecutor, RObject object, String prefix) { this.commandExecutor = commandExecutor; this.object = (RedissonMultimap<K, ?>) object; this.prefix = prefix; } public RFuture<Boolean> expireKeyAsync(K key, long timeToLive, TimeUnit timeUnit) { ByteBuf keyState = object.encodeMapKey(key); String keyHash = object.hash(keyState); String setName = object.getValuesName(keyHash); return commandExecutor.evalWriteAsync(object.getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN, "local res = redis.call('hpexpire', KEYS[1], ARGV[1], 'fields', 1, ARGV[2])" + "if res[1] == 1 then " + "redis.call('pexpire', KEYS[2], ARGV[1]); " + "return 1;" + "end; " + "return 0; ", Arrays.asList(object.getRawName(), setName), timeUnit.toMillis(timeToLive), object.encodeMapKey(key)); } public RFuture<Boolean> expireAsync(long timeToLive, TimeUnit timeUnit, String param) { return commandExecutor.evalWriteAsync(object.getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN, "local entries = redis.call('hgetall', KEYS[1]); " + "for i, v in ipairs(entries) do " + "if i % 2 == 0 then " + "local name = ARGV[2] .. v; " + "if ARGV[3] ~= '' then " + "redis.call('pexpire', name, ARGV[1], ARGV[3]); " + "else " + "redis.call('pexpire', name, ARGV[1]); " + "end; " + "end;" + "end; " + "if ARGV[3] ~= '' then " + "return redis.call('pexpire', KEYS[1], ARGV[1], ARGV[3]); " + "end; " + "return redis.call('pexpire', KEYS[1], ARGV[1]); ", Arrays.asList(object.getRawName()), timeUnit.toMillis(timeToLive), prefix, param); } public RFuture<Boolean> expireAtAsync(long timestamp, String param) { return commandExecutor.evalWriteAsync(object.getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN, "local entries = redis.call('hgetall', KEYS[1]); " + "for i, v in ipairs(entries) do " + "if i % 2 == 0 then " + "local name = ARGV[2] .. v; " + "if ARGV[3] ~= '' then " + "redis.call('pexpireat', name, ARGV[1], ARGV[3]); " + "else " + "redis.call('pexpireat', name, ARGV[1]); " + "end; " + "end;" + "end; " + "if ARGV[3] ~= '' then " + "return redis.call('pexpireat', KEYS[1], ARGV[1], ARGV[3]); " + "end; " + "return redis.call('pexpireat', KEYS[1], ARGV[1]); ", Arrays.asList(object.getRawName()), timestamp, prefix, param); } public RFuture<Boolean> clearExpireAsync() { return commandExecutor.evalWriteAsync(object.getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN, "local entries = redis.call('hgetall', KEYS[1]); " + "for i, v in ipairs(entries) do " + "if i % 2 == 0 then " + "local name = ARGV[1] .. v; " + "redis.call('persist', name); " + "end;" + "end; " + "return redis.call('persist', KEYS[1]); ", Arrays.asList(object.getRawName()), prefix); } }
RedissonMultimapCacheNative
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/headers/ReactiveClientHeadersFromBuilderListenerTest.java
{ "start": 1386, "end": 3550 }
class ____ { private static final String HEADER_NAME = "my-header"; private static final String HEADER_VALUE = "oifajrofijaeoir5gjaoasfaxcvcz"; public static final String COPIED_INCOMING_HEADER = "copied-incoming-header"; public static final String INCOMING_HEADER = "incoming-header"; public static final String DIRECT_HEADER_PARAM = "direct-header-param"; public static final String DIRECT_HEADER_PARAM_VAL = "direct-header-param-val"; @TestHTTPResource URI baseUri; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(ReactiveClientHeadersFromBuilderTest.Client.class, TestJacksonBasicMessageBodyReader.class) .addAsServiceProvider(RestClientBuilderListener.class, CustomRestClientBuilderListener.class)) .overrideRuntimeConfigKey("my.property-value", HEADER_VALUE); @Test void shouldPropagateHeaders() { // we're calling a resource that sets "incoming-header" header // this header should be dropped by the client and its value should be put into copied-incoming-header String propagatedHeaderValue = "propag8ed header"; // @formatter:off var response = given() .header(INCOMING_HEADER, propagatedHeaderValue) .body(baseUri.toString()) .when() .post("/call-client") .thenReturn(); // @formatter:on assertThat(response.statusCode()).isEqualTo(200); assertThat(response.jsonPath().getString(INCOMING_HEADER)).isNull(); assertThat(response.jsonPath().getString(COPIED_INCOMING_HEADER)).isEqualTo(format("[%s]", propagatedHeaderValue)); assertThat(response.jsonPath().getString(HEADER_NAME)).isEqualTo(format("[%s]", HEADER_VALUE)); assertThat(response.jsonPath().getString(DIRECT_HEADER_PARAM)).isEqualTo(format("[%s]", DIRECT_HEADER_PARAM_VAL)); } @Path("/") @ApplicationScoped public static
ReactiveClientHeadersFromBuilderListenerTest
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/verification/AtMost.java
{ "start": 711, "end": 1991 }
class ____ implements VerificationMode { private final int maxNumberOfInvocations; public AtMost(int maxNumberOfInvocations) { if (maxNumberOfInvocations < 0) { throw new MockitoException("Negative value is not allowed here"); } this.maxNumberOfInvocations = maxNumberOfInvocations; } @Override public void verify(VerificationData data) { List<Invocation> invocations = data.getAllInvocations(); MatchableInvocation wanted = data.getTarget(); List<Invocation> found = findInvocations(invocations, wanted); int foundSize = found.size(); if (foundSize > maxNumberOfInvocations) { throw wantedAtMostX(maxNumberOfInvocations, foundSize); } removeAlreadyVerified(found); markVerified(found, wanted); } private void removeAlreadyVerified(List<Invocation> invocations) { for (Iterator<Invocation> iterator = invocations.iterator(); iterator.hasNext(); ) { Invocation i = iterator.next(); if (i.isVerified()) { iterator.remove(); } } } @Override public String toString() { return "Wanted invocations count: at most " + maxNumberOfInvocations; } }
AtMost
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/aot/generate/GeneratedFiles.java
{ "start": 2973, "end": 4555 }
class ____ that should be used to determine the path * of the file * @param content an {@link InputStreamSource} that will provide an input * stream containing the file contents */ default void addSourceFile(String className, InputStreamSource content) { addFile(Kind.SOURCE, getClassNamePath(className), content); } /** * Add a generated {@link Kind#RESOURCE resource file} with content from the * given {@link CharSequence}. * @param path the relative path of the file * @param content the contents of the file */ default void addResourceFile(String path, CharSequence content) { addResourceFile(path, appendable -> appendable.append(content)); } /** * Add a generated {@link Kind#RESOURCE resource file} with content written * to an {@link Appendable} passed to the given {@link ThrowingConsumer}. * @param path the relative path of the file * @param content a {@link ThrowingConsumer} that accepts an * {@link Appendable} which will receive the file contents */ default void addResourceFile(String path, ThrowingConsumer<Appendable> content) { addFile(Kind.RESOURCE, path, content); } /** * Add a generated {@link Kind#RESOURCE resource file} with content from the * given {@link InputStreamSource}. * @param path the relative path of the file * @param content an {@link InputStreamSource} that will provide an input * stream containing the file contents */ default void addResourceFile(String path, InputStreamSource content) { addFile(Kind.RESOURCE, path, content); } /** * Add a generated {@link Kind#CLASS
name
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/DebuggerFactory.java
{ "start": 930, "end": 1182 }
interface ____ { /** * Creates the debugger. * * @param camelContext the camel context * @return the created debugger */ Debugger createDebugger(CamelContext camelContext) throws Exception; }
DebuggerFactory
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/manytomany/BasicList.java
{ "start": 963, "end": 7746 }
class ____ { private Integer ed1_id; private Integer ed2_id; private Integer ing1_id; private Integer ing2_id; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { // Revision 1 scope.inTransaction( em -> { ListOwnedEntity ed1 = new ListOwnedEntity( 1, "data_ed_1" ); ListOwnedEntity ed2 = new ListOwnedEntity( 2, "data_ed_2" ); ListOwningEntity ing1 = new ListOwningEntity( 3, "data_ing_1" ); ListOwningEntity ing2 = new ListOwningEntity( 4, "data_ing_2" ); em.persist( ed1 ); em.persist( ed2 ); em.persist( ing1 ); em.persist( ing2 ); ed1_id = ed1.getId(); ed2_id = ed2.getId(); ing1_id = ing1.getId(); ing2_id = ing2.getId(); } ); // Revision 2 scope.inTransaction( em -> { ListOwningEntity ing1 = em.find( ListOwningEntity.class, ing1_id ); ListOwningEntity ing2 = em.find( ListOwningEntity.class, ing2_id ); ListOwnedEntity ed1 = em.find( ListOwnedEntity.class, ed1_id ); ListOwnedEntity ed2 = em.find( ListOwnedEntity.class, ed2_id ); ing1.setReferences( new ArrayList<ListOwnedEntity>() ); ing1.getReferences().add( ed1 ); ing2.setReferences( new ArrayList<ListOwnedEntity>() ); ing2.getReferences().add( ed1 ); ing2.getReferences().add( ed2 ); } ); // Revision 3 scope.inTransaction( em -> { ListOwningEntity ing1 = em.find( ListOwningEntity.class, ing1_id ); ListOwnedEntity ed2 = em.find( ListOwnedEntity.class, ed2_id ); ing1.getReferences().add( ed2 ); } ); // Revision 4 scope.inTransaction( em -> { ListOwningEntity ing1 = em.find( ListOwningEntity.class, ing1_id ); ListOwnedEntity ed1 = em.find( ListOwnedEntity.class, ed1_id ); ing1.getReferences().remove( ed1 ); } ); // Revision 5 scope.inTransaction( em -> { ListOwningEntity ing1 = em.find( ListOwningEntity.class, ing1_id ); ing1.setReferences( null ); } ); } @Test public void testRevisionsCounts(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); assertEquals( Arrays.asList( 1, 2, 4 ), auditReader.getRevisions( ListOwnedEntity.class, ed1_id ) ); assertEquals( Arrays.asList( 1, 2, 3, 5 ), auditReader.getRevisions( ListOwnedEntity.class, ed2_id ) ); assertEquals( Arrays.asList( 1, 2, 3, 4, 5 ), auditReader.getRevisions( ListOwningEntity.class, ing1_id ) ); assertEquals( Arrays.asList( 1, 2 ), auditReader.getRevisions( ListOwningEntity.class, ing2_id ) ); } ); } @Test public void testHistoryOfEdId1(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); ListOwningEntity ing1 = em.find( ListOwningEntity.class, ing1_id ); ListOwningEntity ing2 = em.find( ListOwningEntity.class, ing2_id ); ListOwnedEntity rev1 = auditReader.find( ListOwnedEntity.class, ed1_id, 1 ); ListOwnedEntity rev2 = auditReader.find( ListOwnedEntity.class, ed1_id, 2 ); ListOwnedEntity rev3 = auditReader.find( ListOwnedEntity.class, ed1_id, 3 ); ListOwnedEntity rev4 = auditReader.find( ListOwnedEntity.class, ed1_id, 4 ); ListOwnedEntity rev5 = auditReader.find( ListOwnedEntity.class, ed1_id, 5 ); assertEquals( Collections.EMPTY_LIST, rev1.getReferencing() ); assert TestTools.checkCollection( rev2.getReferencing(), ing1, ing2 ); assert TestTools.checkCollection( rev3.getReferencing(), ing1, ing2 ); assert TestTools.checkCollection( rev4.getReferencing(), ing2 ); assert TestTools.checkCollection( rev5.getReferencing(), ing2 ); } ); } @Test public void testHistoryOfEdId2(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); ListOwningEntity ing1 = em.find( ListOwningEntity.class, ing1_id ); ListOwningEntity ing2 = em.find( ListOwningEntity.class, ing2_id ); ListOwnedEntity rev1 = auditReader.find( ListOwnedEntity.class, ed2_id, 1 ); ListOwnedEntity rev2 = auditReader.find( ListOwnedEntity.class, ed2_id, 2 ); ListOwnedEntity rev3 = auditReader.find( ListOwnedEntity.class, ed2_id, 3 ); ListOwnedEntity rev4 = auditReader.find( ListOwnedEntity.class, ed2_id, 4 ); ListOwnedEntity rev5 = auditReader.find( ListOwnedEntity.class, ed2_id, 5 ); assertEquals( Collections.EMPTY_LIST, rev1.getReferencing() ); assert TestTools.checkCollection( rev2.getReferencing(), ing2 ); assert TestTools.checkCollection( rev3.getReferencing(), ing1, ing2 ); assert TestTools.checkCollection( rev4.getReferencing(), ing1, ing2 ); assert TestTools.checkCollection( rev5.getReferencing(), ing2 ); } ); } @Test public void testHistoryOfEdIng1(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); ListOwnedEntity ed1 = em.find( ListOwnedEntity.class, ed1_id ); ListOwnedEntity ed2 = em.find( ListOwnedEntity.class, ed2_id ); ListOwningEntity rev1 = auditReader.find( ListOwningEntity.class, ing1_id, 1 ); ListOwningEntity rev2 = auditReader.find( ListOwningEntity.class, ing1_id, 2 ); ListOwningEntity rev3 = auditReader.find( ListOwningEntity.class, ing1_id, 3 ); ListOwningEntity rev4 = auditReader.find( ListOwningEntity.class, ing1_id, 4 ); ListOwningEntity rev5 = auditReader.find( ListOwningEntity.class, ing1_id, 5 ); assertEquals( Collections.EMPTY_LIST, rev1.getReferences() ); assert TestTools.checkCollection( rev2.getReferences(), ed1 ); assert TestTools.checkCollection( rev3.getReferences(), ed1, ed2 ); assert TestTools.checkCollection( rev4.getReferences(), ed2 ); assertEquals( Collections.EMPTY_LIST, rev5.getReferences() ); } ); } @Test public void testHistoryOfEdIng2(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); ListOwnedEntity ed1 = em.find( ListOwnedEntity.class, ed1_id ); ListOwnedEntity ed2 = em.find( ListOwnedEntity.class, ed2_id ); ListOwningEntity rev1 = auditReader.find( ListOwningEntity.class, ing2_id, 1 ); ListOwningEntity rev2 = auditReader.find( ListOwningEntity.class, ing2_id, 2 ); ListOwningEntity rev3 = auditReader.find( ListOwningEntity.class, ing2_id, 3 ); ListOwningEntity rev4 = auditReader.find( ListOwningEntity.class, ing2_id, 4 ); ListOwningEntity rev5 = auditReader.find( ListOwningEntity.class, ing2_id, 5 ); assertEquals( Collections.EMPTY_LIST, rev1.getReferences() ); assert TestTools.checkCollection( rev2.getReferences(), ed1, ed2 ); assert TestTools.checkCollection( rev3.getReferences(), ed1, ed2 ); assert TestTools.checkCollection( rev4.getReferences(), ed1, ed2 ); assert TestTools.checkCollection( rev5.getReferences(), ed1, ed2 ); } ); } }
BasicList
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/support/TransactionSynchronization.java
{ "start": 1315, "end": 1803 }
interface ____ enable the execution order of * synchronizations to be controlled declaratively. The default {@link #getOrder() * order} is {@link Ordered#LOWEST_PRECEDENCE}, indicating late execution; return * a lower value for earlier execution. * * @author Juergen Hoeller * @since 02.06.2003 * @see TransactionSynchronizationManager * @see AbstractPlatformTransactionManager * @see org.springframework.jdbc.datasource.DataSourceUtils#CONNECTION_SYNCHRONIZATION_ORDER */ public
to
java
quarkusio__quarkus
independent-projects/bootstrap/app-model/src/main/java/io/quarkus/sbom/ApplicationManifest.java
{ "start": 2021, "end": 4161 }
class ____ extends ApplicationManifest { private Builder() { super(); } private Builder(ApplicationManifest manifest) { super(manifest); } public Builder setMainComponent(ApplicationComponent main) { this.mainComponent = main; return this; } public Builder addComponent(ApplicationComponent component) { if (component == null) { throw new IllegalArgumentException("component is null"); } if (components == null) { components = new ArrayList<>(); } components.add(component); return this; } public Builder setRunnerPath(Path runnerPath) { this.runnerPath = runnerPath; return this; } public ApplicationManifest build() { return new ApplicationManifest(this); } } protected ApplicationComponent mainComponent; protected Collection<ApplicationComponent> components; protected Path runnerPath; private ApplicationManifest() { } private ApplicationManifest(ApplicationManifest builder) { if (builder.mainComponent == null) { throw new IllegalArgumentException("Main component is null"); } this.mainComponent = builder.mainComponent.ensureImmutable(); if (builder.components == null || builder.components.isEmpty()) { this.components = List.of(); } else { var tmp = new ApplicationComponent[builder.components.size()]; int i = 0; for (var c : builder.components) { tmp[i++] = c.ensureImmutable(); } this.components = List.of(tmp); } this.runnerPath = builder.runnerPath; } public ApplicationComponent getMainComponent() { return mainComponent; } public Collection<ApplicationComponent> getComponents() { return components == null ? List.of() : components; } public Path getRunnerPath() { return runnerPath; } }
Builder
java
apache__spark
streaming/src/test/java/org/apache/spark/streaming/JavaWriteAheadLogSuite.java
{ "start": 1362, "end": 1425 }
class ____ extends WriteAheadLog { static
JavaWriteAheadLogSuite
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/DefaultResourceAllocationStrategy.java
{ "start": 26669, "end": 29306 }
class ____ implements ResourceMatchingStrategy { private final Comparator<InternalResourceInfo> resourceInfoComparator; /** * Returns a {@link PrioritizedResourceMatchingStrategy} that prioritizes the resource with * the least utilization, used to evenly distribute slots to workers. * * @return least utilization prioritized resource matching strategy. */ public static PrioritizedResourceMatchingStrategy leastUtilization() { return new PrioritizedResourceMatchingStrategy( Comparator.comparingDouble(i -> i.utilization)); } /** * Returns a {@link PrioritizedResourceMatchingStrategy} that prioritizes the resource with * the highest utilization, used to minimize number of workers assigned. * * @return most utilization prioritized resource matching strategy. */ public static PrioritizedResourceMatchingStrategy mostUtilization() { return new PrioritizedResourceMatchingStrategy( Comparator.comparingDouble(i -> -i.utilization)); } private PrioritizedResourceMatchingStrategy( final Comparator<InternalResourceInfo> resourceInfoComparator) { this.resourceInfoComparator = resourceInfoComparator; } @Override public int tryFulfilledRequirementWithResource( List<InternalResourceInfo> internalResources, int numUnfulfilled, ResourceProfile requiredResource, JobID jobId) { if (internalResources.isEmpty()) { return numUnfulfilled; } Queue<InternalResourceInfo> prioritizedResources = new PriorityQueue<>(internalResources.size(), resourceInfoComparator); prioritizedResources.addAll(internalResources); while (numUnfulfilled > 0 && !prioritizedResources.isEmpty()) { final InternalResourceInfo currentTaskManager = prioritizedResources.poll(); if (currentTaskManager.tryAllocateSlotForJob(jobId, requiredResource)) { numUnfulfilled--; // ignore non-fitting task managers to reduce the overhead of insert and check. if (currentTaskManager.availableProfile.allFieldsNoLessThan(requiredResource)) { prioritizedResources.add(currentTaskManager); } } } return numUnfulfilled; } } }
PrioritizedResourceMatchingStrategy
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/graph/GraphParser.java
{ "start": 1408, "end": 1708 }
class ____ { // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Parse (creation) /** * Creates a root graph based on the passed {@code rootEntityClass} and parses * {@code graphText} into the generated root graph. * * @param rootEntityClass The entity
GraphParser
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/postgresql/ast/stmt/PGInsertStatement.java
{ "start": 1148, "end": 5464 }
class ____ extends SQLInsertStatement implements PGSQLStatement { private List<ValuesClause> valuesList = new ArrayList<ValuesClause>(); private SQLExpr returning; private boolean defaultValues; private List<SQLExpr> onConflictTarget; private SQLName onConflictConstraint; private SQLExpr onConflictWhere; private SQLExpr onConflictUpdateWhere; private boolean onConflictDoNothing; private List<SQLUpdateSetItem> onConflictUpdateSetItems; public PGInsertStatement() { dbType = DbType.postgresql; } public void cloneTo(PGInsertStatement x) { super.cloneTo(x); for (ValuesClause v : valuesList) { ValuesClause v2 = v.clone(); v2.setParent(x); x.valuesList.add(v2); } if (returning != null) { x.setReturning(returning.clone()); } x.defaultValues = defaultValues; } public SQLExpr getReturning() { return returning; } public void setReturning(SQLExpr returning) { this.returning = returning; } public ValuesClause getValues() { if (valuesList.isEmpty()) { return null; } return valuesList.get(0); } public void setValues(ValuesClause values) { if (valuesList.isEmpty()) { valuesList.add(values); } else { valuesList.set(0, values); } } public List<ValuesClause> getValuesList() { return valuesList; } public void addValueCause(ValuesClause valueClause) { valueClause.setParent(this); valuesList.add(valueClause); } public boolean isDefaultValues() { return defaultValues; } public void setDefaultValues(boolean defaultValues) { this.defaultValues = defaultValues; } protected void accept0(SQLASTVisitor visitor) { if (visitor instanceof PGASTVisitor) { accept0((PGASTVisitor) visitor); } else { super.accept0(visitor); } } @Override public void accept0(PGASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, with); this.acceptChild(visitor, tableSource); this.acceptChild(visitor, columns); this.acceptChild(visitor, valuesList); this.acceptChild(visitor, query); this.acceptChild(visitor, returning); } visitor.endVisit(this); } public PGInsertStatement clone() { PGInsertStatement x = new PGInsertStatement(); cloneTo(x); return x; } public List<SQLExpr> getOnConflictTarget() { return onConflictTarget; } public void setOnConflictTarget(List<SQLExpr> onConflictTarget) { this.onConflictTarget = onConflictTarget; } public boolean isOnConflictDoNothing() { return onConflictDoNothing; } public void setOnConflictDoNothing(boolean onConflictDoNothing) { this.onConflictDoNothing = onConflictDoNothing; } public List<SQLUpdateSetItem> getOnConflictUpdateSetItems() { return onConflictUpdateSetItems; } public void addConflicUpdateItem(SQLUpdateSetItem item) { if (onConflictUpdateSetItems == null) { onConflictUpdateSetItems = new ArrayList<SQLUpdateSetItem>(); } item.setParent(this); onConflictUpdateSetItems.add(item); } public SQLName getOnConflictConstraint() { return onConflictConstraint; } public void setOnConflictConstraint(SQLName x) { if (x != null) { x.setParent(this); } this.onConflictConstraint = x; } public SQLExpr getOnConflictWhere() { return onConflictWhere; } public void setOnConflictWhere(SQLExpr x) { if (x != null) { x.setParent(this); } this.onConflictWhere = x; } public SQLExpr getOnConflictUpdateWhere() { return onConflictUpdateWhere; } public void setOnConflictUpdateWhere(SQLExpr x) { if (x != null) { x.setParent(this); } this.onConflictUpdateWhere = x; } @Override public List<SQLCommentHint> getHeadHintsDirect() { return null; } }
PGInsertStatement
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/block/OracleBlockTest4.java
{ "start": 936, "end": 3964 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = "DECLARE" + " done BOOLEAN;" + "BEGIN" + " FOR i IN 1..50 LOOP" + " IF done THEN" + " GOTO end_loop;" + " END IF;" + " <<end_loop>>" + " END LOOP;" + "END;"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statement = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); statement.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("conditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(0, visitor.getTables().size()); assertEquals(0, visitor.getColumns().size()); } public void test_1() throws Exception { String sql = "DECLARE" + " done BOOLEAN;" + "BEGIN" + " FOR i IN REVERSE 1..50 LOOP" + " IF done THEN" + " GOTO end_loop;" + " END IF;" + " <<end_loop>>" + " END LOOP;" + "END;"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statement = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); assertEquals("DECLARE\n" + "\tdone BOOLEAN;\n" + "BEGIN\n" + "\tFOR i IN REVERSE 1..50\n" + "\tLOOP\n" + "\t\tIF done THEN\n" + "\t\t\tGOTO end_loop;\n" + "\t\tEND IF;\n" + "\t\t<<end_loop>>\n" + "\tEND LOOP;\n" + "END;", statement.toString()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); statement.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("conditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(0, visitor.getTables().size()); assertEquals(0, visitor.getColumns().size()); } }
OracleBlockTest4
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/PolymorphicDeserSubtypeCheck5016Test.java
{ "start": 1258, "end": 1467 }
class ____ { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public Animal thisType; } static
AnimalInfo
java
quarkusio__quarkus
independent-projects/junit5-virtual-threads/src/main/java/io/quarkus/test/junit5/virtual/internal/VirtualThreadExtension.java
{ "start": 3649, "end": 4167 }
class ____. return null; } if (clazz.isAnnotationPresent(ShouldPin.class)) { return clazz.getAnnotation(ShouldPin.class); } return null; } private ShouldNotPin getShouldNotPin(Class<?> clazz, Method method) { if (method.isAnnotationPresent(ShouldNotPin.class)) { return method.getAnnotation(ShouldNotPin.class); } if (method.isAnnotationPresent(ShouldPin.class)) { // If the method overrides the
annotation
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/requests/DeleteAclsRequestTest.java
{ "start": 1638, "end": 4387 }
class ____ { private static final short V0 = 0; private static final short V1 = 1; private static final AclBindingFilter LITERAL_FILTER = new AclBindingFilter(new ResourcePatternFilter(ResourceType.TOPIC, "foo", PatternType.LITERAL), new AccessControlEntryFilter("User:ANONYMOUS", "127.0.0.1", AclOperation.READ, AclPermissionType.DENY)); private static final AclBindingFilter PREFIXED_FILTER = new AclBindingFilter(new ResourcePatternFilter(ResourceType.GROUP, "prefix", PatternType.PREFIXED), new AccessControlEntryFilter("User:*", "127.0.0.1", AclOperation.CREATE, AclPermissionType.ALLOW)); private static final AclBindingFilter ANY_FILTER = new AclBindingFilter(new ResourcePatternFilter(ResourceType.GROUP, "bar", PatternType.ANY), new AccessControlEntryFilter("User:*", "127.0.0.1", AclOperation.CREATE, AclPermissionType.ALLOW)); private static final AclBindingFilter UNKNOWN_FILTER = new AclBindingFilter(new ResourcePatternFilter(ResourceType.UNKNOWN, "prefix", PatternType.PREFIXED), new AccessControlEntryFilter("User:*", "127.0.0.1", AclOperation.CREATE, AclPermissionType.ALLOW)); @Test public void shouldThrowOnV0IfPrefixed() { assertThrows(UnsupportedVersionException.class, () -> new DeleteAclsRequest.Builder(requestData(PREFIXED_FILTER)).build(V0)); } @Test public void shouldThrowOnUnknownElements() { assertThrows(IllegalArgumentException.class, () -> new DeleteAclsRequest.Builder(requestData(UNKNOWN_FILTER)).build(V1)); } @Test public void shouldRoundTripV1() { final DeleteAclsRequest original = new DeleteAclsRequest.Builder( requestData(LITERAL_FILTER, PREFIXED_FILTER, ANY_FILTER) ).build(V1); final Readable readable = original.serialize(); final DeleteAclsRequest result = DeleteAclsRequest.parse(readable, V1); assertRequestEquals(original, result); } private static void assertRequestEquals(final DeleteAclsRequest original, final DeleteAclsRequest actual) { assertEquals(original.filters().size(), actual.filters().size(), "Number of filters wrong"); for (int idx = 0; idx != original.filters().size(); ++idx) { final AclBindingFilter originalFilter = original.filters().get(idx); final AclBindingFilter actualFilter = actual.filters().get(idx); assertEquals(originalFilter, actualFilter); } } private static DeleteAclsRequestData requestData(AclBindingFilter... acls) { return new DeleteAclsRequestData().setFilters(Arrays.stream(acls) .map(DeleteAclsRequest::deleteAclsFilter) .collect(Collectors.toList())); } }
DeleteAclsRequestTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/type/TypeFactoryTest.java
{ "start": 1350, "end": 1448 }
class ____ extends MyStringXMap<Integer> { } @SuppressWarnings("serial") static
MyStringIntMap
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/action/TransportInferenceAction.java
{ "start": 1230, "end": 3028 }
class ____ extends BaseTransportInferenceAction<InferenceAction.Request> { @Inject public TransportInferenceAction( TransportService transportService, ActionFilters actionFilters, XPackLicenseState licenseState, InferenceEndpointRegistry inferenceEndpointRegistry, InferenceServiceRegistry serviceRegistry, InferenceStats inferenceStats, StreamingTaskManager streamingTaskManager, NodeClient nodeClient, ThreadPool threadPool ) { super( InferenceAction.NAME, transportService, actionFilters, licenseState, inferenceEndpointRegistry, serviceRegistry, inferenceStats, streamingTaskManager, InferenceAction.Request::new, nodeClient, threadPool ); } @Override protected boolean isInvalidTaskTypeForInferenceEndpoint(InferenceAction.Request request, Model model) { return false; } @Override protected ElasticsearchStatusException createInvalidTaskTypeException(InferenceAction.Request request, Model model) { return null; } @Override protected void doInference( Model model, InferenceAction.Request request, InferenceService service, ActionListener<InferenceServiceResults> listener ) { service.infer( model, request.getQuery(), request.getReturnDocuments(), request.getTopN(), request.getInput(), request.isStreaming(), request.getTaskSettings(), request.getInputType(), request.getInferenceTimeout(), listener ); } }
TransportInferenceAction
java
elastic__elasticsearch
x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/search/aggregations/bucket/geogrid/GeoHexGridTiler.java
{ "start": 17607, "end": 19216 }
class ____ extends GeoHexGridTiler { private final long maxAddresses; private final GeoHexVisitor visitor; UnboundedGeoHexGridTiler(int precision) { super(precision); this.visitor = new GeoHexVisitor(); maxAddresses = calcMaxAddresses(precision); } @Override protected boolean h3IntersectsBounds(long h3) { return true; } @Override protected GeoRelation relateTile(GeoShapeValues.GeoShapeValue geoValue, long h3) throws IOException { visitor.reset(h3); final int resolution = H3.getResolution(h3); if (resolution != precision && (visitor.getMaxY() > H3CartesianUtil.getNorthPolarBound(resolution) || visitor.getMinY() < H3CartesianUtil.getSouthPolarBound(resolution))) { // close to the poles, the properties of the H3 grid are lost because of the equirectangular projection, // therefore we cannot ensure that the relationship at this level make any sense in the next level. // Therefore, we just return CROSSES which just mean keep recursing. return GeoRelation.QUERY_CROSSES; } geoValue.visit(visitor); return visitor.relation(); } @Override protected boolean valueInsideBounds(GeoShapeValues.GeoShapeValue geoValue) { return true; } @Override protected long getMaxCells() { return maxAddresses; } } }
UnboundedGeoHexGridTiler
java
apache__rocketmq
remoting/src/test/java/org/apache/rocketmq/remoting/protocol/RemotingSerializableTest.java
{ "start": 1282, "end": 3103 }
class ____ { @Test public void testEncodeAndDecode_HeterogeneousClass() { Sample sample = new Sample(); byte[] bytes = RemotingSerializable.encode(sample); Sample decodedSample = RemotingSerializable.decode(bytes, Sample.class); assertThat(decodedSample).isEqualTo(sample); } @Test public void testToJson_normalString() { RemotingSerializable serializable = new RemotingSerializable() { private List<String> stringList = Arrays.asList("a", "o", "e", "i", "u", "v"); public List<String> getStringList() { return stringList; } public void setStringList(List<String> stringList) { this.stringList = stringList; } }; String string = serializable.toJson(); assertThat(string).isEqualTo("{\"stringList\":[\"a\",\"o\",\"e\",\"i\",\"u\",\"v\"]}"); } @Test public void testToJson_prettyString() { RemotingSerializable serializable = new RemotingSerializable() { private List<String> stringList = Arrays.asList("a", "o", "e", "i", "u", "v"); public List<String> getStringList() { return stringList; } public void setStringList(List<String> stringList) { this.stringList = stringList; } }; String prettyString = serializable.toJson(true); assertThat(prettyString).isEqualTo("{\n" + "\t\"stringList\":[\n" + "\t\t\"a\",\n" + "\t\t\"o\",\n" + "\t\t\"e\",\n" + "\t\t\"i\",\n" + "\t\t\"u\",\n" + "\t\t\"v\"\n" + "\t]\n" + "}"); } @Test public void testEncode() {
RemotingSerializableTest
java
quarkusio__quarkus
extensions/cache/runtime/src/main/java/io/quarkus/cache/runtime/caffeine/CaffeineCacheImpl.java
{ "start": 1130, "end": 1332 }
class ____ an internal Quarkus cache implementation using Caffeine. Do not use it explicitly from your Quarkus * application. * The public methods signatures may change without prior notice. */ public
is
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/DataTypeExtractorTest.java
{ "start": 3139, "end": 3600 }
class ____ { @SuppressWarnings({"unchecked", "rawtypes"}) private static Stream<TestSpec> testData() { return Stream.of( // simple extraction of INT TestSpec.forType(Integer.class).expectDataType(DataTypes.INT()), // simple extraction of BYTES TestSpec.forType(byte[].class).expectDataType(DataTypes.BYTES()), // extraction from hint conversion
DataTypeExtractorTest
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/runtime/graal/JVMChecksFeature.java
{ "start": 359, "end": 549 }
class ____ implements Feature { @Override public void duringSetup(Feature.DuringSetupAccess access) { JVMChecksRecorder.disableUnsafeRelatedWarnings(); } }
JVMChecksFeature
java
alibaba__fastjson
src/main/java/com/alibaba/fastjson/support/geo/Polygon.java
{ "start": 199, "end": 512 }
class ____ extends Geometry { private double[][][] coordinates; public Polygon() { super("Polygon"); } public double[][][] getCoordinates() { return coordinates; } public void setCoordinates(double[][][] coordinates) { this.coordinates = coordinates; } }
Polygon
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/support/ConstructorResolverAotTests.java
{ "start": 25953, "end": 26165 }
class ____ { public SampleBeanWithConstructors() { } public SampleBeanWithConstructors(String name) { } public SampleBeanWithConstructors(Number number, String name) { } }
SampleBeanWithConstructors
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/script/ScriptMetadata.java
{ "start": 3839, "end": 11276 }
class ____ implements NamedDiff<Metadata.ProjectCustom> { final Diff<Map<String, StoredScriptSource>> pipelines; ScriptMetadataDiff(ScriptMetadata before, ScriptMetadata after) { this.pipelines = DiffableUtils.diff(before.scripts, after.scripts, DiffableUtils.getStringKeySerializer()); } ScriptMetadataDiff(StreamInput in) throws IOException { pipelines = DiffableUtils.readJdkMapDiff( in, DiffableUtils.getStringKeySerializer(), StoredScriptSource::new, StoredScriptSource::readDiffFrom ); } @Override public String getWriteableName() { return TYPE; } @Override public Metadata.ProjectCustom apply(Metadata.ProjectCustom part) { return new ScriptMetadata(pipelines.apply(((ScriptMetadata) part).scripts)); } @Override public void writeTo(StreamOutput out) throws IOException { pipelines.writeTo(out); } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.minimumCompatible(); } } /** * Convenience method to build and return a new * {@link ScriptMetadata} adding the specified stored script. */ static ScriptMetadata putStoredScript(ScriptMetadata previous, String id, StoredScriptSource source) { Builder builder = new Builder(previous); builder.storeScript(id, source); return builder.build(); } /** * Convenience method to build and return a new * {@link ScriptMetadata} deleting the specified stored script. */ static ScriptMetadata deleteStoredScript(ScriptMetadata previous, String id) { Builder builder = new ScriptMetadata.Builder(previous); builder.deleteScript(id); return builder.build(); } /** * The type of {@link ClusterState} data. */ public static final String TYPE = "stored_scripts"; /** * This will parse XContent into {@link ScriptMetadata}. * * The following format will be parsed: * * {@code * { * "<id>" : "<{@link StoredScriptSource#fromXContent(XContentParser, boolean)}>", * "<id>" : "<{@link StoredScriptSource#fromXContent(XContentParser, boolean)}>", * ... * } * } */ public static ScriptMetadata fromXContent(XContentParser parser) throws IOException { Map<String, StoredScriptSource> scripts = new HashMap<>(); String id = null; Token token = parser.currentToken(); if (token == null) { token = parser.nextToken(); } if (token != Token.START_OBJECT) { throw new ParsingException(parser.getTokenLocation(), "unexpected token [" + token + "], expected [{]"); } token = parser.nextToken(); while (token != Token.END_OBJECT) { switch (token) { case FIELD_NAME -> id = parser.currentName(); case START_OBJECT -> { if (id == null) { throw new ParsingException( parser.getTokenLocation(), "unexpected token [" + token + "], expected [<id>, <code>, {]" ); } StoredScriptSource source = StoredScriptSource.fromXContent(parser, true); // as of 8.0 we drop scripts/templates with an empty source // this check should be removed for the next upgradable version after 8.0 // since there is a guarantee no more empty scripts will exist if (source.getSource().isEmpty()) { if (Script.DEFAULT_TEMPLATE_LANG.equals(source.getLang())) { logger.warn("empty template [" + id + "] found and dropped"); } else { logger.warn("empty script [" + id + "] found and dropped"); } } else { scripts.put(id, source); } id = null; } default -> throw new ParsingException( parser.getTokenLocation(), "unexpected token [" + token + "], expected [<id>, <code>, {]" ); } token = parser.nextToken(); } return new ScriptMetadata(scripts); } public static NamedDiff<Metadata.ProjectCustom> readDiffFrom(StreamInput in) throws IOException { return new ScriptMetadataDiff(in); } private final Map<String, StoredScriptSource> scripts; /** * Standard constructor to create metadata to store scripts. * @param scripts The currently stored scripts. Must not be {@code null}, * use and empty {@link Map} to specify there were no * previously stored scripts. */ ScriptMetadata(Map<String, StoredScriptSource> scripts) { this.scripts = Collections.unmodifiableMap(scripts); } public ScriptMetadata(StreamInput in) throws IOException { Map<String, StoredScriptSource> scripts = new HashMap<>(); StoredScriptSource source; int size = in.readVInt(); for (int i = 0; i < size; i++) { String id = in.readString(); source = new StoredScriptSource(in); scripts.put(id, source); } this.scripts = Collections.unmodifiableMap(scripts); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeMap(scripts, StreamOutput::writeWriteable); } @Override public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params ignored) { return Iterators.map(scripts.entrySet().iterator(), entry -> (builder, params) -> { builder.field(entry.getKey()); return entry.getValue().toXContent(builder, params); }); } @Override public Diff<Metadata.ProjectCustom> diff(Metadata.ProjectCustom before) { return new ScriptMetadataDiff((ScriptMetadata) before, this); } @Override public String getWriteableName() { return TYPE; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.minimumCompatible(); } @Override public EnumSet<Metadata.XContentContext> context() { return Metadata.ALL_CONTEXTS; } /** * Returns the map of stored scripts. */ Map<String, StoredScriptSource> getStoredScripts() { return scripts; } /** * Retrieves a stored script based on a user-specified id. */ StoredScriptSource getStoredScript(String id) { return scripts.get(id); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScriptMetadata that = (ScriptMetadata) o; return scripts.equals(that.scripts); } @Override public int hashCode() { return scripts.hashCode(); } @Override public String toString() { return "ScriptMetadata{" + "scripts=" + scripts + '}'; } }
ScriptMetadataDiff
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationDataExtractor.java
{ "start": 880, "end": 910 }
class ____ NOT thread-safe. */
is
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/retention/MlDataRemoverTests.java
{ "start": 466, "end": 1267 }
class ____ extends ESTestCase { public void testStringOrNull() { MlDataRemover remover = (requestsPerSecond, listener, isTimedOutSupplier) -> {}; SearchHitBuilder hitBuilder = new SearchHitBuilder(0); assertNull(remover.stringFieldValueOrNull(hitBuilder.build(), "missing")); hitBuilder = new SearchHitBuilder(0); hitBuilder.addField("not_a_string", Collections.singletonList(new Date())); assertNull(remover.stringFieldValueOrNull(hitBuilder.build(), "not_a_string")); hitBuilder = new SearchHitBuilder(0); hitBuilder.addField("string_field", Collections.singletonList("actual_string_value")); assertEquals("actual_string_value", remover.stringFieldValueOrNull(hitBuilder.build(), "string_field")); } }
MlDataRemoverTests
java
quarkusio__quarkus
extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/Place.java
{ "start": 72, "end": 1177 }
class ____ { public static final Place crussol = new Place("chateau de Crussol", 4); public static final Place grignan = new Place("chateau de Grignan", 3); public static final Place suze = new Place("chateau de Suze La Rousse", 2); public static final Place adhemar = new Place("chateau des Adhemar", 1); public String name; public int rating; public Place(String name, int rating) { this.name = name; this.rating = rating; } public Place() { // Used by the mapper. } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Place place = (Place) o; return rating == place.rating && Objects.equals(name, place.name); } @Override public int hashCode() { return Objects.hash(name, rating); } @Override public String toString() { return "Place{" + "name='" + name + '\'' + ", rating=" + rating + '}'; } }
Place
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/histogram/HistogramPercentileEvaluator.java
{ "start": 1291, "end": 4782 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(HistogramPercentileEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator value; private final EvalOperator.ExpressionEvaluator percentile; private final DriverContext driverContext; private Warnings warnings; public HistogramPercentileEvaluator(Source source, EvalOperator.ExpressionEvaluator value, EvalOperator.ExpressionEvaluator percentile, DriverContext driverContext) { this.source = source; this.value = value; this.percentile = percentile; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (ExponentialHistogramBlock valueBlock = (ExponentialHistogramBlock) value.eval(page)) { try (DoubleBlock percentileBlock = (DoubleBlock) percentile.eval(page)) { return eval(page.getPositionCount(), valueBlock, percentileBlock); } } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += value.baseRamBytesUsed(); baseRamBytesUsed += percentile.baseRamBytesUsed(); return baseRamBytesUsed; } public DoubleBlock eval(int positionCount, ExponentialHistogramBlock valueBlock, DoubleBlock percentileBlock) { try(DoubleBlock.Builder result = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) { ExponentialHistogramScratch valueScratch = new ExponentialHistogramScratch(); position: for (int p = 0; p < positionCount; p++) { switch (valueBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } switch (percentileBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } ExponentialHistogram value = valueBlock.getExponentialHistogram(valueBlock.getFirstValueIndex(p), valueScratch); double percentile = percentileBlock.getDouble(percentileBlock.getFirstValueIndex(p)); try { HistogramPercentile.process(result, value, percentile); } catch (ArithmeticException e) { warnings().registerException(e); result.appendNull(); } } return result.build(); } } @Override public String toString() { return "HistogramPercentileEvaluator[" + "value=" + value + ", percentile=" + percentile + "]"; } @Override public void close() { Releasables.closeExpectNoException(value, percentile); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
HistogramPercentileEvaluator
java
micronaut-projects__micronaut-core
discovery-core/src/main/java/io/micronaut/discovery/config/ConfigDiscoveryConfiguration.java
{ "start": 729, "end": 841 }
class ____ common configuration discovery settings. * * @author graemerocher * @since 1.0 */ public abstract
for
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/deployment/AbstractVerticleTest.java
{ "start": 1172, "end": 1404 }
class ____ extends AbstractVerticle { public void start() { } public String getDeploymentID() { return deploymentID(); } public JsonObject getConfig() { return config(); } } }
MyAbstractVerticle
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/utils/SqlValidatorUtils.java
{ "start": 2314, "end": 10407 }
class ____ { public static void adjustTypeForArrayConstructor( RelDataType componentType, SqlOperatorBinding opBinding) { if (opBinding instanceof SqlCallBinding) { adjustTypeForMultisetConstructor( componentType, componentType, (SqlCallBinding) opBinding); } } public static void adjustTypeForMapConstructor( Pair<RelDataType, RelDataType> componentType, SqlOperatorBinding opBinding) { if (opBinding instanceof SqlCallBinding) { adjustTypeForMultisetConstructor( componentType.getKey(), componentType.getValue(), (SqlCallBinding) opBinding); } } public static boolean throwValidationSignatureErrorOrReturnFalse( SqlCallBinding callBinding, boolean throwOnFailure) { if (throwOnFailure) { throw callBinding.newValidationSignatureError(); } else { return false; } } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public static boolean throwExceptionOrReturnFalse( Optional<RuntimeException> e, boolean throwOnFailure) { if (e.isPresent()) { if (throwOnFailure) { throw e.get(); } else { return false; } } else { return true; } } /** * Checks whether the heading operands are in the form {@code (ROW, DESCRIPTOR, DESCRIPTOR ..., * other params)}, returning whether successful, and throwing if any columns are not found. * * @param callBinding The call binding * @param descriptorLocations position of the descriptor operands * @return true if validation passes; throws if any columns are not found */ public static boolean checkTableAndDescriptorOperands( SqlCallBinding callBinding, Integer... descriptorLocations) { final SqlNode operand0 = callBinding.operand(0); final SqlValidator validator = callBinding.getValidator(); final RelDataType type = validator.getValidatedNodeType(operand0); if (type.getSqlTypeName() != SqlTypeName.ROW) { return false; } for (Integer location : descriptorLocations) { final SqlNode operand = callBinding.operand(location); if (operand.getKind() != SqlKind.DESCRIPTOR) { return false; } validateColumnNames( validator, type.getFieldNames(), ((SqlCall) operand).getOperandList()); } return true; } private static void validateColumnNames( SqlValidator validator, List<String> fieldNames, List<SqlNode> columnNames) { final SqlNameMatcher matcher = validator.getCatalogReader().nameMatcher(); for (SqlNode columnName : columnNames) { SqlIdentifier columnIdentifier = (SqlIdentifier) columnName; if (!columnIdentifier.isSimple()) { throw SqlUtil.newContextException( columnName.getParserPosition(), RESOURCE.aliasMustBeSimpleIdentifier()); } final String name = columnIdentifier.getSimple(); if (matcher.indexOf(fieldNames, name) < 0) { throw SqlUtil.newContextException( columnName.getParserPosition(), RESOURCE.unknownIdentifier(name)); } } } /** * When the element element does not equal with the component type, making explicit casting. * * @param evenType derived type for element with even index * @param oddType derived type for element with odd index * @param sqlCallBinding description of call */ private static void adjustTypeForMultisetConstructor( RelDataType evenType, RelDataType oddType, SqlCallBinding sqlCallBinding) { SqlCall call = sqlCallBinding.getCall(); List<RelDataType> operandTypes = sqlCallBinding.collectOperandTypes(); List<SqlNode> operands = call.getOperandList(); RelDataType elementType; for (int i = 0; i < operands.size(); i++) { if (i % 2 == 0) { elementType = evenType; } else { elementType = oddType; } if (operandTypes.get(i).equalsSansFieldNames(elementType)) { continue; } call.setOperand(i, castTo(operands.get(i), elementType)); } } /** * Make output field names unique from input field names by appending index. For example, Input * has field names {@code a, b, c} and output has field names {@code b, c, d}. After calling * this function, new output field names will be {@code b0, c0, d}. * * <p>We assume that input fields in the input parameter are uniquely named, just as the output * fields in the output parameter are. * * @param input Input fields * @param output Output fields * @return output fields with unique names. */ public static List<RelDataTypeField> makeOutputUnique( List<RelDataTypeField> input, List<RelDataTypeField> output) { final Set<String> uniqueNames = new HashSet<>(); for (RelDataTypeField field : input) { uniqueNames.add(field.getName()); } List<RelDataTypeField> result = new ArrayList<>(); for (RelDataTypeField field : output) { String fieldName = field.getName(); int count = 0; String candidate = fieldName; while (uniqueNames.contains(candidate)) { candidate = fieldName + count; count++; } uniqueNames.add(candidate); result.add(new RelDataTypeFieldImpl(candidate, field.getIndex(), field.getType())); } return result; } public static Either<String, RuntimeException> reduceLiteralToString( SqlNode operand, SqlValidator validator) { if (operand instanceof SqlCharStringLiteral) { return Either.Left( ((SqlCharStringLiteral) operand).getValueAs(NlsString.class).getValue()); } else if (operand.getKind() == SqlKind.CAST) { // CAST(CAST('v' AS STRING) AS STRING) SqlCall call = (SqlCall) operand; SqlDataTypeSpec dataType = call.operand(1); if (!toLogicalType(dataType.deriveType(validator)).is(CHARACTER_STRING)) { return Either.Right( new ValidationException("Don't support to cast value to non-string type.")); } SqlNode operand0 = call.operand(0); if (operand0 instanceof SqlCharStringLiteral) { return Either.Left( ((SqlCharStringLiteral) operand0).getValueAs(NlsString.class).getValue()); } else { return Either.Right( new ValidationException( String.format( "Unsupported expression %s is in runtime config at position %s. Currently, " + "runtime config should be be a MAP of string literals.", operand, operand.getParserPosition()))); } } else { return Either.Right( new ValidationException( String.format( "Unsupported expression %s is in runtime config at position %s. Currently, " + "runtime config should be be a MAP of string literals.", operand, operand.getParserPosition()))); } } private static SqlNode castTo(SqlNode node, RelDataType type) { return SqlStdOperatorTable.CAST.createCall( SqlParserPos.ZERO, node, SqlTypeUtil.convertTypeToSpec(type).withNullable(type.isNullable())); } }
SqlValidatorUtils
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ModifiedButNotUsedTest.java
{ "start": 6745, "end": 7940 }
class ____ { static void foo() { // BUG: Diagnostic contains: TestProtoMessage.Builder proto = TestProtoMessage.newBuilder(); proto.setMessage(TestFieldProtoMessage.newBuilder()); TestProtoMessage.Builder proto2 = // BUG: Diagnostic contains: TestProtoMessage.newBuilder().setMessage(TestFieldProtoMessage.newBuilder()); TestProtoMessage.Builder proto3 = // BUG: Diagnostic contains: TestProtoMessage.getDefaultInstance().toBuilder().clearMessage(); TestProtoMessage.Builder proto4 = // BUG: Diagnostic contains: TestProtoMessage.getDefaultInstance().toBuilder().clear(); } } """) .doTest(); } @Test public void protoSideEffects() { refactoringHelper .addInputLines( "Test.java", """ import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage; import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;
Test
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java
{ "start": 1059, "end": 7139 }
class ____ { @Test void testNewInstance() { HelloServiceImpl0 instance = (HelloServiceImpl0) ClassUtils.newInstance(HelloServiceImpl0.class.getName()); Assertions.assertEquals("Hello world!", instance.sayHello()); } @Test void testNewInstance0() { Assertions.assertThrows( IllegalStateException.class, () -> ClassUtils.newInstance(PrivateHelloServiceImpl.class.getName())); } @Test void testNewInstance1() { Assertions.assertThrows( IllegalStateException.class, () -> ClassUtils.newInstance( "org.apache.dubbo.common.compiler.support.internal.HelloServiceInternalImpl")); } @Test void testNewInstance2() { Assertions.assertThrows( IllegalStateException.class, () -> ClassUtils.newInstance("org.apache.dubbo.common.compiler.support.internal.NotExistsImpl")); } @Test void testForName() { ClassUtils.forName(new String[] {"org.apache.dubbo.common.compiler.support"}, "HelloServiceImpl0"); } @Test void testForName1() { Assertions.assertThrows( IllegalStateException.class, () -> ClassUtils.forName( new String[] {"org.apache.dubbo.common.compiler.support"}, "HelloServiceImplXX")); } @Test void testForName2() { Assertions.assertEquals(boolean.class, ClassUtils.forName("boolean")); Assertions.assertEquals(byte.class, ClassUtils.forName("byte")); Assertions.assertEquals(char.class, ClassUtils.forName("char")); Assertions.assertEquals(short.class, ClassUtils.forName("short")); Assertions.assertEquals(int.class, ClassUtils.forName("int")); Assertions.assertEquals(long.class, ClassUtils.forName("long")); Assertions.assertEquals(float.class, ClassUtils.forName("float")); Assertions.assertEquals(double.class, ClassUtils.forName("double")); Assertions.assertEquals(boolean[].class, ClassUtils.forName("boolean[]")); Assertions.assertEquals(byte[].class, ClassUtils.forName("byte[]")); Assertions.assertEquals(char[].class, ClassUtils.forName("char[]")); Assertions.assertEquals(short[].class, ClassUtils.forName("short[]")); Assertions.assertEquals(int[].class, ClassUtils.forName("int[]")); Assertions.assertEquals(long[].class, ClassUtils.forName("long[]")); Assertions.assertEquals(float[].class, ClassUtils.forName("float[]")); Assertions.assertEquals(double[].class, ClassUtils.forName("double[]")); } @Test void testGetBoxedClass() { Assertions.assertEquals(Boolean.class, ClassUtils.getBoxedClass(boolean.class)); Assertions.assertEquals(Character.class, ClassUtils.getBoxedClass(char.class)); Assertions.assertEquals(Byte.class, ClassUtils.getBoxedClass(byte.class)); Assertions.assertEquals(Short.class, ClassUtils.getBoxedClass(short.class)); Assertions.assertEquals(Integer.class, ClassUtils.getBoxedClass(int.class)); Assertions.assertEquals(Long.class, ClassUtils.getBoxedClass(long.class)); Assertions.assertEquals(Float.class, ClassUtils.getBoxedClass(float.class)); Assertions.assertEquals(Double.class, ClassUtils.getBoxedClass(double.class)); Assertions.assertEquals(ClassUtilsTest.class, ClassUtils.getBoxedClass(ClassUtilsTest.class)); } @Test void testBoxedAndUnboxed() { Assertions.assertEquals(Boolean.valueOf(true), ClassUtils.boxed(true)); Assertions.assertEquals(Character.valueOf('0'), ClassUtils.boxed('0')); Assertions.assertEquals(Byte.valueOf((byte) 0), ClassUtils.boxed((byte) 0)); Assertions.assertEquals(Short.valueOf((short) 0), ClassUtils.boxed((short) 0)); Assertions.assertEquals(Integer.valueOf((int) 0), ClassUtils.boxed((int) 0)); Assertions.assertEquals(Long.valueOf((long) 0), ClassUtils.boxed((long) 0)); Assertions.assertEquals(Float.valueOf((float) 0), ClassUtils.boxed((float) 0)); Assertions.assertEquals(Double.valueOf((double) 0), ClassUtils.boxed((double) 0)); Assertions.assertTrue(ClassUtils.unboxed(Boolean.valueOf(true))); Assertions.assertEquals('0', ClassUtils.unboxed(Character.valueOf('0'))); Assertions.assertEquals((byte) 0, ClassUtils.unboxed(Byte.valueOf((byte) 0))); Assertions.assertEquals((short) 0, ClassUtils.unboxed(Short.valueOf((short) 0))); Assertions.assertEquals(0, ClassUtils.unboxed(Integer.valueOf((int) 0))); Assertions.assertEquals((long) 0, ClassUtils.unboxed(Long.valueOf((long) 0))); // Assertions.assertEquals((float) 0, ClassUtils.unboxed(Float.valueOf((float) 0)), ((float) 0)); // Assertions.assertEquals((double) 0, ClassUtils.unboxed(Double.valueOf((double) 0)), ((double) 0)); } @Test void testGetSize() { Assertions.assertEquals(0, ClassUtils.getSize(null)); List<Integer> list = new ArrayList<>(); list.add(1); Assertions.assertEquals(1, ClassUtils.getSize(list)); Map map = new HashMap(); map.put(1, 1); Assertions.assertEquals(1, ClassUtils.getSize(map)); int[] array = new int[1]; Assertions.assertEquals(1, ClassUtils.getSize(array)); Assertions.assertEquals(-1, ClassUtils.getSize(new Object())); } @Test void testToUri() { Assertions.assertThrows(RuntimeException.class, () -> ClassUtils.toURI("#xx_abc#hello")); } @Test void testGetSizeMethod() { Assertions.assertEquals("getLength()", ClassUtils.getSizeMethod(GenericClass3.class)); } @Test void testGetSimpleClassName() { Assertions.assertNull(ClassUtils.getSimpleClassName(null)); Assertions.assertEquals("Map", ClassUtils.getSimpleClassName(Map.class.getName())); Assertions.assertEquals("Map", ClassUtils.getSimpleClassName(Map.class.getSimpleName())); } private
ClassUtilsTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/store/records/SubClusterDeregisterRequest.java
{ "start": 1420, "end": 2705 }
class ____ { @Private @Unstable public static SubClusterDeregisterRequest newInstance( SubClusterId subClusterId, SubClusterState subClusterState) { SubClusterDeregisterRequest registerRequest = Records.newRecord(SubClusterDeregisterRequest.class); registerRequest.setSubClusterId(subClusterId); registerRequest.setState(subClusterState); return registerRequest; } /** * Get the {@link SubClusterId} representing the unique identifier of the * subcluster. * * @return the subcluster identifier */ @Public @Unstable public abstract SubClusterId getSubClusterId(); /** * Set the {@link SubClusterId} representing the unique identifier of the * subcluster. * * @param subClusterId the subcluster identifier */ @Private @Unstable public abstract void setSubClusterId(SubClusterId subClusterId); /** * Get the {@link SubClusterState} of the subcluster. * * @return the state of the subcluster */ @Public @Unstable public abstract SubClusterState getState(); /** * Set the {@link SubClusterState} of the subcluster. * * @param state the state of the subCluster */ @Private @Unstable public abstract void setState(SubClusterState state); }
SubClusterDeregisterRequest
java
spring-projects__spring-security
messaging/src/test/java/org/springframework/security/messaging/context/AuthenticationPrincipalArgumentResolverTests.java
{ "start": 12455, "end": 13337 }
class ____ { public final String property; public CopyUserPrincipal(String property) { this.property = property; } public CopyUserPrincipal(CopyUserPrincipal toCopy) { this.property = toCopy.property; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CopyUserPrincipal other = (CopyUserPrincipal) obj; if (this.property == null) { if (other.property != null) { return false; } } else if (!this.property.equals(other.property)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.property == null) ? 0 : this.property.hashCode()); return result; } } }
CopyUserPrincipal
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/TermsLookup.java
{ "start": 1291, "end": 4986 }
class ____ implements Writeable, ToXContentFragment { private final String index; private final String id; private final String path; private String routing; public TermsLookup(String index, String id, String path) { if (id == null) { throw new IllegalArgumentException("[" + TermsQueryBuilder.NAME + "] query lookup element requires specifying the id."); } if (path == null) { throw new IllegalArgumentException("[" + TermsQueryBuilder.NAME + "] query lookup element requires specifying the path."); } if (index == null) { throw new IllegalArgumentException("[" + TermsQueryBuilder.NAME + "] query lookup element requires specifying the index."); } this.index = index; this.id = id; this.path = path; } /** * Read from a stream. */ public TermsLookup(StreamInput in) throws IOException { if (in.getTransportVersion().before(TransportVersions.V_8_0_0)) { in.readOptionalString(); } id = in.readString(); path = in.readString(); index = in.readString(); routing = in.readOptionalString(); } @Override public void writeTo(StreamOutput out) throws IOException { if (out.getTransportVersion().before(TransportVersions.V_8_0_0)) { out.writeOptionalString(MapperService.SINGLE_MAPPING_NAME); } out.writeString(id); out.writeString(path); out.writeString(index); out.writeOptionalString(routing); } public String index() { return index; } public String id() { return id; } public String path() { return path; } public String routing() { return routing; } public TermsLookup routing(String routing) { this.routing = routing; return this; } private static final ConstructingObjectParser<TermsLookup, Void> PARSER = new ConstructingObjectParser<>("terms_lookup", args -> { String index = (String) args[0]; String id = (String) args[1]; String path = (String) args[2]; return new TermsLookup(index, id, path); }); static { PARSER.declareString(constructorArg(), new ParseField("index")); PARSER.declareString(constructorArg(), new ParseField("id")); PARSER.declareString(constructorArg(), new ParseField("path")); PARSER.declareString(TermsLookup::routing, new ParseField("routing")); } public static TermsLookup parseTermsLookup(XContentParser parser) throws IOException { return PARSER.parse(parser, null); } @Override public String toString() { return index + "/" + id + "/" + path; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field("index", index); builder.field("id", id); builder.field("path", path); if (routing != null) { builder.field("routing", routing); } return builder; } @Override public int hashCode() { return Objects.hash(index, id, path, routing); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } TermsLookup other = (TermsLookup) obj; return Objects.equals(index, other.index) && Objects.equals(id, other.id) && Objects.equals(path, other.path) && Objects.equals(routing, other.routing); } }
TermsLookup
java
square__retrofit
retrofit/src/main/java/retrofit2/OptionalConverterFactory.java
{ "start": 2240, "end": 2630 }
class ____<T> implements Converter<ResponseBody, Optional<T>> { private final Converter<ResponseBody, T> delegate; OptionalConverter(Converter<ResponseBody, T> delegate) { this.delegate = delegate; } @Override public Optional<T> convert(ResponseBody value) throws IOException { return Optional.ofNullable(delegate.convert(value)); } } }
OptionalConverter
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/CxfEndpointBuilderFactory.java
{ "start": 80957, "end": 96523 }
interface ____ extends AdvancedCxfEndpointConsumerBuilder, AdvancedCxfEndpointProducerBuilder { default CxfEndpointBuilder basic() { return (CxfEndpointBuilder) this; } /** * This option controls whether the CXF component, when running in * PAYLOAD mode, will DOM parse the incoming messages into DOM Elements * or keep the payload as a javax.xml.transform.Source object that would * allow streaming in some cases. * * The option is a: <code>java.lang.Boolean</code> type. * * Default: false * Group: advanced * * @param allowStreaming the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder allowStreaming(Boolean allowStreaming) { doSetProperty("allowStreaming", allowStreaming); return this; } /** * This option controls whether the CXF component, when running in * PAYLOAD mode, will DOM parse the incoming messages into DOM Elements * or keep the payload as a javax.xml.transform.Source object that would * allow streaming in some cases. * * The option will be converted to a <code>java.lang.Boolean</code> * type. * * Default: false * Group: advanced * * @param allowStreaming the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder allowStreaming(String allowStreaming) { doSetProperty("allowStreaming", allowStreaming); return this; } /** * To use a custom configured CXF Bus. * * The option is a: <code>org.apache.cxf.Bus</code> type. * * Group: advanced * * @param bus the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder bus(org.apache.cxf.Bus bus) { doSetProperty("bus", bus); return this; } /** * To use a custom configured CXF Bus. * * The option will be converted to a <code>org.apache.cxf.Bus</code> * type. * * Group: advanced * * @param bus the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder bus(String bus) { doSetProperty("bus", bus); return this; } /** * This option is used to set the CXF continuation timeout which could * be used in CxfConsumer by default when the CXF server is using Jetty * or Servlet transport. * * The option is a: <code>long</code> type. * * Default: 30000 * Group: advanced * * @param continuationTimeout the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder continuationTimeout(long continuationTimeout) { doSetProperty("continuationTimeout", continuationTimeout); return this; } /** * This option is used to set the CXF continuation timeout which could * be used in CxfConsumer by default when the CXF server is using Jetty * or Servlet transport. * * The option will be converted to a <code>long</code> type. * * Default: 30000 * Group: advanced * * @param continuationTimeout the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder continuationTimeout(String continuationTimeout) { doSetProperty("continuationTimeout", continuationTimeout); return this; } /** * To use a custom CxfBinding to control the binding between Camel * Message and CXF Message. * * The option is a: * <code>org.apache.camel.component.cxf.common.CxfBinding</code> type. * * Group: advanced * * @param cxfBinding the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder cxfBinding(org.apache.camel.component.cxf.common.CxfBinding cxfBinding) { doSetProperty("cxfBinding", cxfBinding); return this; } /** * To use a custom CxfBinding to control the binding between Camel * Message and CXF Message. * * The option will be converted to a * <code>org.apache.camel.component.cxf.common.CxfBinding</code> type. * * Group: advanced * * @param cxfBinding the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder cxfBinding(String cxfBinding) { doSetProperty("cxfBinding", cxfBinding); return this; } /** * This option could apply the implementation of * org.apache.camel.component.cxf.CxfEndpointConfigurer which supports * to configure the CXF endpoint in programmatic way. User can configure * the CXF server and client by implementing configure{ServerClient} * method of CxfEndpointConfigurer. * * The option is a: * <code>org.apache.camel.component.cxf.jaxws.CxfConfigurer</code> type. * * Group: advanced * * @param cxfConfigurer the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder cxfConfigurer(org.apache.camel.component.cxf.jaxws.CxfConfigurer cxfConfigurer) { doSetProperty("cxfConfigurer", cxfConfigurer); return this; } /** * This option could apply the implementation of * org.apache.camel.component.cxf.CxfEndpointConfigurer which supports * to configure the CXF endpoint in programmatic way. User can configure * the CXF server and client by implementing configure{ServerClient} * method of CxfEndpointConfigurer. * * The option will be converted to a * <code>org.apache.camel.component.cxf.jaxws.CxfConfigurer</code> type. * * Group: advanced * * @param cxfConfigurer the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder cxfConfigurer(String cxfConfigurer) { doSetProperty("cxfConfigurer", cxfConfigurer); return this; } /** * Will set the default bus when CXF endpoint create a bus by itself. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param defaultBus the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder defaultBus(boolean defaultBus) { doSetProperty("defaultBus", defaultBus); return this; } /** * Will set the default bus when CXF endpoint create a bus by itself. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param defaultBus the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder defaultBus(String defaultBus) { doSetProperty("defaultBus", defaultBus); return 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: advanced * * @param headerFilterStrategy the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder 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: advanced * * @param headerFilterStrategy the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder headerFilterStrategy(String headerFilterStrategy) { doSetProperty("headerFilterStrategy", headerFilterStrategy); return this; } /** * Whether to merge protocol headers. If enabled then propagating * headers between Camel and CXF becomes more consistent and similar. * For more details see CAMEL-6393. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param mergeProtocolHeaders the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder mergeProtocolHeaders(boolean mergeProtocolHeaders) { doSetProperty("mergeProtocolHeaders", mergeProtocolHeaders); return this; } /** * Whether to merge protocol headers. If enabled then propagating * headers between Camel and CXF becomes more consistent and similar. * For more details see CAMEL-6393. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param mergeProtocolHeaders the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder mergeProtocolHeaders(String mergeProtocolHeaders) { doSetProperty("mergeProtocolHeaders", mergeProtocolHeaders); return this; } /** * To enable MTOM (attachments). This requires to use POJO or PAYLOAD * data format mode. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param mtomEnabled the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder mtomEnabled(boolean mtomEnabled) { doSetProperty("mtomEnabled", mtomEnabled); return this; } /** * To enable MTOM (attachments). This requires to use POJO or PAYLOAD * data format mode. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param mtomEnabled the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder mtomEnabled(String mtomEnabled) { doSetProperty("mtomEnabled", mtomEnabled); return this; } /** * To set additional CXF options using the key/value pairs from the Map. * For example to turn on stacktraces in SOAP faults, * properties.faultStackTraceEnabled=true. This is a multi-value option * with prefix: properties. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the properties(String, * Object) method to add a value (call the method multiple times to set * more values). * * Group: advanced * * @param key the option key * @param value the option value * @return the dsl builder */ default AdvancedCxfEndpointBuilder properties(String key, Object value) { doSetMultiValueProperty("properties", "properties." + key, value); return this; } /** * To set additional CXF options using the key/value pairs from the Map. * For example to turn on stacktraces in SOAP faults, * properties.faultStackTraceEnabled=true. This is a multi-value option * with prefix: properties. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the properties(String, * Object) method to add a value (call the method multiple times to set * more values). * * Group: advanced * * @param values the values * @return the dsl builder */ default AdvancedCxfEndpointBuilder properties(Map values) { doSetMultiValueProperties("properties", "properties.", values); return this; } /** * Enable schema validation for request and response. Disabled by * default for performance reason. * * The option is a: <code>java.lang.Boolean</code> type. * * Default: false * Group: advanced * * @param schemaValidationEnabled the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder schemaValidationEnabled(Boolean schemaValidationEnabled) { doSetProperty("schemaValidationEnabled", schemaValidationEnabled); return this; } /** * Enable schema validation for request and response. Disabled by * default for performance reason. * * The option will be converted to a <code>java.lang.Boolean</code> * type. * * Default: false * Group: advanced * * @param schemaValidationEnabled the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder schemaValidationEnabled(String schemaValidationEnabled) { doSetProperty("schemaValidationEnabled", schemaValidationEnabled); return this; } /** * Sets whether SOAP message validation should be disabled. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param skipPayloadMessagePartCheck the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder skipPayloadMessagePartCheck(boolean skipPayloadMessagePartCheck) { doSetProperty("skipPayloadMessagePartCheck", skipPayloadMessagePartCheck); return this; } /** * Sets whether SOAP message validation should be disabled. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param skipPayloadMessagePartCheck the value to set * @return the dsl builder */ default AdvancedCxfEndpointBuilder skipPayloadMessagePartCheck(String skipPayloadMessagePartCheck) { doSetProperty("skipPayloadMessagePartCheck", skipPayloadMessagePartCheck); return this; } } public
AdvancedCxfEndpointBuilder
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/SpringApplicationAotProcessorTests.java
{ "start": 6495, "end": 6835 }
class ____ { public static String @Nullable [] argsHolder; public static boolean postRunInvoked; void invoke(String @Nullable [] args, Runnable applicationRun) { argsHolder = args; applicationRun.run(); postRunInvoked = true; } void clean() { argsHolder = null; postRunInvoked = false; } } }
ApplicationInvoker
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/MessageBodyReaderTests.java
{ "start": 2264, "end": 4230 }
class ____ { private final AbstractJsonMessageBodyReader reader; public CommonReaderTests(AbstractJsonMessageBodyReader reader) { this.reader = reader; } void deserializeMissingToken() throws IOException { var stream = new ByteArrayInputStream("{\"model\": \"model\", \"cost\": 2".getBytes(StandardCharsets.UTF_8)); Object widget = new Widget("", 1d); reader.readFrom((Class<Object>) widget.getClass(), null, null, null, null, stream); } void deserializeMissingRequiredProperty() throws IOException { // missing non-nullable property var stream = new ByteArrayInputStream("{\"cost\": 2}".getBytes(StandardCharsets.UTF_8)); Object widget = new Widget("", 1d); reader.readFrom((Class<Object>) widget.getClass(), null, null, null, null, stream); } void deserializeMissingReferenceProperty() throws IOException { var json = "{\n" + " \"id\" : 1,\n" + " \"name\" : \"Learn HTML\",\n" + " \"owner\" : 1\n" + // unresolved reference to student "}"; var stream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); Object book = new Book(1, null, null); reader.readFrom((Class<Object>) book.getClass(), null, null, null, null, stream); } void deserializeClassWithInvalidDefinition() throws IOException { var json = "{\n" + " \"arg\" : \"Learn HTML\"" + "}"; var stream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); Object invalid = new InvalidDefinition(null); reader.readFrom((Class<Object>) invalid.getClass(), null, null, null, null, stream); } } @Nested @DisplayName("JacksonMessageBodyReader")
CommonReaderTests
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/inject/ast/MethodElement.java
{ "start": 2208, "end": 10389 }
class ____. * * @return The method annotation metadata * @since 4.0.0 */ @NonNull default MutableAnnotationMetadataDelegate<AnnotationMetadata> getMethodAnnotationMetadata() { return new MutableAnnotationMetadataDelegate<>() { @Override public AnnotationMetadata getAnnotationMetadata() { return MethodElement.this.getAnnotationMetadata(); } }; } /** * @return The return type of the method */ @NonNull ClassElement getReturnType(); /** * @return The type arguments declared on this method. */ default List<? extends GenericPlaceholderElement> getDeclaredTypeVariables() { return Collections.emptyList(); } /** * The type arguments for this method element. * The type arguments should include the type arguments added to the method plus the type arguments of the declaring class. * * @return The type arguments for this method element * @since 4.0.0 */ @Experimental @NonNull default Map<String, ClassElement> getTypeArguments() { Map<String, ClassElement> typeArguments = getDeclaringType().getTypeArguments(); Map<String, ClassElement> methodTypeArguments = getDeclaredTypeArguments(); Map<String, ClassElement> newTypeArguments = CollectionUtils.newLinkedHashMap(typeArguments.size() + methodTypeArguments.size()); newTypeArguments.putAll(typeArguments); newTypeArguments.putAll(methodTypeArguments); return newTypeArguments; } /** * The declared type arguments for this method element. * * @return The declared type arguments for this method element * @since 4.0.0 */ @Experimental @NonNull default Map<String, ClassElement> getDeclaredTypeArguments() { return Collections.emptyMap(); } /** * <p>Returns the receiver type of this executable, or empty if the method has no receiver type.</p> * * <p>A MethodElement which is an instance method, or a constructor of an inner class, has a receiver type derived from the declaring type.</p> * * <p>A MethodElement which is a static method, or a constructor of a non-inner class, or an initializer (static or instance), has no receiver type.</p> * * @return The receiver type for the method if one exists. * @since 3.1.0 */ default Optional<ClassElement> getReceiverType() { return Optional.empty(); } /** * Returns the types declared in the {@code throws} declaration of a method. * * @return The {@code throws} types, if any. Never {@code null}. * @since 3.1.0 */ @NonNull default ClassElement[] getThrownTypes() { return ClassElement.ZERO_CLASS_ELEMENTS; } /** * @return The method parameters */ @NonNull ParameterElement[] getParameters(); /** * Takes this method element and transforms into a new method element with the given parameters appended to the existing parameters. * * @param newParameters The new parameters * @return A new method element * @since 2.3.0 */ @NonNull default MethodElement withNewParameters(@NonNull ParameterElement... newParameters) { return withParameters(ArrayUtils.concat(getParameters(), newParameters)); } /** * Takes this method element and transforms into a new method element with the given parameters. * * @param newParameters The new parameters * @return A new method element * @since 4.0.0 */ @NonNull MethodElement withParameters(@NonNull ParameterElement... newParameters); /** * Returns a new method with a new owning type. * * @param owningType The owning type. * @return A new method element * @since 4.0.0 */ @NonNull default MethodElement withNewOwningType(@NonNull ClassElement owningType) { throw new IllegalStateException("Not supported to change the owning type!"); } /** * This method adds an associated bean using this method element as the originating element. * * <p>Note that this method can only be called on classes being directly compiled by Micronaut. If the ClassElement is * loaded from pre-compiled code an {@link UnsupportedOperationException} will be thrown.</p> * * @param type The type of the bean * @return A bean builder */ default @NonNull BeanElementBuilder addAssociatedBean(@NonNull ClassElement type) { throw new UnsupportedOperationException("Only classes being processed from source code can define associated beans"); } /** * If {@link #isSuspend()} returns true this method exposes the continuation parameter in addition to the other parameters of the method. * * @return The suspend parameters * @since 2.3.0 */ default @NonNull ParameterElement[] getSuspendParameters() { return getParameters(); } /** * Returns true if the method has parameters. * * @return True if it does */ default boolean hasParameters() { return getParameters().length > 0; } /** * Is the method a Kotlin suspend function. * * @return True if it is. * @since 2.3.0 */ default boolean isSuspend() { return false; } /** * Is the method a default method on an interfaces. * * @return True if it is. * @since 2.3.0 */ default boolean isDefault() { return false; } /** * If method has varargs parameter. * @return True if it does * @since 4.0.0 */ default boolean isVarArgs() { return false; } /** * The generic return type of the method. * * @return The return type of the method * @since 1.1.1 */ default @NonNull ClassElement getGenericReturnType() { return getReturnType(); } /** * Get the method description. * * @param simple If simple type names are to be used * @return The method description */ @Override default @NonNull String getDescription(boolean simple) { String typeString = simple ? getReturnType().getSimpleName() : getReturnType().getName(); String args = Arrays.stream(getParameters()).map(arg -> simple ? arg.getType().getSimpleName() : arg.getType().getName() + " " + arg.getName()).collect(Collectors.joining(",")); return typeString + " " + getName() + "(" + args + ")"; } /** * Checks if this method element overrides another. * * @param overridden Possible overridden method * @return true if this overrides passed method element * @since 3.1 */ @NextMajorVersion("Review the package-private methods with broken access, those might need to be excluded completely") default boolean overrides(@NonNull MethodElement overridden) { if (equals(overridden) || isStatic() || overridden.isStatic() || isPrivate() || overridden.isPrivate()) { return false; } if (!isSubSignature(overridden)) { return false; } MethodElement newMethod = this; if (newMethod.isAbstract() && !newMethod.isDefault() && (!overridden.isAbstract() || overridden.isDefault())) { return false; } if (isPackagePrivate() && overridden.isPackagePrivate()) { // This is a special case for identical package-private methods from the same package // if the package is changed in the subclass in between; by Java rules those methods aren't overridden // But this kind of non-overridden method in the subclass CANNOT be called by the reflection, // it will always call the subclass method! // In Micronaut 4 we mark this method as overridden, in the future we might want to exclude them completely if (!getDeclaringType().getPackageName().equals(overridden.getDeclaringType().getPackageName())) { return false; } } // Check if a parent
annotations
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/TableEnvironmentImpl.java
{ "start": 68320, "end": 69799 }
class ____ extends ApiExpressionDefaultVisitor<Void> { void check(Object... arguments) { final TableReferenceChecker checker = new TableReferenceChecker(); Arrays.stream(arguments) .filter(Expression.class::isInstance) .map(Expression.class::cast) .forEach(e -> e.accept(checker)); } @Override protected Void defaultMethod(Expression expression) { expression.getChildren().forEach(child -> child.accept(this)); return null; } @Override public Void visit(TableReferenceExpression tableRef) { super.visit(tableRef); if (tableRef.getTableEnvironment() != null && tableRef.getTableEnvironment() != TableEnvironmentImpl.this) { throw new ValidationException( "All table references must use the same TableEnvironment."); } return null; } @Override public Void visit(ModelReferenceExpression modelRef) { super.visit(modelRef); if (modelRef.getTableEnvironment() != null && modelRef.getTableEnvironment() != TableEnvironmentImpl.this) { throw new ValidationException( "All model references must use the same TableEnvironment."); } return null; } } }
TableReferenceChecker
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/io/InspectedContent.java
{ "start": 1248, "end": 3746 }
class ____ implements Content { static final int MEMORY_LIMIT = 4 * 1024 + 3; private final int size; private final Object content; InspectedContent(int size, Object content) { this.size = size; this.content = content; } @Override public int size() { return this.size; } @Override public void writeTo(OutputStream outputStream) throws IOException { if (this.content instanceof byte[] bytes) { FileCopyUtils.copy(bytes, outputStream); } else if (this.content instanceof File file) { InputStream inputStream = new FileInputStream(file); FileCopyUtils.copy(inputStream, outputStream); } else { throw new IllegalStateException("Unknown content type"); } } /** * Factory method to create an {@link InspectedContent} instance from a source input * stream. * @param inputStream the content input stream * @param inspectors any inspectors to apply * @return a new inspected content instance * @throws IOException on IO error */ public static InspectedContent of(InputStream inputStream, Inspector... inspectors) throws IOException { Assert.notNull(inputStream, "'inputStream' must not be null"); return of((outputStream) -> FileCopyUtils.copy(inputStream, outputStream), inspectors); } /** * Factory method to create an {@link InspectedContent} instance from source content. * @param content the content * @param inspectors any inspectors to apply * @return a new inspected content instance * @throws IOException on IO error */ public static InspectedContent of(Content content, Inspector... inspectors) throws IOException { Assert.notNull(content, "'content' must not be null"); return of(content::writeTo, inspectors); } /** * Factory method to create an {@link InspectedContent} instance from a source write * method. * @param writer a consumer representing the write method * @param inspectors any inspectors to apply * @return a new inspected content instance * @throws IOException on IO error */ public static InspectedContent of(IOConsumer<OutputStream> writer, Inspector... inspectors) throws IOException { Assert.notNull(writer, "'writer' must not be null"); InspectingOutputStream outputStream = new InspectingOutputStream(inspectors); try (outputStream) { writer.accept(outputStream); } return new InspectedContent(outputStream.getSize(), outputStream.getContent()); } /** * Interface that can be used to inspect content as it is initially read. */ public
InspectedContent
java
apache__camel
components/camel-pgevent/src/main/java/org/apache/camel/component/pgevent/PgEventEndpoint.java
{ "start": 4460, "end": 10485 }
class ____ classResolver = getCamelContext().getClassResolver(); classResolver.resolveMandatoryClass(PGDriver.class.getName(), PgEventComponent.class.getClassLoader()); conn = (PGConnection) DriverManager.getConnection( "jdbc:pgsql://" + this.getHost() + ":" + this.getPort() + "/" + this.getDatabase(), this.getUser(), this.getPass()); } return conn; } /** * Parse the provided URI and extract available parameters * * @throws IllegalArgumentException if there is an error in the parameters */ protected final void parseUri() throws IllegalArgumentException { LOG.debug("URI: {}", uri); if (uri.matches(FORMAT1)) { LOG.trace("FORMAT1"); String[] parts = uri.replaceFirst(FORMAT1, "$1:$2:$3:$4").split(":"); host = parts[0]; port = Integer.parseInt(parts[1]); database = parts[2]; channel = parts[3]; } else if (uri.matches(FORMAT2)) { LOG.trace("FORMAT2"); String[] parts = uri.replaceFirst(FORMAT2, "$1:$2:$3").split(":"); host = parts[0]; port = 5432; database = parts[1]; channel = parts[2]; } else if (uri.matches(FORMAT3)) { LOG.trace("FORMAT3"); String[] parts = uri.replaceFirst(FORMAT3, "$1:$2").split(":"); host = "localhost"; port = 5432; database = parts[0]; channel = parts[1]; } else if (uri.matches(FORMAT4)) { LOG.trace("FORMAT4"); String[] parts = uri.replaceFirst(FORMAT4, "$1:$2").split(":"); database = parts[0]; channel = parts[1]; } else { throw new IllegalArgumentException("The provided URL does not match the acceptable patterns."); } } @Override public Producer createProducer() throws Exception { validateInputs(); return new PgEventProducer(this); } private void validateInputs() throws IllegalArgumentException { if (getChannel() == null || getChannel().isEmpty()) { throw new IllegalArgumentException("A required parameter was not set when creating this Endpoint (channel)"); } if (datasource == null && user == null) { throw new IllegalArgumentException( "A required parameter was " + "not set when creating this Endpoint (pgUser or pgDataSource)"); } } @Override public Consumer createConsumer(Processor processor) throws Exception { validateInputs(); PgEventConsumer consumer = new PgEventConsumer(this, processor); configureConsumer(consumer); return consumer; } ExecutorService createWorkerPool(Object source) { return getCamelContext().getExecutorServiceManager().newThreadPool(source, "PgEventConsumer[" + channel + "]", workerPoolCoreSize, workerPoolMaxSize); } public String getHost() { return host; } /** * To connect using hostname and port to the database. */ public void setHost(String host) { this.host = host; } public Integer getPort() { return port; } /** * To connect using hostname and port to the database. */ public void setPort(Integer port) { this.port = port; } public String getDatabase() { return database; } /** * The database name. The database name can take any characters because it is sent as a quoted identifier. It is * part of the endpoint URI, so diacritical marks and non-Latin letters have to be URL encoded. */ public void setDatabase(String database) { this.database = database; } public String getChannel() { return channel; } /** * The channel name */ public void setChannel(String channel) { this.channel = channel; } public String getUser() { return user; } /** * Username for login */ public void setUser(String user) { this.user = user; } public String getPass() { return pass; } /** * Password for login */ public void setPass(String pass) { this.pass = pass; } public DataSource getDatasource() { return datasource; } /** * To connect using the given {@link javax.sql.DataSource} instead of using hostname and port. */ public void setDatasource(DataSource datasource) { this.datasource = datasource; } public int getReconnectDelay() { return reconnectDelay; } /** * When the consumer unexpected lose connection to the database, then this specifies the interval (millis) between * re-connection attempts to establish a new connection. */ public void setReconnectDelay(int reconnectDelay) { this.reconnectDelay = reconnectDelay; } public ExecutorService getWorkerPool() { return workerPool; } /** * To use a custom worker pool for processing the events from the database. */ public void setWorkerPool(ExecutorService workerPool) { this.workerPool = workerPool; } public int getWorkerPoolCoreSize() { return workerPoolCoreSize; } /** * Number of core threads in the worker pool for processing the events from the database. */ public void setWorkerPoolCoreSize(int workerPoolCoreSize) { this.workerPoolCoreSize = workerPoolCoreSize; } public int getWorkerPoolMaxSize() { return workerPoolMaxSize; } /** * Maximum number of threads in the worker pool for processing the events from the database. */ public void setWorkerPoolMaxSize(int workerPoolMaxSize) { this.workerPoolMaxSize = workerPoolMaxSize; } }
ClassResolver
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/BootstrapUtilsTests.java
{ "start": 8277, "end": 8369 }
class ____ {} // Invalid @BootWithBar @BootWithFoo static
EmptyBootstrapWithAnnotationClass
java
apache__camel
components/camel-netty/src/test/java/org/apache/camel/component/netty/NettySSLConsumerClientModeTest.java
{ "start": 4430, "end": 5334 }
class ____ { private int port; private ServerBootstrap bootstrap; private Channel channel; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; MyServer(int port) { this.port = port; } public void start() throws Exception { bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ServerInitializer()); ChannelFuture cf = bootstrap.bind(port).sync(); channel = cf.channel(); } public void shutdown() { channel.disconnect(); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } private static
MyServer
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/ContainerRequestContextTest.java
{ "start": 648, "end": 1236 }
class ____ { @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { return ShrinkWrap.create(JavaArchive.class) .addClass(HelloResource.class); } }); @Test public void helloWorldTest() { RestAssured.get("/hello") .then() .body(equalTo("hello foo")); } @Path("/hello") public static
ContainerRequestContextTest
java
apache__rocketmq
controller/src/main/java/org/apache/rocketmq/controller/elect/impl/DefaultElectPolicy.java
{ "start": 1236, "end": 5821 }
class ____ implements ElectPolicy { // <clusterName, brokerName, brokerAddr>, Used to judge whether a broker // has preliminary qualification to be selected as master private BrokerValidPredicate validPredicate; // <clusterName, brokerName, brokerAddr, BrokerLiveInfo>, Used to obtain the BrokerLiveInfo information of a broker private BrokerLiveInfoGetter brokerLiveInfoGetter; // Sort in descending order according to<epoch, offset>, and sort in ascending order according to priority private final Comparator<BrokerLiveInfo> comparator = (o1, o2) -> { if (o1.getEpoch() == o2.getEpoch()) { return o1.getMaxOffset() == o2.getMaxOffset() ? o1.getElectionPriority() - o2.getElectionPriority() : (int) (o2.getMaxOffset() - o1.getMaxOffset()); } else { return o2.getEpoch() - o1.getEpoch(); } }; public DefaultElectPolicy(BrokerValidPredicate validPredicate, BrokerLiveInfoGetter brokerLiveInfoGetter) { this.validPredicate = validPredicate; this.brokerLiveInfoGetter = brokerLiveInfoGetter; } public DefaultElectPolicy() { } /** * We will try to select a new master from syncStateBrokers and allReplicaBrokers in turn. * The strategies are as follows: * - Filter alive brokers by 'validPredicate'. * - Check whether the old master is still valid. * - If preferBrokerAddr is not empty and valid, select it as master. * - Otherwise, we will sort the array of 'brokerLiveInfo' according to (epoch, offset, electionPriority), and select the best candidate as the new master. * * @param clusterName the brokerGroup belongs * @param syncStateBrokers all broker replicas in syncStateSet * @param allReplicaBrokers all broker replicas * @param oldMaster old master's broker id * @param preferBrokerId the broker id prefer to be elected * @return master elected by our own policy */ @Override public Long elect(String clusterName, String brokerName, Set<Long> syncStateBrokers, Set<Long> allReplicaBrokers, Long oldMaster, Long preferBrokerId) { Long newMaster = null; // try to elect in syncStateBrokers if (syncStateBrokers != null) { newMaster = tryElect(clusterName, brokerName, syncStateBrokers, oldMaster, preferBrokerId); } if (newMaster != null) { return newMaster; } // try to elect in all allReplicaBrokers if (allReplicaBrokers != null) { newMaster = tryElect(clusterName, brokerName, allReplicaBrokers, oldMaster, preferBrokerId); } return newMaster; } private Long tryElect(String clusterName, String brokerName, Set<Long> brokers, Long oldMaster, Long preferBrokerId) { if (this.validPredicate != null) { brokers = brokers.stream().filter(brokerAddr -> this.validPredicate.check(clusterName, brokerName, brokerAddr)).collect(Collectors.toSet()); } if (!brokers.isEmpty()) { // if old master is still valid, and preferBrokerAddr is blank or is equals to oldMaster if (brokers.contains(oldMaster) && (preferBrokerId == null || preferBrokerId.equals(oldMaster))) { return oldMaster; } // if preferBrokerAddr is valid, we choose it, otherwise we choose nothing if (preferBrokerId != null) { return brokers.contains(preferBrokerId) ? preferBrokerId : null; } if (this.brokerLiveInfoGetter != null) { // sort brokerLiveInfos by (epoch,maxOffset) TreeSet<BrokerLiveInfo> brokerLiveInfos = new TreeSet<>(this.comparator); brokers.forEach(brokerAddr -> brokerLiveInfos.add(this.brokerLiveInfoGetter.get(clusterName, brokerName, brokerAddr))); if (brokerLiveInfos.size() >= 1) { return brokerLiveInfos.first().getBrokerId(); } } // elect random return brokers.iterator().next(); } return null; } public void setBrokerLiveInfoGetter(BrokerLiveInfoGetter brokerLiveInfoGetter) { this.brokerLiveInfoGetter = brokerLiveInfoGetter; } public void setValidPredicate(BrokerValidPredicate validPredicate) { this.validPredicate = validPredicate; } public BrokerLiveInfoGetter getBrokerLiveInfoGetter() { return brokerLiveInfoGetter; } }
DefaultElectPolicy
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/java8stream/erroneous/ErroneousStreamToNonStreamMapper.java
{ "start": 280, "end": 447 }
interface ____ { Integer stringStreamToInteger(Stream<String> strings); Stream<String> integerToStringStream(Integer integer); }
ErroneousStreamToNonStreamMapper
java
quarkusio__quarkus
extensions/container-image/deployment/src/test/java/io/quarkus/container/image/deployment/ContainerImageConfigEffectiveGroupTest.java
{ "start": 174, "end": 1907 }
class ____ { public static final String USER_NAME_SYSTEM_PROPERTY = "user.name"; private final Optional<String> EMPTY = Optional.empty(); @Test void testFromLowercaseUsername() { testWithNewUsername("test", () -> { Optional<String> group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY)); assertEquals(ContainerImageProcessor.getEffectiveGroup(EMPTY, false), Optional.of("test")); }); } @Test void testFromUppercaseUsername() { testWithNewUsername("TEST", () -> { Optional<String> group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY)); assertEquals(ContainerImageProcessor.getEffectiveGroup(EMPTY, false), Optional.of("test")); }); } @Test void testFromSpaceInUsername() { testWithNewUsername("user name", () -> { Optional<String> group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY)); assertEquals(ContainerImageProcessor.getEffectiveGroup(EMPTY, false), Optional.of("user-name")); }); } @Test void testFromOther() { testWithNewUsername("WhateveR", () -> { Optional<String> group = Optional.of("OtheR"); assertEquals(ContainerImageProcessor.getEffectiveGroup(group, false), Optional.of("other")); }); } private void testWithNewUsername(String newUserName, Runnable test) { String previousUsernameValue = System.getProperty(USER_NAME_SYSTEM_PROPERTY); System.setProperty(USER_NAME_SYSTEM_PROPERTY, newUserName); test.run(); System.setProperty(USER_NAME_SYSTEM_PROPERTY, previousUsernameValue); } }
ContainerImageConfigEffectiveGroupTest
java
quarkusio__quarkus
independent-projects/bootstrap/app-model/src/main/java/io/quarkus/paths/SharedArchivePathTree.java
{ "start": 613, "end": 2354 }
class ____ extends ArchivePathTree { // It would probably be better to have a weak hash map based cache, // however as the first iteration it'll already be more efficient than before private static final Map<Path, SharedArchivePathTree> CACHE = new ConcurrentHashMap<>(); /** * Returns an instance of {@link ArchivePathTree} for the {@code path} either from a cache * or creates a new instance for it and puts it in the cache. * * @param path path to an archive * @return instance of {@link ArchivePathTree}, never null */ static ArchivePathTree forPath(Path path) { return CACHE.computeIfAbsent(path, SharedArchivePathTree::new); } /** * Removes an entry for {@code path} from the path tree cache. If the cache * does not contain an entry for the {@code path}, the method will return silently. * * @param path path to remove from the cache */ static void removeFromCache(Path path) { CACHE.remove(path); } private final AtomicInteger openCount = new AtomicInteger(); private volatile SharedOpenArchivePathTree lastOpen; SharedArchivePathTree(Path archive) { super(archive); } @Override public OpenPathTree open() { var lastOpen = this.lastOpen; if (lastOpen != null) { var acquired = lastOpen.acquire(); if (acquired != null) { return acquired; } } try { lastOpen = this.lastOpen = new SharedOpenArchivePathTree(openFs()); } catch (IOException e) { throw new UncheckedIOException(e); } return new CallerOpenPathTree(lastOpen); } private
SharedArchivePathTree
java
alibaba__fastjson
src/test/java/com/alibaba/json/test/tmall/RateSearchItemDO.java
{ "start": 179, "end": 13005 }
class ____ { /** * ����id */ @JSONField(name = "feed_id") private long feedId; /** * ��Ʒid */ @JSONField(name = "item_id") private long aucNumId; /** * ���в���ֵ */ @JSONField(name = "rate") private int rate; /** * �����Ƿ���ͼƬ */ @JSONField(name = "rater_pic") private int raterPic; /** * ������(����id) */ @JSONField(name = "rated_uid") private long ratedUid; /** * ������(���id) */ @JSONField(name = "rater_uid") private long raterUid; /** * ���������dz� */ @JSONField(name = "rated_user_nick") private String ratedUserNick; /** * �������dz� */ @JSONField(name = "rater_user_nick") private String raterUserNick; /** * ����״̬ */ @JSONField(name = "status") private int status; /** * �������� */ @JSONField(name = "feedback") private String feedback; /** * �����Ƿ������� */ @JSONField(name = "validfeedback") private int validfeedback; /** * �ظ� */ @JSONField(name = "reply") private String reply; /** * ҵ������ */ @JSONField(name = "biz_type") private int bizType; /** * �㷨���ֵ */ @JSONField(name = "sort_weight") private int sortWeight; /** * ����ʱ��� */ @JSONField(name = "gmt_create") private long gmtCreateStamp; /** * ���ü��� */ @JSONField(name = "vote_useful") private int voteUseful; /** * �����ֶ� */ @JSONField(name = "attributes") private String attributes; /** * ���Ի��Ĵ�ֱ���� */ @JSONField(name = "details") private String properties; /** * �Ƿ����� */ @JSONField(name = "anony") private int anony; /** * ��Ǽ�¼��Դ */ @JSONField(name = "source") private long source; /** * �������ʱ�� */ @JSONField(name = "gmt_trade_finished") private long gmtTradeFinishedStamp; /** * �����߽��׽�ɫ */ @JSONField(name = "rater_type") private int raterType; /** * ���ۼƷ�״̬ */ @JSONField(name = "validscore") private int validscore; /** * ��Ʒһ����Ŀid */ @JSONField(name = "cate_level1_id") private long rootCatId; /** * ��ƷҶ����Ŀ */ @JSONField(name = "cate_id") private long leafCatId; /** * ������Id * */ @JSONField(name = "mord_id") private long parentTradeId; /** * �Ӷ���Id * */ @JSONField(name = "order_id") private long tradeId; /** * �Ƿ����׷�� */ @JSONField(name = "append") private int append; /** * ׷��״̬ */ @JSONField(name = "append_status") private int appendStatus; /** * ׷������ */ @JSONField(name = "append_feedback") private String appendFeedback; /** * ׷���ظ����� */ @JSONField(name = "append_reply") private String appendReply; /** * ׷��ʱ��� */ @JSONField(name = "append_create") private long appendCreateStamp; /** * ׷���Ƿ����ͼƬ */ @JSONField(name = "append_pic") private int appendPic; /** * ׷����¼id */ @JSONField(name = "append_feed_id") private long appendFeedId; /** * ׷�������ֶ� */ @JSONField(name = "append_attributes") private String appendAttributes; /** * ׷����ֱ�����ֶ� */ @JSONField(name = "append_properties") private String appendProperties; /** * �㷨�����ֵ */ @JSONField(name = "algo_sort") private long algoSort; /** * �۵���־ */ @JSONField(name = "fold_flag") private int foldFlag; /** * �㷨�����ֶ� */ @JSONField(name = "reason") private String reason; /** * �㷨�����ֶ� */ @JSONField(name = "other") private String other; /** * ���ӡ���ǩ */ @JSONField(name = "expression_auc") private String expressionAuc; /** * ���ӡ���ǩ����λ�� */ @JSONField(name = "position") private String position; /** * ���Ի��û���ǩ * */ @JSONField(name = "personalized_tag") private String personalizedTag; /** * ����ͼƬ */ @JSONField(name = "main_pic_json") private String mainPicJson; /** * ׷��ͼƬ */ @JSONField(name = "append_pic_json") private String appendPicJson; /** * ���������Ϣ */ @JSONField(name = "main_component_json") private String mainComponentJson; /** * ׷�������Ϣ */ @JSONField(name = "append_component_json") private String appendComponentJson; /** * �Ƿ�Ϊϵͳ���� */ @JSONField(name = "is_auto") private String auto; public long getFeedId () { return feedId; } public void setFeedId (long feedId) { this.feedId = feedId; } public long getRatedUid () { return ratedUid; } public void setRatedUid (long ratedUid) { this.ratedUid = ratedUid; } public long getRaterUid () { return raterUid; } public void setRaterUid (long raterUid) { this.raterUid = raterUid; } public String getRaterUserNick () { return raterUserNick; } public void setRaterUserNick (String raterUserNick) { this.raterUserNick = raterUserNick; } public String getFeedback () { return feedback; } public void setFeedback (String feedback) { this.feedback = feedback; } public int getRate () { return rate; } public void setRate (int rate) { this.rate = rate; } public int getStatus () { return status; } public void setStatus (int status) { this.status = status; } public String getReply () { return reply; } public void setReply (String reply) { this.reply = reply; } public int getBizType () { return bizType; } public void setBizType (int bizType) { this.bizType = bizType; } public int getSortWeight () { return sortWeight; } public void setSortWeight (int sortWeight) { this.sortWeight = sortWeight; } public int getVoteUseful () { return voteUseful; } public void setVoteUseful (int voteUseful) { this.voteUseful = voteUseful; } public String getAttributes () { return attributes; } public void setAttributes (String attributes) { this.attributes = attributes; } public String getProperties () { return properties; } public void setProperties (String properties) { this.properties = properties; } public int getAppendStatus () { return appendStatus; } public void setAppendStatus (int appendStatus) { this.appendStatus = appendStatus; } public String getAppendFeedback () { return appendFeedback; } public void setAppendFeedback (String appendFeedback) { this.appendFeedback = appendFeedback; } public String getAppendReply () { return appendReply; } public void setAppendReply (String appendReply) { this.appendReply = appendReply; } public long getAppendFeedId () { return appendFeedId; } public void setAppendFeedId (long appendFeedId) { this.appendFeedId = appendFeedId; } public String getAppendAttributes () { return appendAttributes; } public void setAppendAttributes (String appendAttributes) { this.appendAttributes = appendAttributes; } public String getAppendProperties () { return appendProperties; } public void setAppendProperties (String appendProperties) { this.appendProperties = appendProperties; } public int getRaterPic () { return raterPic; } public void setRaterPic (int raterPic) { this.raterPic = raterPic; } public int getValidfeedback () { return validfeedback; } public void setValidfeedback (int validfeedback) { this.validfeedback = validfeedback; } public int getAppendPic () { return appendPic; } public void setAppendPic (int appendPic) { this.appendPic = appendPic; } public long getGmtCreateStamp () { return gmtCreateStamp; } public void setGmtCreateStamp (long gmtCreateStamp) { this.gmtCreateStamp = gmtCreateStamp; } public long getAppendCreateStamp () { return appendCreateStamp; } public void setAppendCreateStamp (long appendCreateStamp) { this.appendCreateStamp = appendCreateStamp; } public int getAppend () { return append; } public void setAppend (int append) { this.append = append; } public boolean haveAppend () { return append == 1; } public String getRatedUserNick () { return ratedUserNick; } public void setRatedUserNick (String ratedUserNick) { this.ratedUserNick = ratedUserNick; } public int getAnony () { return anony; } public void setAnony (int anony) { this.anony = anony; } public long getGmtTradeFinishedStamp () { return gmtTradeFinishedStamp; } public void setGmtTradeFinishedStamp (long gmtTradeFinishedStamp) { this.gmtTradeFinishedStamp = gmtTradeFinishedStamp; } public int getRaterType () { return raterType; } public void setRaterType (int raterType) { this.raterType = raterType; } public int getValidscore () { return validscore; } public void setValidscore (int validscore) { this.validscore = validscore; } public long getAlgoSort () { return algoSort; } public void setAlgoSort (long algoSort) { this.algoSort = algoSort; } public int getFoldFlag () { return foldFlag; } public void setFoldFlag (int foldFlag) { this.foldFlag = foldFlag; } public String getReason () { return reason; } public void setReason (String reason) { this.reason = reason; } public String getOther () { return other; } public void setOther (String other) { this.other = other; } public String getExpressionAuc () { return expressionAuc; } public void setExpressionAuc (String expressionAuc) { this.expressionAuc = expressionAuc; } public String getPosition () { return position; } public void setPosition (String position) { this.position = position; } public long getAucNumId () { return aucNumId; } public void setAucNumId (long aucNumId) { this.aucNumId = aucNumId; } public long getSource () { return source; } public void setSource (long source) { this.source = source; } public long getRootCatId () { return rootCatId; } public void setRootCatId (long rootCatId) { this.rootCatId = rootCatId; } public long getLeafCatId() { return leafCatId; } public void setLeafCatId(long leafCatId) { this.leafCatId = leafCatId; } public String getMainPicJson() { return mainPicJson; } public void setMainPicJson(String mainPicJson) { this.mainPicJson = mainPicJson; } public String getAppendPicJson() { return appendPicJson; } public void setAppendPicJson(String appendPicJson) { this.appendPicJson = appendPicJson; } public String getMainComponentJson() { return mainComponentJson; } public void setMainComponentJson(String mainComponentJson) { this.mainComponentJson = mainComponentJson; } public String getAppendComponentJson() { return appendComponentJson; } public void setAppendComponentJson(String appendComponentJson) { this.appendComponentJson = appendComponentJson; } public String getAuto() { return auto; } public void setAuto(String auto) { this.auto = auto; } public long getParentTradeId() { return parentTradeId; } public void setParentTradeId(long parentTradeId) { this.parentTradeId = parentTradeId; } public long getTradeId() { return tradeId; } public void setTradeId(long tradeId) { this.tradeId = tradeId; } public String getPersonalizedTag() { return personalizedTag; } public void setPersonalizedTag(String personalizedTag) { this.personalizedTag = personalizedTag; } }
RateSearchItemDO
java
apache__kafka
server/src/main/java/org/apache/kafka/server/transaction/AddPartitionsToTxnManager.java
{ "start": 3013, "end": 3384 }
class ____ extends InterBrokerSendThread { public static final String VERIFICATION_FAILURE_RATE_METRIC_NAME = "VerificationFailureRate"; public static final String VERIFICATION_TIME_MS_METRIC_NAME = "VerificationTimeMs"; /** * handles the Partition Response based on the Request Version and the exact operation. */ public
AddPartitionsToTxnManager
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/ExtractionUtils.java
{ "start": 3139, "end": 5236 }
class ____ { // -------------------------------------------------------------------------------------------- // Methods shared across packages // -------------------------------------------------------------------------------------------- /** Collects methods of the given name. */ public static List<Method> collectMethods(Class<?> function, String methodName) { return Arrays.stream(function.getMethods()) .filter(method -> method.getName().equals(methodName)) .sorted(Comparator.comparing(Method::toString)) // for deterministic order .collect(Collectors.toList()); } /** * Checks whether a method/constructor can be called with the given argument classes. This * includes type widening and vararg. {@code null} is a wildcard. * * <p>E.g., {@code (int.class, int.class)} matches {@code f(Object...), f(int, int), f(Integer, * Object)} and so forth. */ public static boolean isInvokable( Autoboxing autoboxing, Executable executable, Class<?>... classes) { final int m = executable.getModifiers(); if (!Modifier.isPublic(m)) { return false; } final int paramCount = executable.getParameterCount(); final int classCount = classes.length; // check for enough classes for each parameter if ((!executable.isVarArgs() && classCount != paramCount) || (executable.isVarArgs() && classCount < paramCount - 1)) { return false; } int currentClass = 0; for (int currentParam = 0; currentParam < paramCount; currentParam++) { final Class<?> param = executable.getParameterTypes()[currentParam]; // last parameter is a vararg that needs to consume remaining classes if (currentParam == paramCount - 1 && executable.isVarArgs()) { final Class<?> paramComponent = executable.getParameterTypes()[currentParam].getComponentType(); // we have more than one
ExtractionUtils
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalCentroid.java
{ "start": 5213, "end": 6519 }
class ____ { public static final ParseField CENTROID = new ParseField("location"); public static final ParseField COUNT = new ParseField("count"); } @Override public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException { if (centroid != null) { builder.startObject(Fields.CENTROID.getPreferredName()); { builder.field(nameFirst(), extractFirst(centroid)); builder.field(nameSecond(), extractSecond(centroid)); } builder.endObject(); } builder.field(Fields.COUNT.getPreferredName(), count); return builder; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; if (super.equals(obj) == false) return false; InternalCentroid that = (InternalCentroid) obj; return count == that.count && Objects.equals(centroid, that.centroid); } @Override public int hashCode() { return Objects.hash(super.hashCode(), centroid, count); } @Override public String toString() { return "InternalCentroid{" + "centroid=" + centroid + ", count=" + count + '}'; } }
Fields
java
apache__hadoop
hadoop-tools/hadoop-streaming/src/test/java/org/apache/hadoop/streaming/TestStreamJob.java
{ "start": 1288, "end": 3476 }
class ____ { @Test public void testCreateJobWithExtraArgs() throws IOException { assertThrows(IllegalArgumentException.class, () -> { ArrayList<String> dummyArgs = new ArrayList<String>(); dummyArgs.add("-input"); dummyArgs.add("dummy"); dummyArgs.add("-output"); dummyArgs.add("dummy"); dummyArgs.add("-mapper"); dummyArgs.add("dummy"); dummyArgs.add("dummy"); dummyArgs.add("-reducer"); dummyArgs.add("dummy"); StreamJob.createJob(dummyArgs.toArray(new String[] {})); }); } @Test public void testCreateJob() throws IOException { JobConf job; ArrayList<String> dummyArgs = new ArrayList<String>(); dummyArgs.add("-input"); dummyArgs.add("dummy"); dummyArgs.add("-output"); dummyArgs.add("dummy"); dummyArgs.add("-mapper"); dummyArgs.add("dummy"); dummyArgs.add("-reducer"); dummyArgs.add("dummy"); ArrayList<String> args; args = new ArrayList<String>(dummyArgs); args.add("-inputformat"); args.add("org.apache.hadoop.mapred.KeyValueTextInputFormat"); job = StreamJob.createJob(args.toArray(new String[] {})); assertEquals(KeyValueTextInputFormat.class, job.getInputFormat().getClass()); args = new ArrayList<String>(dummyArgs); args.add("-inputformat"); args.add("org.apache.hadoop.mapred.SequenceFileInputFormat"); job = StreamJob.createJob(args.toArray(new String[] {})); assertEquals(SequenceFileInputFormat.class, job.getInputFormat().getClass()); args = new ArrayList<String>(dummyArgs); args.add("-inputformat"); args.add("org.apache.hadoop.mapred.KeyValueTextInputFormat"); args.add("-inputreader"); args.add("StreamXmlRecordReader,begin=<doc>,end=</doc>"); job = StreamJob.createJob(args.toArray(new String[] {})); assertEquals(StreamInputFormat.class, job.getInputFormat().getClass()); } @Test public void testOptions() throws Exception { StreamJob streamJob = new StreamJob(); assertEquals(1, streamJob.run(new String[0])); assertEquals(0, streamJob.run(new String[] {"-help"})); assertEquals(0, streamJob.run(new String[] {"-info"})); } }
TestStreamJob
java
apache__spark
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/Table.java
{ "start": 1431, "end": 1866 }
interface ____ mixin {@code SupportsRead} and {@code SupportsWrite} to provide data reading * and writing ability. * <p> * The default implementation of {@link #partitioning()} returns an empty array of partitions, and * the default implementation of {@link #properties()} returns an empty map. These should be * overridden by implementations that support partitioning and table properties. * * @since 3.0.0 */ @Evolving public
can
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/TreatedLeftJoinInheritanceTest.java
{ "start": 8544, "end": 8875 }
class ____ extends TablePerClassEntity { @ManyToOne private ChildEntity child; public TablePerClassSubEntity() { } public TablePerClassSubEntity(ChildEntity child) { this.child = child; } public ChildEntity getChild() { return child; } } @Entity( name = "ChildEntity" ) public static
TablePerClassSubEntity
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringFromMultipleEndpointTest.java
{ "start": 1040, "end": 1314 }
class ____ extends FromMultipleEndpointTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/fromMultipleEndpointTest.xml"); } }
SpringFromMultipleEndpointTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/PolymorphicJsonTests.java
{ "start": 1476, "end": 2626 }
class ____ extends PolymorphicJsonTests { public Jackson() { } } @BeforeEach public void setup(SessionFactoryScope scope) { scope.inTransaction( (session) -> { session.persist( new EntityWithJsonA( 1, new PropertyA( "e1" ) ) ); session.persist( new EntityWithJsonB( 2, new PropertyB( 123 ) ) ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void verifyReadWorks(SessionFactoryScope scope) { scope.inTransaction( (session) -> { EntityWithJson entityWithJsonA = session.find( EntityWithJson.class, 1 ); EntityWithJson entityWithJsonB = session.find( EntityWithJson.class, 2 ); assertThat( entityWithJsonA, instanceOf( EntityWithJsonA.class ) ); assertThat( entityWithJsonB, instanceOf( EntityWithJsonB.class ) ); assertThat( ( (EntityWithJsonA) entityWithJsonA ).property.value, is( "e1" ) ); assertThat( ( (EntityWithJsonB) entityWithJsonB ).property.value, is( 123 ) ); } ); } @Entity(name = "EntityWithJson") @Table(name = "EntityWithJson") public static abstract
Jackson
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/http/Http2ServerTest.java
{ "start": 6784, "end": 32076 }
class ____ extends AbstractHttp2ConnectionHandlerBuilder<TestClientHandler, TestClientHandlerBuilder> { private final Consumer<Connection> requestHandler; public TestClientHandlerBuilder(Consumer<Connection> requestHandler) { this.requestHandler = requestHandler; } @Override protected TestClientHandler build(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder, Http2Settings initialSettings) throws Exception { return new TestClientHandler(requestHandler, decoder, encoder, initialSettings); } public TestClientHandler build(Http2Connection conn) { connection(conn); initialSettings(settings); frameListener(new Http2EventAdapter() { @Override public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception { return super.onDataRead(ctx, streamId, data, padding, endOfStream); } }); return super.build(); } } protected ChannelInitializer channelInitializer(int port, String host, Promise<SslHandshakeCompletionEvent> latch, Consumer<Connection> handler) { return new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { SslContext sslContext = SslContextBuilder .forClient() .applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, HttpVersion.HTTP_2.alpnName(), HttpVersion.HTTP_1_1.alpnName() )).trustManager(Trust.SERVER_JKS.get().getTrustManagerFactory(vertx)) .build(); SslHandler sslHandler = sslContext.newHandler(ByteBufAllocator.DEFAULT, host, port); ch.pipeline().addLast(sslHandler); ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler("whatever") { @Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { ChannelPipeline p = ctx.pipeline(); Http2Connection connection = new DefaultHttp2Connection(false); TestClientHandlerBuilder clientHandlerBuilder = new TestClientHandlerBuilder(handler); TestClientHandler clientHandler = clientHandlerBuilder.build(connection); p.addLast(clientHandler); return; } ctx.close(); throw new IllegalStateException("unknown protocol: " + protocol); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeCompletion = (SslHandshakeCompletionEvent) evt; latch.tryComplete(handshakeCompletion); } super.userEventTriggered(ctx, evt); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { latch.tryFail("Channel closed"); super.channelInactive(ctx); } }); } }; } public Channel connect(int port, String host, Consumer<Connection> handler) throws Exception { Bootstrap bootstrap = new Bootstrap(); NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(); eventLoopGroups.add(eventLoopGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.group(eventLoopGroup); Promise<SslHandshakeCompletionEvent> promise = Promise.promise(); bootstrap.handler(channelInitializer(port, host, promise, handler)); ChannelFuture fut = bootstrap.connect(new InetSocketAddress(host, port)); fut.sync(); SslHandshakeCompletionEvent completion = promise.future().toCompletionStage().toCompletableFuture().get(); if (completion.isSuccess()) { return fut.channel(); } else { eventLoopGroup.shutdownGracefully(); AssertionFailedError afe = new AssertionFailedError(); afe.initCause(completion.cause()); throw afe; } } } @Test public void testConnectionHandler() throws Exception { waitFor(2); Context ctx = vertx.getOrCreateContext(); server.connectionHandler(conn -> { assertTrue(Context.isOnEventLoopThread()); assertSameEventLoop(vertx.getOrCreateContext(), ctx); complete(); }); server.requestHandler(req -> fail()); startServer(ctx); TestClient client = new TestClient(); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { vertx.runOnContext(v -> { complete(); }); }); await(); } @Test public void testServerInitialSettings() throws Exception { io.vertx.core.http.Http2Settings settings = TestUtils.randomHttp2Settings(); server.close(); server = vertx.createHttpServer(new HttpServerOptions(serverOptions).setInitialSettings(settings)); server.requestHandler(req -> fail()); startServer(); TestClient client = new TestClient(); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { request.decoder.frameListener(new Http2FrameAdapter() { @Override public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings newSettings) throws Http2Exception { vertx.runOnContext(v -> { assertEquals((Long) settings.getHeaderTableSize(), newSettings.headerTableSize()); assertEquals((Long) settings.getMaxConcurrentStreams(), newSettings.maxConcurrentStreams()); assertEquals((Integer) settings.getInitialWindowSize(), newSettings.initialWindowSize()); assertEquals((Integer) settings.getMaxFrameSize(), newSettings.maxFrameSize()); assertEquals((Long) settings.getMaxHeaderListSize(), newSettings.maxHeaderListSize()); assertEquals(settings.get('\u0007'), newSettings.get('\u0007')); testComplete(); }); } }); }); await(); } @Test public void testServerSettings() throws Exception { waitFor(2); io.vertx.core.http.Http2Settings expectedSettings = TestUtils.randomHttp2Settings(); expectedSettings.setHeaderTableSize((int)io.vertx.core.http.Http2Settings.DEFAULT_HEADER_TABLE_SIZE); Context otherContext = vertx.getOrCreateContext(); server.connectionHandler(conn -> { Context ctx = Vertx.currentContext(); otherContext.runOnContext(v -> { conn.updateSettings(expectedSettings).onComplete(onSuccess(ar -> { assertSame(ctx, Vertx.currentContext()); io.vertx.core.http.Http2Settings ackedSettings = conn.settings(); assertEquals(expectedSettings.getMaxHeaderListSize(), ackedSettings.getMaxHeaderListSize()); assertEquals(expectedSettings.getMaxFrameSize(), ackedSettings.getMaxFrameSize()); assertEquals(expectedSettings.getInitialWindowSize(), ackedSettings.getInitialWindowSize()); assertEquals(expectedSettings.getMaxConcurrentStreams(), ackedSettings.getMaxConcurrentStreams()); assertEquals(expectedSettings.getHeaderTableSize(), ackedSettings.getHeaderTableSize()); assertEquals(expectedSettings.get('\u0007'), ackedSettings.get(7)); complete(); })); }); }); server.requestHandler(req -> { fail(); }); startServer(); TestClient client = new TestClient(); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { request.decoder.frameListener(new Http2FrameAdapter() { AtomicInteger count = new AtomicInteger(); Context context = vertx.getOrCreateContext(); @Override public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings newSettings) throws Http2Exception { context.runOnContext(v -> { switch (count.getAndIncrement()) { case 0: // Initial settings break; case 1: // Server sent settings assertEquals((Long)expectedSettings.getMaxHeaderListSize(), newSettings.maxHeaderListSize()); assertEquals((Integer)expectedSettings.getMaxFrameSize(), newSettings.maxFrameSize()); assertEquals((Integer)expectedSettings.getInitialWindowSize(), newSettings.initialWindowSize()); assertEquals((Long)expectedSettings.getMaxConcurrentStreams(), newSettings.maxConcurrentStreams()); // assertEquals((Long)expectedSettings.getHeaderTableSize(), newSettings.headerTableSize()); complete(); break; default: fail(); } }); } }); }); await(); } @Test public void testClientSettings() throws Exception { Context ctx = vertx.getOrCreateContext(); io.vertx.core.http.Http2Settings initialSettings = TestUtils.randomHttp2Settings(); io.vertx.core.http.Http2Settings updatedSettings = TestUtils.randomHttp2Settings(); AtomicInteger count = new AtomicInteger(); server.connectionHandler(conn -> { io.vertx.core.http.Http2Settings settings = conn.remoteSettings(); assertEquals(initialSettings.isPushEnabled(), settings.isPushEnabled()); // Netty bug ? // Nothing has been yet received so we should get Integer.MAX_VALUE // assertEquals(Integer.MAX_VALUE, settings.getMaxHeaderListSize()); assertEquals(initialSettings.getMaxFrameSize(), settings.getMaxFrameSize()); assertEquals(initialSettings.getInitialWindowSize(), settings.getInitialWindowSize()); assertEquals((Long)(long)initialSettings.getMaxConcurrentStreams(), (Long)(long)settings.getMaxConcurrentStreams()); assertEquals(initialSettings.getHeaderTableSize(), settings.getHeaderTableSize()); conn.remoteSettingsHandler(update -> { assertOnIOContext(ctx); switch (count.getAndIncrement()) { case 0: assertEquals(updatedSettings.isPushEnabled(), update.isPushEnabled()); assertEquals(updatedSettings.getMaxHeaderListSize(), update.getMaxHeaderListSize()); assertEquals(updatedSettings.getMaxFrameSize(), update.getMaxFrameSize()); assertEquals(updatedSettings.getInitialWindowSize(), update.getInitialWindowSize()); assertEquals(updatedSettings.getMaxConcurrentStreams(), update.getMaxConcurrentStreams()); assertEquals(updatedSettings.getHeaderTableSize(), update.getHeaderTableSize()); assertEquals(updatedSettings.get('\u0007'), update.get(7)); testComplete(); break; default: fail(); } }); }); server.requestHandler(req -> { fail(); }); startServer(ctx); TestClient client = new TestClient(); client.settings.putAll(HttpUtils.fromVertxSettings(initialSettings)); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { request.encoder.writeSettings(request.context, HttpUtils.fromVertxSettings(updatedSettings), request.context.newPromise()); request.context.flush(); }); await(); } @Test public void testGet() throws Exception { String expected = TestUtils.randomAlphaString(1000); AtomicBoolean requestEnded = new AtomicBoolean(); Context ctx = vertx.getOrCreateContext(); AtomicInteger expectedStreamId = new AtomicInteger(); server.requestHandler(req -> { assertOnIOContext(ctx); req.endHandler(v -> { assertOnIOContext(ctx); requestEnded.set(true); }); HttpServerResponse resp = req.response(); assertEquals(HttpMethod.GET, req.method()); assertEquals(DEFAULT_HTTPS_HOST, req.authority().host()); assertEquals(DEFAULT_HTTPS_PORT, req.authority().port()); assertEquals("/", req.path()); assertTrue(req.isSSL()); assertEquals(expectedStreamId.get(), req.streamId()); assertEquals("https", req.scheme()); assertEquals("/", req.uri()); assertEquals("foo_request_value", req.getHeader("Foo_request")); assertEquals("bar_request_value", req.getHeader("bar_request")); assertEquals(2, req.headers().getAll("juu_request").size()); assertEquals("juu_request_value_1", req.headers().getAll("juu_request").get(0)); assertEquals("juu_request_value_2", req.headers().getAll("juu_request").get(1)); assertEquals(Collections.singletonList("cookie_1; cookie_2; cookie_3"), req.headers().getAll("cookie")); resp.putHeader("content-type", "text/plain"); resp.putHeader("Foo_response", "foo_response_value"); resp.putHeader("bar_response", "bar_response_value"); resp.putHeader("juu_response", (List<String>)Arrays.asList("juu_response_value_1", "juu_response_value_2")); resp.end(expected); }); startServer(ctx); TestClient client = new TestClient(); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { int id = request.nextStreamId(); expectedStreamId.set(id); request.decoder.frameListener(new Http2EventAdapter() { @Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception { vertx.runOnContext(v -> { assertEquals(id, streamId); assertEquals("200", headers.status().toString()); assertEquals("text/plain", headers.get("content-type").toString()); assertEquals("foo_response_value", headers.get("foo_response").toString()); assertEquals("bar_response_value", headers.get("bar_response").toString()); assertEquals(2, headers.getAll("juu_response").size()); assertEquals("juu_response_value_1", headers.getAll("juu_response").get(0).toString()); assertEquals("juu_response_value_2", headers.getAll("juu_response").get(1).toString()); assertFalse(endStream); }); } @Override public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception { String actual = data.toString(StandardCharsets.UTF_8); vertx.runOnContext(v -> { assertEquals(id, streamId); assertEquals(expected, actual); assertTrue(endOfStream); testComplete(); }); return super.onDataRead(ctx, streamId, data, padding, endOfStream); } }); Http2Headers headers = GET("/").authority(DEFAULT_HTTPS_HOST_AND_PORT); headers.set("foo_request", "foo_request_value"); headers.set("bar_request", "bar_request_value"); headers.set("juu_request", "juu_request_value_1", "juu_request_value_2"); headers.set("cookie", Arrays.asList("cookie_1", "cookie_2", "cookie_3")); request.encoder.writeHeaders(request.context, id, headers, 0, true, request.context.newPromise()); request.context.flush(); }); await(); } @Test public void testStatusMessage() throws Exception { server.requestHandler(req -> { HttpServerResponse resp = req.response(); resp.setStatusCode(404); assertEquals("Not Found", resp.getStatusMessage()); resp.setStatusMessage("whatever"); assertEquals("whatever", resp.getStatusMessage()); testComplete(); }); startServer(); TestClient client = new TestClient(); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { int id = request.nextStreamId(); request.encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise()); request.context.flush(); }); await(); } @Test public void testURI() throws Exception { server.requestHandler(req -> { assertEquals("/some/path", req.path()); assertEquals("foo=foo_value&bar=bar_value_1&bar=bar_value_2", req.query()); assertEquals("/some/path?foo=foo_value&bar=bar_value_1&bar=bar_value_2", req.uri()); assertEquals("http://whatever.com/some/path?foo=foo_value&bar=bar_value_1&bar=bar_value_2", req.absoluteURI()); assertEquals("whatever.com", req.authority().host()); MultiMap params = req.params(); Set<String> names = params.names(); assertEquals(2, names.size()); assertTrue(names.contains("foo")); assertTrue(names.contains("bar")); assertEquals("foo_value", params.get("foo")); assertEquals(Collections.singletonList("foo_value"), params.getAll("foo")); assertEquals("bar_value_1", params.get("bar")); assertEquals(Arrays.asList("bar_value_1", "bar_value_2"), params.getAll("bar")); testComplete(); }); startServer(); TestClient client = new TestClient(); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { int id = request.nextStreamId(); Http2Headers headers = new DefaultHttp2Headers(). method("GET"). scheme("http"). authority("whatever.com"). path("/some/path?foo=foo_value&bar=bar_value_1&bar=bar_value_2"); request.encoder.writeHeaders(request.context, id, headers, 0, true, request.context.newPromise()); request.context.flush(); }); await(); } @Test public void testHeadersEndHandler() throws Exception { Context ctx = vertx.getOrCreateContext(); server.requestHandler(req -> { HttpServerResponse resp = req.response(); resp.setChunked(true); resp.putHeader("some", "some-header"); resp.headersEndHandler(v -> { assertOnIOContext(ctx); assertFalse(resp.headWritten()); resp.putHeader("extra", "extra-header"); }); resp.write("something"); assertTrue(resp.headWritten()); resp.end(); }); startServer(ctx); TestClient client = new TestClient(); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { request.decoder.frameListener(new Http2EventAdapter() { @Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception { vertx.runOnContext(v -> { assertEquals("some-header", headers.get("some").toString()); assertEquals("extra-header", headers.get("extra").toString()); testComplete(); }); } }); int id = request.nextStreamId(); request.encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise()); request.context.flush(); }); await(); } @Test public void testBodyEndHandler() throws Exception { server.requestHandler(req -> { HttpServerResponse resp = req.response(); resp.setChunked(true); AtomicInteger count = new AtomicInteger(); resp.bodyEndHandler(v -> { assertEquals(0, count.getAndIncrement()); assertTrue(resp.ended()); }); resp.write("something"); assertEquals(0, count.get()); resp.end(); assertEquals(1, count.get()); testComplete(); }); startServer(); TestClient client = new TestClient(); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { int id = request.nextStreamId(); request.encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise()); request.context.flush(); }); await(); } @Test public void testPost() throws Exception { Context ctx = vertx.getOrCreateContext(); Buffer expectedContent = TestUtils.randomBuffer(1000); Buffer postContent = Buffer.buffer(); server.requestHandler(req -> { assertOnIOContext(ctx); req.handler(buff -> { assertOnIOContext(ctx); postContent.appendBuffer(buff); }); req.endHandler(v -> { assertOnIOContext(ctx); req.response().putHeader("content-type", "text/plain").end(""); assertEquals(expectedContent, postContent); testComplete(); }); }); startServer(ctx); TestClient client = new TestClient(); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { int id = request.nextStreamId(); request.encoder.writeHeaders(request.context, id, POST("/").set("content-type", "text/plain"), 0, false, request.context.newPromise()); request.encoder.writeData(request.context, id, ((BufferInternal)expectedContent).getByteBuf(), 0, true, request.context.newPromise()); request.context.flush(); }); await(); } @Test public void testPostFileUpload() throws Exception { Context ctx = vertx.getOrCreateContext(); server.requestHandler(req -> { Buffer tot = Buffer.buffer(); req.setExpectMultipart(true); req.uploadHandler(upload -> { assertOnIOContext(ctx); assertEquals("file", upload.name()); assertEquals("tmp-0.txt", upload.filename()); assertEquals("image/gif", upload.contentType()); upload.handler(tot::appendBuffer); upload.endHandler(v -> { assertEquals(tot, Buffer.buffer("some-content")); testComplete(); }); }); req.endHandler(v -> { assertEquals(0, req.formAttributes().size()); req.response().putHeader("content-type", "text/plain").end("done"); }); }); startServer(ctx); String contentType = "multipart/form-data; boundary=a4e41223-a527-49b6-ac1c-315d76be757e"; String contentLength = "225"; String body = "--a4e41223-a527-49b6-ac1c-315d76be757e\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" + "Content-Type: image/gif; charset=utf-8\r\n" + "Content-Length: 12\r\n" + "\r\n" + "some-content\r\n" + "--a4e41223-a527-49b6-ac1c-315d76be757e--\r\n"; TestClient client = new TestClient(); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { int id = request.nextStreamId(); request.encoder.writeHeaders(request.context, id, POST("/form"). set("content-type", contentType).set("content-length", contentLength), 0, false, request.context.newPromise()); request.encoder.writeData(request.context, id, BufferInternal.buffer(body).getByteBuf(), 0, true, request.context.newPromise()); request.context.flush(); }); await(); } @Test public void testConnect() throws Exception { server.requestHandler(req -> { assertEquals(HttpMethod.CONNECT, req.method()); assertEquals("whatever.com", req.authority().host()); assertNull(req.path()); assertNull(req.query()); assertNull(req.scheme()); assertNull(req.uri()); assertNull(req.absoluteURI()); testComplete(); }); startServer(); TestClient client = new TestClient(); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { int id = request.nextStreamId(); Http2Headers headers = new DefaultHttp2Headers().method("CONNECT").authority("whatever.com"); request.encoder.writeHeaders(request.context, id, headers, 0, true, request.context.newPromise()); request.context.flush(); }); await(); } @Test public void testServerRequestPauseResume() throws Exception { testStreamPauseResume(req -> Future.succeededFuture(req)); } private void testStreamPauseResume(Function<HttpServerRequest, Future<ReadStream<Buffer>>> streamProvider) throws Exception { Buffer expected = Buffer.buffer(); String chunk = TestUtils.randomAlphaString(1000); AtomicBoolean done = new AtomicBoolean(); AtomicBoolean paused = new AtomicBoolean(); Buffer received = Buffer.buffer(); server.requestHandler(req -> { Future<ReadStream<Buffer>> fut = streamProvider.apply(req); fut.onComplete(onSuccess(stream -> { vertx.setPeriodic(1, timerID -> { if (paused.get()) { vertx.cancelTimer(timerID); done.set(true); // Let some time to accumulate some more buffers vertx.setTimer(100, id -> { stream.resume(); }); } }); stream.handler(received::appendBuffer); stream.endHandler(v -> { assertEquals(expected, received); testComplete(); }); stream.pause(); })); }); startServer(); TestClient client = new TestClient(); client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { int id = request.nextStreamId(); request.encoder.writeHeaders(request.context, id, POST("/form"). set("content-type", "text/plain"), 0, false, request.context.newPromise()); request.context.flush(); Http2Stream stream = request.connection.stream(id);
TestClientHandlerBuilder
java
apache__flink
flink-core-api/src/main/java/org/apache/flink/api/common/state/StateDeclarations.java
{ "start": 8519, "end": 11333 }
class ____<K, V> implements Serializable { private static final long serialVersionUID = 1L; private final String name; private final TypeDescriptor<K> keyTypeInformation; private final TypeDescriptor<V> valueTypeInformation; private final StateDeclaration.RedistributionMode redistributionMode; public MapStateDeclarationBuilder( String name, TypeDescriptor<K> keyTypeInformation, TypeDescriptor<V> valueTypeInformation) { this( name, keyTypeInformation, valueTypeInformation, StateDeclaration.RedistributionMode.NONE); } public MapStateDeclarationBuilder( String name, TypeDescriptor<K> keyTypeInformation, TypeDescriptor<V> valueTypeInformation, StateDeclaration.RedistributionMode redistributionMode) { this.name = name; this.keyTypeInformation = keyTypeInformation; this.valueTypeInformation = valueTypeInformation; this.redistributionMode = redistributionMode; } public BroadcastStateDeclaration<K, V> buildBroadcast() { return new BroadcastStateDeclaration<K, V>() { @Override public TypeDescriptor<K> getKeyTypeDescriptor() { return keyTypeInformation; } @Override public TypeDescriptor<V> getValueTypeDescriptor() { return valueTypeInformation; } @Override public String getName() { return name; } @Override public RedistributionMode getRedistributionMode() { return StateDeclaration.RedistributionMode.IDENTICAL; } }; } MapStateDeclaration<K, V> build() { return new MapStateDeclaration<K, V>() { @Override public TypeDescriptor<K> getKeyTypeDescriptor() { return keyTypeInformation; } @Override public TypeDescriptor<V> getValueTypeDescriptor() { return valueTypeInformation; } @Override public String getName() { return name; } @Override public RedistributionMode getRedistributionMode() { return redistributionMode; } }; } } /** Builder for {@link ListStateDeclaration}. */ @Experimental public static
MapStateDeclarationBuilder
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/MarkerManager.java
{ "start": 1259, "end": 3762 }
class ____ { private static final ConcurrentMap<String, Marker> MARKERS = new ConcurrentHashMap<>(); private MarkerManager() { // do nothing } /** * Clears all markers. */ public static void clear() { MARKERS.clear(); } /** * Tests existence of the given marker. * * @param key the marker name * @return true if the marker exists. * @since 2.4 */ public static boolean exists(final String key) { return MARKERS.containsKey(key); } /** * Retrieves a Marker or create a Marker that has no parent. * * @param name The name of the Marker. * @return The Marker with the specified name. * @throws IllegalArgumentException if the argument is {@code null} */ public static Marker getMarker(final String name) { return MARKERS.computeIfAbsent(name, Log4jMarker::new); } /** * Retrieves or creates a Marker with the specified parent. The parent must have been previously created. * * @param name The name of the Marker. * @param parent The name of the parent Marker. * @return The Marker with the specified name. * @throws IllegalArgumentException if the parent Marker does not exist. * @deprecated Use the Marker add or set methods to add parent Markers. Will be removed by final GA release. */ @Deprecated public static Marker getMarker(final String name, final String parent) { final Marker parentMarker = MARKERS.get(parent); if (parentMarker == null) { throw new IllegalArgumentException("Parent Marker " + parent + " has not been defined"); } return getMarker(name).addParents(parentMarker); } /** * Retrieves or creates a Marker with the specified parent. * * @param name The name of the Marker. * @param parent The parent Marker. * @return The Marker with the specified name. * @throws IllegalArgumentException if any argument is {@code null} * @deprecated Use the Marker add or set methods to add parent Markers. Will be removed by final GA release. */ @InlineMe( replacement = "MarkerManager.getMarker(name).addParents(parent)", imports = "org.apache.logging.log4j.MarkerManager") @Deprecated public static Marker getMarker(final String name, final Marker parent) { return getMarker(name).addParents(parent); } /** * <em>Consider this
MarkerManager
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/metric/SecurityMetricType.java
{ "start": 379, "end": 4110 }
enum ____ { AUTHC_API_KEY( SecurityMetricGroup.AUTHC, new SecurityMetricInfo("es.security.authc.api_key.success.total", "Number of successful API key authentications.", "count"), new SecurityMetricInfo("es.security.authc.api_key.failures.total", "Number of failed API key authentications.", "count"), new SecurityMetricInfo("es.security.authc.api_key.time", "Time it took (in nanoseconds) to execute API key authentication.", "ns") ), CLOUD_AUTHC_API_KEY( SecurityMetricGroup.AUTHC, new SecurityMetricInfo( "es.security.authc.cloud_api_key.success.total", "Number of successful cloud API key authentications.", "count" ), new SecurityMetricInfo( "es.security.authc.cloud_api_key.failures.total", "Number of failed cloud API key authentications.", "count" ), new SecurityMetricInfo( "es.security.authc.cloud_api_key.time", "Time it took (in nanoseconds) to execute cloud API key authentication.", "ns" ) ), AUTHC_SERVICE_ACCOUNT( SecurityMetricGroup.AUTHC, new SecurityMetricInfo( "es.security.authc.service_account.success.total", "Number of successful service account authentications.", "count" ), new SecurityMetricInfo( "es.security.authc.service_account.failures.total", "Number of failed service account authentications.", "count" ), new SecurityMetricInfo( "es.security.authc.service_account.time", "Time it took (in nanoseconds) to execute service account authentication.", "ns" ) ), AUTHC_OAUTH2_TOKEN( SecurityMetricGroup.AUTHC, new SecurityMetricInfo("es.security.authc.token.success.total", "Number of successful OAuth2 token authentications.", "count"), new SecurityMetricInfo("es.security.authc.token.failures.total", "Number of failed OAuth2 token authentications.", "count"), new SecurityMetricInfo( "es.security.authc.token.time", "Time it took (in nanoseconds) to execute OAuth2 token authentication.", "ns" ) ), AUTHC_REALMS( SecurityMetricGroup.AUTHC, new SecurityMetricInfo("es.security.authc.realms.success.total", "Number of successful realm authentications.", "count"), new SecurityMetricInfo("es.security.authc.realms.failures.total", "Number of failed realm authentications.", "count"), new SecurityMetricInfo("es.security.authc.realms.time", "Time it took (in nanoseconds) to execute realm authentication.", "ns") ), ; private final SecurityMetricGroup group; private final SecurityMetricInfo successMetricInfo; private final SecurityMetricInfo failuresMetricInfo; private final SecurityMetricInfo timeMetricInfo; SecurityMetricType( SecurityMetricGroup group, SecurityMetricInfo successMetricInfo, SecurityMetricInfo failuresMetricInfo, SecurityMetricInfo timeMetricInfo ) { this.group = group; this.successMetricInfo = successMetricInfo; this.failuresMetricInfo = failuresMetricInfo; this.timeMetricInfo = timeMetricInfo; } public SecurityMetricGroup group() { return this.group; } public SecurityMetricInfo successMetricInfo() { return successMetricInfo; } public SecurityMetricInfo failuresMetricInfo() { return failuresMetricInfo; } public SecurityMetricInfo timeMetricInfo() { return timeMetricInfo; } }
SecurityMetricType
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/aggregate/MinOverTimeTests.java
{ "start": 1042, "end": 1871 }
class ____ extends AbstractFunctionTestCase { public MinOverTimeTests(Supplier<TestCaseSupplier.TestCase> testCaseSupplier) { testCase = testCaseSupplier.get(); } @ParametersFactory public static Iterable<Object[]> parameters() { return MinTests.parameters(); } @Override protected Expression build(Source source, List<Expression> args) { return new MinOverTime(source, args.get(0), AggregateFunction.NO_WINDOW); } public static List<DocsV3Support.Param> signatureTypes(List<DocsV3Support.Param> params) { var preview = appliesTo(FunctionAppliesToLifecycle.PREVIEW, "9.3.0", "", false); DocsV3Support.Param window = new DocsV3Support.Param(DataType.TIME_DURATION, List.of(preview)); return List.of(params.get(0), window); } }
MinOverTimeTests
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/extension/LifecycleMethodExecutionExceptionHandler.java
{ "start": 951, "end": 2292 }
class ____ * if exceptions thrown from {@code @BeforeAll} or {@code @AfterAll} methods are * to be handled. When registered at the test level, only exceptions thrown from * {@code @BeforeEach} or {@code @AfterEach} methods will be handled. * * <h2>Constructor Requirements</h2> * * <p>Consult the documentation in {@link Extension} for details on constructor * requirements. * * <h2 id="implementation-guidelines">Implementation Guidelines</h2> * * <p>An implementation of an exception handler method defined in this API must * perform one of the following. * * <ol> * <li>Rethrow the supplied {@code Throwable} <em>as is</em>, which is the default implementation.</li> * <li>Swallow the supplied {@code Throwable}, thereby preventing propagation.</li> * <li>Throw a new exception, potentially wrapping the supplied {@code Throwable}.</li> * </ol> * * <p>If the supplied {@code Throwable} is swallowed by a handler method, subsequent * handler methods for the same lifecycle will not be invoked; otherwise, the * corresponding handler method of the next registered * {@code LifecycleMethodExecutionExceptionHandler} (if there is one) will be * invoked with any {@link Throwable} thrown by the previous handler. * * @since 5.5 * @see TestExecutionExceptionHandler */ @API(status = STABLE, since = "5.10") public
level
java
quarkusio__quarkus
independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/DeploymentDependencySelector.java
{ "start": 247, "end": 1627 }
class ____ implements DependencySelector { static DependencySelector ensureDeploymentDependencySelector(DependencySelector original) { return original.getClass() == DeploymentDependencySelector.class ? original : new DeploymentDependencySelector(original); } private final DependencySelector delegate; DeploymentDependencySelector(DependencySelector delegate) { this.delegate = delegate; } @Override public boolean selectDependency(Dependency dependency) { return !dependency.isOptional() && delegate.selectDependency(dependency); } @Override public DependencySelector deriveChildSelector(DependencyCollectionContext context) { final DependencySelector newDelegate = delegate.deriveChildSelector(context); return newDelegate == null ? null : ensureDeploymentDependencySelector(newDelegate); } @Override public int hashCode() { return Objects.hash(delegate); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DeploymentDependencySelector other = (DeploymentDependencySelector) obj; return Objects.equals(delegate, other.delegate); } }
DeploymentDependencySelector
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-actuator/src/main/java/smoketest/actuator/ExampleHealthIndicator.java
{ "start": 850, "end": 1008 }
class ____ implements HealthIndicator { @Override public Health health() { return Health.up().withDetail("counter", 42).build(); } }
ExampleHealthIndicator
java
apache__maven
compat/maven-compat/src/main/java/org/apache/maven/project/artifact/ActiveProjectArtifact.java
{ "start": 1722, "end": 1863 }
class ____ * should be split. ie scope, file, etc depend on the context of use, whereas everything else is immutable. */ @Deprecated public
and
java
apache__maven
compat/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/relocation/UserPropertiesArtifactRelocationSource.java
{ "start": 6197, "end": 9188 }
class ____ { private final List<Relocation> relocations; private Relocations(List<Relocation> relocations) { this.relocations = relocations; } private Relocation getRelocation(Artifact artifact) { return relocations.stream() .filter(r -> r.predicate.test(artifact)) .findFirst() .orElse(null); } } private Relocations parseRelocations(RepositorySystemSession session) { String relocationsEntries = (String) session.getConfigProperties().get(CONFIG_PROP_RELOCATIONS_ENTRIES); if (relocationsEntries == null) { return null; } String[] entries = relocationsEntries.split(","); try (Stream<String> lines = Arrays.stream(entries)) { List<Relocation> relocationList = lines.filter( l -> l != null && !l.trim().isEmpty()) .map(l -> { boolean global; String splitExpr; if (l.contains(">>")) { global = true; splitExpr = ">>"; } else if (l.contains(">")) { global = false; splitExpr = ">"; } else { throw new IllegalArgumentException("Unrecognized entry: " + l); } String[] parts = l.split(splitExpr); if (parts.length < 1) { throw new IllegalArgumentException("Unrecognized entry: " + l); } Artifact s = parseArtifact(parts[0]); Artifact t; if (parts.length > 1) { t = parseArtifact(parts[1]); } else { t = SENTINEL; } return new Relocation(global, s, t); }) .collect(Collectors.toList()); LOGGER.info("Parsed {} user relocations", relocationList.size()); return new Relocations(relocationList); } } private static Artifact parseArtifact(String coords) { Artifact s; String[] parts = coords.split(":"); s = switch (parts.length) { case 3 -> new DefaultArtifact(parts[0], parts[1], "*", "*", parts[2]); case 4 -> new DefaultArtifact(parts[0], parts[1], "*", parts[2], parts[3]); case 5 -> new DefaultArtifact(parts[0], parts[1], parts[2], parts[3], parts[4]); default -> throw new IllegalArgumentException("Bad artifact coordinates " + coords + ", expected format is <groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>"); }; return s; } }
Relocations
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/rm/RMContainerAllocationException.java
{ "start": 942, "end": 1309 }
class ____ extends Exception { private static final long serialVersionUID = 1L; public RMContainerAllocationException(Throwable cause) { super(cause); } public RMContainerAllocationException(String message) { super(message); } public RMContainerAllocationException(String message, Throwable cause) { super(message, cause); } }
RMContainerAllocationException
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-nfs/src/main/java/org/apache/hadoop/hdfs/nfs/nfs3/Nfs3Utils.java
{ "start": 1899, "end": 9889 }
class ____ { public final static String INODEID_PATH_PREFIX = "/.reserved/.inodes/"; public final static String READ_RPC_START = "READ_RPC_CALL_START____"; public final static String READ_RPC_END = "READ_RPC_CALL_END______"; public final static String WRITE_RPC_START = "WRITE_RPC_CALL_START____"; public final static String WRITE_RPC_END = "WRITE_RPC_CALL_END______"; public static String getFileIdPath(FileHandle handle) { return getFileIdPath(handle.getFileId()); } public static String getFileIdPath(long fileId) { return INODEID_PATH_PREFIX + fileId; } public static HdfsFileStatus getFileStatus(DFSClient client, String fileIdPath) throws IOException { return client.getFileLinkInfo(fileIdPath); } public static Nfs3FileAttributes getNfs3FileAttrFromFileStatus( HdfsFileStatus fs, IdMappingServiceProvider iug) { /** * Some 32bit Linux client has problem with 64bit fileId: it seems the 32bit * client takes only the lower 32bit of the fileId and treats it as signed * int. When the 32th bit is 1, the client considers it invalid. */ NfsFileType fileType = fs.isDirectory() ? NfsFileType.NFSDIR : NfsFileType.NFSREG; fileType = fs.isSymlink() ? NfsFileType.NFSLNK : fileType; int nlink = (fileType == NfsFileType.NFSDIR) ? fs.getChildrenNum() + 2 : 1; long size = (fileType == NfsFileType.NFSDIR) ? getDirSize(fs .getChildrenNum()) : fs.getLen(); return new Nfs3FileAttributes(fileType, nlink, fs.getPermission().toShort(), iug.getUidAllowingUnknown(fs.getOwner()), iug.getGidAllowingUnknown(fs.getGroup()), size, 0 /* fsid */, fs.getFileId(), fs.getModificationTime(), fs.getAccessTime(), new Nfs3FileAttributes.Specdata3()); } public static Nfs3FileAttributes getFileAttr(DFSClient client, String fileIdPath, IdMappingServiceProvider iug) throws IOException { HdfsFileStatus fs = getFileStatus(client, fileIdPath); return fs == null ? null : getNfs3FileAttrFromFileStatus(fs, iug); } /** * HDFS directory size is always zero. Try to return something meaningful * here. Assume each child take 32bytes. * @param childNum number of children of the directory * @return total size of the directory */ public static long getDirSize(int childNum) { return (childNum + 2) * 32; } public static WccAttr getWccAttr(DFSClient client, String fileIdPath) throws IOException { HdfsFileStatus fstat = getFileStatus(client, fileIdPath); if (fstat == null) { return null; } long size = fstat.isDirectory() ? getDirSize(fstat.getChildrenNum()) : fstat .getLen(); return new WccAttr(size, new NfsTime(fstat.getModificationTime()), new NfsTime(fstat.getModificationTime())); } public static WccAttr getWccAttr(Nfs3FileAttributes attr) { return attr == null ? new WccAttr() : new WccAttr(attr.getSize(), attr.getMtime(), attr.getCtime()); } // TODO: maybe not efficient public static WccData createWccData(final WccAttr preOpAttr, DFSClient dfsClient, final String fileIdPath, final IdMappingServiceProvider iug) throws IOException { Nfs3FileAttributes postOpDirAttr = getFileAttr(dfsClient, fileIdPath, iug); return new WccData(preOpAttr, postOpDirAttr); } /** * Send a write response to the netty network socket channel * @param channel channel to which the buffer needs to be written * @param out xdr object to be written to the channel * @param xid transaction identifier */ public static void writeChannel(Channel channel, XDR out, int xid) { if (channel == null) { RpcProgramNfs3.LOG .info("Null channel should only happen in tests. Do nothing."); return; } if (RpcProgramNfs3.LOG.isDebugEnabled()) { RpcProgramNfs3.LOG.debug(WRITE_RPC_END + xid); } ByteBuf outBuf = XDR.writeMessageTcp(out, true); channel.writeAndFlush(outBuf); } public static void writeChannelCommit(Channel channel, XDR out, int xid) { if (RpcProgramNfs3.LOG.isDebugEnabled()) { RpcProgramNfs3.LOG.debug("Commit done:" + xid); } ByteBuf outBuf = XDR.writeMessageTcp(out, true); channel.writeAndFlush(outBuf); } private static boolean isSet(int access, int bits) { return (access & bits) == bits; } public static int getAccessRights(int mode, int type) { int rtn = 0; if (isSet(mode, Nfs3Constant.ACCESS_MODE_READ)) { rtn |= Nfs3Constant.ACCESS3_READ; // LOOKUP is only meaningful for dir if (type == NfsFileType.NFSDIR.toValue()) { rtn |= Nfs3Constant.ACCESS3_LOOKUP; } } if (isSet(mode, Nfs3Constant.ACCESS_MODE_WRITE)) { rtn |= Nfs3Constant.ACCESS3_MODIFY; rtn |= Nfs3Constant.ACCESS3_EXTEND; // Set delete bit, UNIX may ignore it for regular file since it's up to // parent dir op permission rtn |= Nfs3Constant.ACCESS3_DELETE; } if (isSet(mode, Nfs3Constant.ACCESS_MODE_EXECUTE)) { if (type == NfsFileType.NFSREG.toValue()) { rtn |= Nfs3Constant.ACCESS3_EXECUTE; } else { rtn |= Nfs3Constant.ACCESS3_LOOKUP; } } return rtn; } public static int getAccessRightsForUserGroup(int uid, int gid, int[] auxGids, Nfs3FileAttributes attr) { int mode = attr.getMode(); if (uid == attr.getUid()) { return getAccessRights(mode >> 6, attr.getType()); } if (gid == attr.getGid()) { return getAccessRights(mode >> 3, attr.getType()); } // Check for membership in auxiliary groups if (auxGids != null) { for (int auxGid : auxGids) { if (attr.getGid() == auxGid) { return getAccessRights(mode >> 3, attr.getType()); } } } return getAccessRights(mode, attr.getType()); } public static long bytesToLong(byte[] data) { long n = 0xffL & data[0]; for (int i = 1; i < 8; i++) { n = (n << 8) | (0xffL & data[i]); } return n; } public static byte[] longToByte(long v) { byte[] data = new byte[8]; data[0] = (byte) (v >>> 56); data[1] = (byte) (v >>> 48); data[2] = (byte) (v >>> 40); data[3] = (byte) (v >>> 32); data[4] = (byte) (v >>> 24); data[5] = (byte) (v >>> 16); data[6] = (byte) (v >>> 8); data[7] = (byte) (v >>> 0); return data; } public static long getElapsedTime(long startTimeNano) { return System.nanoTime() - startTimeNano; } public static int getNamenodeId(Configuration conf) { URI filesystemURI = FileSystem.getDefaultUri(conf); return getNamenodeId(conf, filesystemURI); } public static int getNamenodeId(Configuration conf, URI namenodeURI) { InetSocketAddress address = DFSUtilClient.getNNAddressCheckLogical(conf, namenodeURI); return address.hashCode(); } public static URI getResolvedURI(FileSystem fs, String exportPath) throws IOException { URI fsURI = fs.getUri(); String scheme = fs.getScheme(); if (scheme.equalsIgnoreCase(FsConstants.VIEWFS_SCHEME)) { ViewFileSystem viewFs = (ViewFileSystem)fs; ViewFileSystem.MountPoint[] mountPoints = viewFs.getMountPoints(); for (ViewFileSystem.MountPoint mount : mountPoints) { String mountedPath = mount.getMountedOnPath().toString(); if (exportPath.startsWith(mountedPath)) { String subpath = exportPath.substring(mountedPath.length()); fsURI = mount.getTargetFileSystemURIs()[0].resolve(subpath); break; } } } else if (scheme.equalsIgnoreCase(HdfsConstants.HDFS_URI_SCHEME)) { fsURI = fsURI.resolve(exportPath); } if (!fsURI.getScheme().equalsIgnoreCase(HdfsConstants.HDFS_URI_SCHEME)) { throw new FileSystemException("Only HDFS is supported as underlying" + "FileSystem, fs scheme:" + scheme + " uri to be added" + fsURI); } return fsURI; } }
Nfs3Utils
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/convert/internal/AttributeConverterManager.java
{ "start": 5319, "end": 9487 }
enum ____ { ATTRIBUTE, COLLECTION_ELEMENT, MAP_KEY; public String getSiteDescriptor() { return switch ( this ) { case ATTRIBUTE -> "basic attribute"; case COLLECTION_ELEMENT -> "collection attribute's element"; case MAP_KEY -> "map attribute's key"; }; } } @Override public ConverterDescriptor<?,?> findAutoApplyConverterForAttribute( MemberDetails attributeMember, MetadataBuildingContext context) { return locateMatchingConverter( attributeMember, ConversionSite.ATTRIBUTE, (autoApplyDescriptor) -> autoApplyDescriptor.getAutoAppliedConverterDescriptorForAttribute( attributeMember, context ), context ); } private ConverterDescriptor<?,?> locateMatchingConverter( MemberDetails memberDetails, ConversionSite conversionSite, Function<AutoApplicableConverterDescriptor, ConverterDescriptor<?,?>> matcher, MetadataBuildingContext context) { if ( registeredConversionsByDomainType != null ) { // we had registered conversions - see if any of them match and, if so, use that conversion final var resolveAttributeType = resolveAttributeType( memberDetails, context ); final var registrationForDomainType = registeredConversionsByDomainType.get( resolveAttributeType.getErasedType() ); if ( registrationForDomainType != null ) { return registrationForDomainType.isAutoApply() ? registrationForDomainType.getConverterDescriptor() : null; } } return pickUniqueMatch( memberDetails, conversionSite, getMatches( memberDetails, conversionSite, matcher ) ); } private static ConverterDescriptor<?,?> pickUniqueMatch( MemberDetails memberDetails, ConversionSite conversionSite, List<ConverterDescriptor<?,?>> matches) { return switch ( matches.size() ) { case 0 -> null; case 1 -> matches.get( 0 ); default -> { final var filtered = matches.stream() .filter( match -> !match.overrideable() ) .toList(); if ( filtered.size() == 1 ) { yield filtered.get( 0 ); } else { // otherwise, we had multiple matches throw new HibernateException( String.format( Locale.ROOT, "Multiple auto-apply converters matched %s [%s.%s] : %s", conversionSite.getSiteDescriptor(), memberDetails.getDeclaringType().getName(), memberDetails.getName(), join( matches, value -> value.getAttributeConverterClass().getName() ) ) ); } } }; } private List<ConverterDescriptor<?,?>> getMatches( MemberDetails memberDetails, ConversionSite conversionSite, Function<AutoApplicableConverterDescriptor, ConverterDescriptor<?,?>> matcher) { final List<ConverterDescriptor<?,?>> matches = new ArrayList<>(); for ( var descriptor : converterDescriptors() ) { if ( BOOT_LOGGER.isTraceEnabled() ) { BOOT_LOGGER.checkingAutoApplyAttributeConverter( descriptor.getAttributeConverterClass().getName(), descriptor.getDomainValueResolvedType().getSignature(), conversionSite.getSiteDescriptor(), memberDetails.getDeclaringType().getName(), memberDetails.getName(), memberDetails.getType().getName() ); } final var match = matcher.apply( descriptor.getAutoApplyDescriptor() ); if ( match != null ) { matches.add( descriptor ); } } return matches; } @Override public ConverterDescriptor<?,?> findAutoApplyConverterForCollectionElement( MemberDetails attributeMember, MetadataBuildingContext context) { return locateMatchingConverter( attributeMember, ConversionSite.COLLECTION_ELEMENT, (autoApplyDescriptor) -> autoApplyDescriptor.getAutoAppliedConverterDescriptorForCollectionElement( attributeMember, context ), context ); } @Override public ConverterDescriptor<?,?> findAutoApplyConverterForMapKey( MemberDetails attributeMember, MetadataBuildingContext context) { return locateMatchingConverter( attributeMember, ConversionSite.MAP_KEY, (autoApplyDescriptor) -> autoApplyDescriptor.getAutoAppliedConverterDescriptorForMapKey( attributeMember, context ), context ); } }
ConversionSite
java
apache__camel
core/camel-main/src/test/java/org/apache/camel/main/MainSupervisingRouteControllerTest.java
{ "start": 1546, "end": 7202 }
class ____ { @Test public void testMain() throws Exception { // lets make a simple route Main main = new Main(); main.configure().addRoutesBuilder(new MyRoute()); main.configure().routeControllerConfig() .withEnabled(true) .withBackOffDelay(25) .withBackOffMaxAttempts(3) .withInitialDelay(100) .withThreadPoolSize(2) .withExcludeRoutes("timer*"); main.start(); MockEndpoint mock = main.getCamelContext().getEndpoint("mock:foo", MockEndpoint.class); mock.expectedMinimumMessageCount(3); MockEndpoint mock2 = main.getCamelContext().getEndpoint("mock:cheese", MockEndpoint.class); mock2.expectedMessageCount(0); MockEndpoint mock3 = main.getCamelContext().getEndpoint("mock:cake", MockEndpoint.class); mock3.expectedMessageCount(0); MockEndpoint mock4 = main.getCamelContext().getEndpoint("mock:bar", MockEndpoint.class); mock4.expectedMessageCount(0); MockEndpoint.assertIsSatisfied(5, TimeUnit.SECONDS, mock, mock2, mock3, mock4); assertEquals("Started", main.camelContext.getRouteController().getRouteStatus("foo").toString()); // cheese was not able to start assertEquals("Stopped", main.camelContext.getRouteController().getRouteStatus("cheese").toString()); // cake was not able to start assertEquals("Stopped", main.camelContext.getRouteController().getRouteStatus("cake").toString()); SupervisingRouteController src = (SupervisingRouteController) main.camelContext.getRouteController(); Throwable e = src.getRestartException("cake"); assertNotNull(e); assertEquals("Cannot start", e.getMessage()); assertInstanceOf(IllegalArgumentException.class, e); // bar is no auto startup assertEquals("Stopped", main.camelContext.getRouteController().getRouteStatus("bar").toString()); main.stop(); } @Test public void testMainOk() throws Exception { // lets make a simple route Main main = new Main(); main.configure().addRoutesBuilder(new MyRoute()); main.configure().routeControllerConfig().setEnabled(true); main.configure().routeControllerConfig().setBackOffDelay(25); main.configure().routeControllerConfig().setBackOffMaxAttempts(10); main.configure().routeControllerConfig().setInitialDelay(100); main.configure().routeControllerConfig().setThreadPoolSize(2); main.start(); MockEndpoint mock = main.getCamelContext().getEndpoint("mock:foo", MockEndpoint.class); mock.expectedMinimumMessageCount(3); MockEndpoint mock2 = main.getCamelContext().getEndpoint("mock:cheese", MockEndpoint.class); mock2.expectedMessageCount(0); MockEndpoint mock3 = main.getCamelContext().getEndpoint("mock:cake", MockEndpoint.class); mock3.expectedMessageCount(0); MockEndpoint mock4 = main.getCamelContext().getEndpoint("mock:bar", MockEndpoint.class); mock4.expectedMessageCount(0); MockEndpoint.assertIsSatisfied(5, TimeUnit.SECONDS, mock, mock2, mock3, mock4); // these should all start assertEquals("Started", main.camelContext.getRouteController().getRouteStatus("foo").toString()); assertEquals("Started", main.camelContext.getRouteController().getRouteStatus("cheese").toString()); assertEquals("Started", main.camelContext.getRouteController().getRouteStatus("cake").toString()); // bar is no auto startup assertEquals("Stopped", main.camelContext.getRouteController().getRouteStatus("bar").toString()); main.stop(); } @Test public void testMainApplicationProperties() throws Exception { // lets make a simple route Main main = new Main(); main.setDefaultPropertyPlaceholderLocation("classpath:route-controller.properties"); main.configure().addRoutesBuilder(new MyRoute()); main.start(); MockEndpoint mock = main.getCamelContext().getEndpoint("mock:foo", MockEndpoint.class); mock.expectedMinimumMessageCount(3); MockEndpoint mock2 = main.getCamelContext().getEndpoint("mock:cheese", MockEndpoint.class); mock2.expectedMessageCount(0); MockEndpoint mock3 = main.getCamelContext().getEndpoint("mock:cake", MockEndpoint.class); mock3.expectedMessageCount(0); MockEndpoint mock4 = main.getCamelContext().getEndpoint("mock:bar", MockEndpoint.class); mock4.expectedMessageCount(0); MockEndpoint.assertIsSatisfied(5, TimeUnit.SECONDS, mock, mock2, mock3, mock4); assertEquals("Started", main.camelContext.getRouteController().getRouteStatus("foo").toString()); // cheese was not able to start assertEquals("Stopped", main.camelContext.getRouteController().getRouteStatus("cheese").toString()); // cake was not able to start assertEquals("Stopped", main.camelContext.getRouteController().getRouteStatus("cake").toString()); SupervisingRouteController src = (SupervisingRouteController) main.camelContext.getRouteController(); Throwable e = src.getRestartException("cake"); assertNotNull(e); assertEquals("Cannot start", e.getMessage()); assertInstanceOf(IllegalArgumentException.class, e); // bar is no auto startup assertEquals("Stopped", main.camelContext.getRouteController().getRouteStatus("bar").toString()); main.stop(); } private static
MainSupervisingRouteControllerTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryAsyncTest.java
{ "start": 4558, "end": 4988 }
class ____ { AtomicInteger test() { var ai = new AtomicInteger(); ai.set(1); return ai; } } """) .doTest(); } @Test public void negative_passedToAnotherMethod() { helper .addSourceLines( "Test.java", """ import java.util.concurrent.atomic.AtomicInteger;
Test
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/subselect/Employee.java
{ "start": 262, "end": 558 }
class ____ { @Id @GeneratedValue private Long id; private String name; public String getName() { return name; } @SuppressWarnings("unused") private Employee() { } public Employee(String name) { this.name = name; } @Override public String toString() { return name; } }
Employee
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/long2darrays/Long2DArrays_assertContains_at_Index_Test.java
{ "start": 1116, "end": 1476 }
class ____ extends Long2DArraysBaseTest { @Test void should_delegate_to_Arrays2D() { // GIVEN long[] longs = new long[] { 6, 8, 10 }; // WHEN long2dArrays.assertContains(info, actual, longs, atIndex(1)); // THEN verify(arrays2d).assertContains(info, failures, actual, longs, atIndex(1)); } }
Long2DArrays_assertContains_at_Index_Test
java
google__dagger
javatests/dagger/internal/codegen/AssistedFactoryTest.java
{ "start": 12568, "end": 12707 }
class ____ {}"); Source bar = CompilerTests.javaSource( "test.Bar", "package test;", "final
Foo
java
netty__netty
transport/src/main/java/io/netty/channel/socket/nio/NioDomainSocketChannel.java
{ "start": 16067, "end": 16232 }
class ____ extends NioByteUnsafe { // Only extending it so we create a new instance in newUnsafe() and return it. } private final
NioSocketChannelUnsafe
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/indices/IndicesServiceTests.java
{ "start": 8154, "end": 8712 }
class ____ extends Plugin implements MapperPlugin { public TestPlugin() {} @Override public Map<String, Mapper.TypeParser> getMappers() { return Collections.singletonMap("fake-mapper", KeywordFieldMapper.PARSER); } @Override public void onIndexModule(IndexModule indexModule) { super.onIndexModule(indexModule); indexModule.addSimilarity("fake-similarity", (settings, indexCreatedVersion, scriptService) -> new BM25Similarity()); } } public static
TestPlugin
java
apache__flink
flink-state-backends/flink-statebackend-forst/src/main/java/org/apache/flink/state/forst/ForStIncrementalCheckpointUtils.java
{ "start": 1678, "end": 3072 }
class ____ { private static final Logger logger = LoggerFactory.getLogger(ForStIncrementalCheckpointUtils.class); /** * Evaluates state handle's "score" regarding the target range when choosing the best state * handle to init the initial db for recovery, if the overlap fraction is less than * overlapFractionThreshold, then just return {@code Score.MIN} to mean the handle has no chance * to be the initial handle. */ private static Score stateHandleEvaluator( KeyedStateHandle stateHandle, KeyGroupRange targetKeyGroupRange, double overlapFractionThreshold) { final KeyGroupRange handleKeyGroupRange = stateHandle.getKeyGroupRange(); final KeyGroupRange intersectGroup = handleKeyGroupRange.getIntersection(targetKeyGroupRange); final double overlapFraction = (double) intersectGroup.getNumberOfKeyGroups() / handleKeyGroupRange.getNumberOfKeyGroups(); if (overlapFraction < overlapFractionThreshold) { return Score.MIN; } return new Score(intersectGroup.getNumberOfKeyGroups(), overlapFraction); } /** * Score of the state handle, intersect group range is compared first, and then compare the * overlap fraction. */ private static
ForStIncrementalCheckpointUtils
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/selection/typegenerics/SourceWildCardExtendsMapper.java
{ "start": 316, "end": 600 }
interface ____ { SourceWildCardExtendsMapper INSTANCE = Mappers.getMapper( SourceWildCardExtendsMapper.class ); Target map( Source source); default String unwrap(Wrapper<? extends Number> t) { return t.getWrapped().toString(); }
SourceWildCardExtendsMapper
java
grpc__grpc-java
util/src/main/java/io/grpc/util/SecretRoundRobinLoadBalancerProvider.java
{ "start": 1010, "end": 1133 }
class ____ { private SecretRoundRobinLoadBalancerProvider() { } public static final
SecretRoundRobinLoadBalancerProvider
java
elastic__elasticsearch
modules/mapper-extras/src/main/java/org/elasticsearch/index/mapper/extras/MapperExtrasPlugin.java
{ "start": 884, "end": 2171 }
class ____ extends Plugin implements MapperPlugin, SearchPlugin { @Override public Map<String, Mapper.TypeParser> getMappers() { Map<String, Mapper.TypeParser> mappers = new LinkedHashMap<>(); mappers.put(ScaledFloatFieldMapper.CONTENT_TYPE, ScaledFloatFieldMapper.PARSER); mappers.put(TokenCountFieldMapper.CONTENT_TYPE, TokenCountFieldMapper.PARSER); mappers.put(RankFeatureFieldMapper.CONTENT_TYPE, RankFeatureFieldMapper.PARSER); mappers.put(RankFeaturesFieldMapper.CONTENT_TYPE, RankFeaturesFieldMapper.PARSER); mappers.put(SearchAsYouTypeFieldMapper.CONTENT_TYPE, SearchAsYouTypeFieldMapper.PARSER); mappers.put(MatchOnlyTextFieldMapper.CONTENT_TYPE, MatchOnlyTextFieldMapper.PARSER); return Collections.unmodifiableMap(mappers); } @Override public Map<String, TypeParser> getMetadataMappers() { return Collections.singletonMap(RankFeatureMetaFieldMapper.CONTENT_TYPE, RankFeatureMetaFieldMapper.PARSER); } @Override public List<QuerySpec<?>> getQueries() { return Collections.singletonList( new QuerySpec<>(RankFeatureQueryBuilder.NAME, RankFeatureQueryBuilder::new, p -> RankFeatureQueryBuilder.PARSER.parse(p, null)) ); } }
MapperExtrasPlugin
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringPropertyModelHandler.java
{ "start": 1598, "end": 2771 }
class ____ extends ModelHandlerBase { private final @Nullable Environment environment; SpringPropertyModelHandler(Context context, @Nullable Environment environment) { super(context); this.environment = environment; } @Override public void handle(ModelInterpretationContext intercon, Model model) throws ModelHandlerException { SpringPropertyModel propertyModel = (SpringPropertyModel) model; Scope scope = ActionUtil.stringToScope(propertyModel.getScope()); String defaultValue = propertyModel.getDefaultValue(); String source = propertyModel.getSource(); if (OptionHelper.isNullOrEmpty(propertyModel.getName()) || OptionHelper.isNullOrEmpty(source)) { addError("The \"name\" and \"source\" attributes of <springProperty> must be set"); } PropertyModelHandlerHelper.setProperty(intercon, propertyModel.getName(), getValue(source, defaultValue), scope); } private String getValue(String source, String defaultValue) { if (this.environment == null) { addWarn("No Spring Environment available to resolve " + source); return defaultValue; } return this.environment.getProperty(source, defaultValue); } }
SpringPropertyModelHandler
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java
{ "start": 227857, "end": 249114 }
class ____ uses an upper bound on the generic @Test void compilerWithGenerics_12040_2() { expression = parser.parseExpression("payload/2"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(2); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(6))).isEqualTo(3); expression = parser.parseExpression("9/payload"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(9))).isEqualTo(1); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(3))).isEqualTo(3); expression = parser.parseExpression("payload+2"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(6); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(6))).isEqualTo(8); expression = parser.parseExpression("100+payload"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(104); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(10))).isEqualTo(110); expression = parser.parseExpression("payload-2"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(2); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(6))).isEqualTo(4); expression = parser.parseExpression("100-payload"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(96); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(10))).isEqualTo(90); expression = parser.parseExpression("payload*2"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(8); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(6))).isEqualTo(12); expression = parser.parseExpression("100*payload"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(400); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(10))).isEqualTo(1000); } // The other numeric operators @Test void compilerWithGenerics_12040_3() { expression = parser.parseExpression("payload >= 2"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(4), boolean.class)).isTrue(); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), boolean.class)).isFalse(); expression = parser.parseExpression("2 >= payload"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(5), boolean.class)).isFalse(); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), boolean.class)).isTrue(); expression = parser.parseExpression("payload > 2"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(4), boolean.class)).isTrue(); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), boolean.class)).isFalse(); expression = parser.parseExpression("2 > payload"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(5), boolean.class)).isFalse(); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), boolean.class)).isTrue(); expression = parser.parseExpression("payload <=2"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), boolean.class)).isTrue(); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(6), boolean.class)).isFalse(); expression = parser.parseExpression("2 <= payload"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), boolean.class)).isFalse(); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(6), boolean.class)).isTrue(); expression = parser.parseExpression("payload < 2"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), boolean.class)).isTrue(); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(6), boolean.class)).isFalse(); expression = parser.parseExpression("2 < payload"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), boolean.class)).isFalse(); assertCanCompile(expression); assertThat(expression.getValue(new GenericMessageTestHelper2<>(6), boolean.class)).isTrue(); } @Test void indexerMapAccessor_12045() { SpelParserConfiguration spc = new SpelParserConfiguration( SpelCompilerMode.IMMEDIATE,getClass().getClassLoader()); SpelExpressionParser sep = new SpelExpressionParser(spc); expression=sep.parseExpression("headers[command]"); MyMessage root = new MyMessage(); assertThat(expression.getValue(root)).isEqualTo("wibble"); // This next call was failing because the isCompilable check in Indexer // did not check on the key being compilable (and also generateCode in the // Indexer was missing the optimization that it didn't need necessarily // need to call generateCode for that accessor) assertThat(expression.getValue(root)).isEqualTo("wibble"); assertCanCompile(expression); // What about a map key that is an expression - ensure the getKey() is evaluated in the right scope expression=sep.parseExpression("headers[getKey()]"); assertThat(expression.getValue(root)).isEqualTo("wobble"); assertThat(expression.getValue(root)).isEqualTo("wobble"); expression=sep.parseExpression("list[getKey2()]"); assertThat(expression.getValue(root)).isEqualTo("wobble"); assertThat(expression.getValue(root)).isEqualTo("wobble"); expression = sep.parseExpression("ia[getKey2()]"); assertThat(expression.getValue(root)).isEqualTo(3); assertThat(expression.getValue(root)).isEqualTo(3); } @Test void elvisOperator_SPR15192() { SpelParserConfiguration configuration = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, null); Expression exp; exp = new SpelExpressionParser(configuration).parseExpression("bar()"); assertThat(exp.getValue(new Foo(), String.class)).isEqualTo("BAR"); assertCanCompile(exp); assertThat(exp.getValue(new Foo(), String.class)).isEqualTo("BAR"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("bar('baz')"); assertThat(exp.getValue(new Foo(), String.class)).isEqualTo("BAZ"); assertCanCompile(exp); assertThat(exp.getValue(new Foo(), String.class)).isEqualTo("BAZ"); assertIsCompiled(exp); StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("map", Collections.singletonMap("foo", "qux")); exp = new SpelExpressionParser(configuration).parseExpression("bar(#map['foo'])"); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("QUX"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("QUX"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("bar(#map['foo'] ?: 'qux')"); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("QUX"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("QUX"); assertIsCompiled(exp); // When the condition is a primitive exp = new SpelExpressionParser(configuration).parseExpression("3?:'foo'"); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertIsCompiled(exp); // When the condition is a double slot primitive exp = new SpelExpressionParser(configuration).parseExpression("3L?:'foo'"); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertIsCompiled(exp); // When the condition is an empty string exp = new SpelExpressionParser(configuration).parseExpression("''?:4L"); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("4"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("4"); assertIsCompiled(exp); // null condition exp = new SpelExpressionParser(configuration).parseExpression("null?:4L"); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("4"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("4"); assertIsCompiled(exp); // variable access returning primitive exp = new SpelExpressionParser(configuration).parseExpression("#x?:'foo'"); context.setVariable("x",50); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("50"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("50"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("#x?:'foo'"); context.setVariable("x",null); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertIsCompiled(exp); // variable access returning array exp = new SpelExpressionParser(configuration).parseExpression("#x?:'foo'"); context.setVariable("x",new int[]{1,2,3}); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("1,2,3"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("1,2,3"); assertIsCompiled(exp); } @Test void elvisOperator_SPR17214() { SpelParserConfiguration spc = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, null); SpelExpressionParser sep = new SpelExpressionParser(spc); RecordHolder rh = null; expression = sep.parseExpression("record.get('abc')?:record.put('abc',expression.someLong?.longValue())"); rh = new RecordHolder(); assertThat(expression.getValue(rh)).isNull(); assertThat(expression.getValue(rh)).isEqualTo(3L); assertCanCompile(expression); rh = new RecordHolder(); assertThat(expression.getValue(rh)).isNull(); assertThat(expression.getValue(rh)).isEqualTo(3L); expression = sep.parseExpression("record.get('abc')?:record.put('abc',3L.longValue())"); rh = new RecordHolder(); assertThat(expression.getValue(rh)).isNull(); assertThat(expression.getValue(rh)).isEqualTo(3L); assertCanCompile(expression); rh = new RecordHolder(); assertThat(expression.getValue(rh)).isNull(); assertThat(expression.getValue(rh)).isEqualTo(3L); expression = sep.parseExpression("record.get('abc')?:record.put('abc',3L.longValue())"); rh = new RecordHolder(); assertThat(expression.getValue(rh)).isNull(); assertThat(expression.getValue(rh)).isEqualTo(3L); assertCanCompile(expression); rh = new RecordHolder(); assertThat(expression.getValue(rh)).isNull(); assertThat(expression.getValue(rh)).isEqualTo(3L); expression = sep.parseExpression("record.get('abc')==null?record.put('abc',expression.someLong?.longValue()):null"); rh = new RecordHolder(); rh.expression.someLong=6L; assertThat(expression.getValue(rh)).isNull(); assertThat(rh.get("abc")).isEqualTo(6L); assertThat(expression.getValue(rh)).isNull(); assertCanCompile(expression); rh = new RecordHolder(); rh.expression.someLong=6L; assertThat(expression.getValue(rh)).isNull(); assertThat(rh.get("abc")).isEqualTo(6L); assertThat(expression.getValue(rh)).isNull(); } @Test void testNullComparison_SPR22358() { SpelParserConfiguration configuration = new SpelParserConfiguration(SpelCompilerMode.OFF, null); SpelExpressionParser parser = new SpelExpressionParser(configuration); StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setRootObject(new Reg(1)); verifyCompilationAndBehaviourWithNull("value>1", parser, ctx ); verifyCompilationAndBehaviourWithNull("value<1", parser, ctx ); verifyCompilationAndBehaviourWithNull("value>=1", parser, ctx ); verifyCompilationAndBehaviourWithNull("value<=1", parser, ctx ); verifyCompilationAndBehaviourWithNull2("value>value2", parser, ctx ); verifyCompilationAndBehaviourWithNull2("value<value2", parser, ctx ); verifyCompilationAndBehaviourWithNull2("value>=value2", parser, ctx ); verifyCompilationAndBehaviourWithNull2("value<=value2", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueD>1.0d", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueD<1.0d", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueD>=1.0d", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueD<=1.0d", parser, ctx ); verifyCompilationAndBehaviourWithNull2("valueD>valueD2", parser, ctx ); verifyCompilationAndBehaviourWithNull2("valueD<valueD2", parser, ctx ); verifyCompilationAndBehaviourWithNull2("valueD>=valueD2", parser, ctx ); verifyCompilationAndBehaviourWithNull2("valueD<=valueD2", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueL>1L", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueL<1L", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueL>=1L", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueL<=1L", parser, ctx ); verifyCompilationAndBehaviourWithNull2("valueL>valueL2", parser, ctx ); verifyCompilationAndBehaviourWithNull2("valueL<valueL2", parser, ctx ); verifyCompilationAndBehaviourWithNull2("valueL>=valueL2", parser, ctx ); verifyCompilationAndBehaviourWithNull2("valueL<=valueL2", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueF>1.0f", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueF<1.0f", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueF>=1.0f", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueF<=1.0f", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueF>valueF2", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueF<valueF2", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueF>=valueF2", parser, ctx ); verifyCompilationAndBehaviourWithNull("valueF<=valueF2", parser, ctx ); } private void verifyCompilationAndBehaviourWithNull(String expressionText, SpelExpressionParser parser, StandardEvaluationContext ctx) { Reg r = (Reg)ctx.getRootObject().getValue(); r.setValue2(1); // having a value in value2 fields will enable compilation to succeed, then can switch it to null SpelExpression fast = (SpelExpression) parser.parseExpression(expressionText); SpelExpression slow = (SpelExpression) parser.parseExpression(expressionText); fast.getValue(ctx); assertThat(fast.compileExpression()).isTrue(); r.setValue2(null); // try the numbers 0,1,2,null for (int i = 0; i < 4; i++) { r.setValue(i < 3 ? i : null); boolean slowResult = (Boolean)slow.getValue(ctx); boolean fastResult = (Boolean)fast.getValue(ctx); assertThat(fastResult).as("Differing results: expression=" + expressionText + " value=" + r.getValue() + " slow=" + slowResult + " fast="+fastResult).isEqualTo(slowResult); } } private void verifyCompilationAndBehaviourWithNull2(String expressionText, SpelExpressionParser parser, StandardEvaluationContext ctx) { SpelExpression fast = (SpelExpression) parser.parseExpression(expressionText); SpelExpression slow = (SpelExpression) parser.parseExpression(expressionText); fast.getValue(ctx); assertThat(fast.compileExpression()).isTrue(); Reg r = (Reg)ctx.getRootObject().getValue(); // try the numbers 0,1,2,null for (int i = 0; i < 4; i++) { r.setValue(i < 3 ? i : null); boolean slowResult = (Boolean)slow.getValue(ctx); boolean fastResult = (Boolean)fast.getValue(ctx); assertThat(fastResult).as("Differing results: expression=" + expressionText + " value=" + r.getValue() + " slow=" + slowResult + " fast="+fastResult).isEqualTo(slowResult); } } @Test void ternaryOperator_SPR15192() { SpelParserConfiguration configuration = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, null); Expression exp; StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("map", Collections.singletonMap("foo", "qux")); exp = new SpelExpressionParser(configuration).parseExpression("bar(#map['foo'] != null ? #map['foo'] : 'qux')"); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("QUX"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("QUX"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("3==3?3:'foo'"); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("3!=3?3:'foo'"); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertIsCompiled(exp); // When the condition is a double slot primitive exp = new SpelExpressionParser(configuration).parseExpression("3==3?3L:'foo'"); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("3!=3?3L:'foo'"); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertIsCompiled(exp); // When the condition is an empty string exp = new SpelExpressionParser(configuration).parseExpression("''==''?'abc':4L"); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("abc"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("abc"); assertIsCompiled(exp); // null condition exp = new SpelExpressionParser(configuration).parseExpression("3==3?null:4L"); assertThat(exp.getValue(context, new Foo(), String.class)).isNull(); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isNull(); assertIsCompiled(exp); // variable access returning primitive exp = new SpelExpressionParser(configuration).parseExpression("#x==#x?50:'foo'"); context.setVariable("x",50); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("50"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("50"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("#x!=#x?50:'foo'"); context.setVariable("x",null); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertIsCompiled(exp); // variable access returning array exp = new SpelExpressionParser(configuration).parseExpression("#x==#x?'1,2,3':'foo'"); context.setVariable("x",new int[]{1,2,3}); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("1,2,3"); assertCanCompile(exp); assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("1,2,3"); assertIsCompiled(exp); } @Test void repeatedCompilation() throws Exception { // Verifying that after a number of compilations, the classloaders // used to load the compiled expressions are discarded/replaced. // See SpelCompiler.loadClass() Field f = SpelExpression.class.getDeclaredField("compiledAst"); Set<Object> classloadersUsed = new HashSet<>(); for (int i = 0; i < 1500; i++) { // 1500 is greater than SpelCompiler.CLASSES_DEFINED_LIMIT expression = parser.parseExpression("4 + 5"); assertThat((int) expression.getValue(Integer.class)).isEqualTo(9); assertCanCompile(expression); f.setAccessible(true); CompiledExpression cEx = (CompiledExpression) f.get(expression); classloadersUsed.add(cEx.getClass().getClassLoader()); assertThat((int) expression.getValue(Integer.class)).isEqualTo(9); } assertThat(classloadersUsed.size()).isGreaterThan(1); } // Helper methods private SpelNodeImpl getAst() { SpelExpression spelExpression = (SpelExpression) expression; SpelNode ast = spelExpression.getAST(); return (SpelNodeImpl)ast; } private void assertCanCompile(Expression expression) { assertThat(SpelCompiler.compile(expression)) .as(() -> "Expression <%s> should be compilable" .formatted(((SpelExpression) expression).toStringAST())) .isTrue(); } private void assertCannotCompile(Expression expression) { assertThat(SpelCompiler.compile(expression)) .as(() -> "Expression <%s> should not be compilable" .formatted(((SpelExpression) expression).toStringAST())) .isFalse(); } private Expression parse(String expression) { return parser.parseExpression(expression); } private static void assertNotPublic(Class<?> clazz) { assertThat(Modifier.isPublic(clazz.getModifiers())).as("%s must be private", clazz.getName()).isFalse(); } // Nested types public
here