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
quarkusio__quarkus
extensions/security-webauthn/deployment/src/main/java/io/quarkus/security/webauthn/deployment/QuarkusSecurityWebAuthnProcessor.java
{ "start": 2280, "end": 5911 }
class ____ { @BuildStep public IndexDependencyBuildItem addTypesToJandex() { // needed by registerJacksonTypes() return new IndexDependencyBuildItem("com.webauthn4j", "webauthn4j-core"); } @BuildStep public void registerJacksonTypes(BuildProducer<ReflectiveHierarchyBuildItem> reflection) { reflection.produce( ReflectiveHierarchyBuildItem.builder(AuthenticatorAssertionResponse.class).build()); reflection.produce( ReflectiveHierarchyBuildItem.builder(AuthenticatorAttestationResponse.class).build()); reflection.produce(ReflectiveHierarchyBuildItem.builder(AuthenticationRequest.class).build()); reflection.produce(ReflectiveHierarchyBuildItem.builder(RegistrationRequest.class).build()); reflection.produce( ReflectiveHierarchyBuildItem.builder(PublicKeyCredentialCreationOptions.class).build()); reflection.produce( ReflectiveHierarchyBuildItem.builder(PublicKeyCredentialRequestOptions.class).build()); reflection.produce( ReflectiveHierarchyBuildItem.builder(PublicKeyCredentialRpEntity.class).build()); reflection.produce( ReflectiveHierarchyBuildItem.builder(PublicKeyCredentialUserEntity.class).build()); reflection.produce( ReflectiveHierarchyBuildItem.builder(PublicKeyCredentialParameters.class).build()); reflection.produce( ReflectiveHierarchyBuildItem.builder(PublicKeyCredentialType.class).build()); reflection.produce( ReflectiveHierarchyBuildItem.builder(PublicKeyCredential.class).build()); reflection.produce( ReflectiveHierarchyBuildItem.builder(AttestationObject.class).build()); reflection.produce( ReflectiveHierarchyBuildItem.builder(CollectedClientData.class).build()); } @BuildStep public void myBeans(BuildProducer<AdditionalBeanBuildItem> additionalBeans) { AdditionalBeanBuildItem.Builder builder = AdditionalBeanBuildItem.builder().setUnremovable(); builder.addBeanClass(WebAuthnSecurity.class) .addBeanClass(WebAuthnAuthenticatorStorage.class) .addBeanClass(WebAuthnTrustedIdentityProvider.class); additionalBeans.produce(builder.build()); } @Record(ExecutionTime.RUNTIME_INIT) @BuildStep public void setup( WebAuthnRecorder recorder, VertxWebRouterBuildItem vertxWebRouterBuildItem, BeanContainerBuildItem beanContainerBuildItem, NonApplicationRootPathBuildItem nonApplicationRootPathBuildItem) { recorder.setupRoutes(beanContainerBuildItem.getValue(), vertxWebRouterBuildItem.getHttpRouter(), nonApplicationRootPathBuildItem.getNonApplicationRootPath()); } @BuildStep @Record(ExecutionTime.RUNTIME_INIT) SyntheticBeanBuildItem initWebAuthnAuth( WebAuthnRecorder recorder) { return SyntheticBeanBuildItem.configure(WebAuthnAuthenticationMechanism.class) .types(HttpAuthenticationMechanism.class) .setRuntimeInit() .scope(Singleton.class) .supplier(recorder.setupWebAuthnAuthenticationMechanism()).done(); } @BuildStep List<HttpAuthMechanismAnnotationBuildItem> registerHttpAuthMechanismAnnotation() { return List.of( new HttpAuthMechanismAnnotationBuildItem(DotName.createSimple(WebAuthn.class), WebAuthn.AUTH_MECHANISM_SCHEME)); } public static
QuarkusSecurityWebAuthnProcessor
java
spring-projects__spring-security
crypto/src/test/java/org/springframework/security/crypto/password/AbstractPasswordEncoderValidationTests.java
{ "start": 956, "end": 1925 }
class ____ { private PasswordEncoder encoder; protected void setEncoder(PasswordEncoder encoder) { this.encoder = encoder; } protected <T extends PasswordEncoder> T getEncoder(Class<T> clazz) { return getEncoder(); } protected <T extends PasswordEncoder> T getEncoder() { return (T) this.encoder; } @Test void encodeWhenNullThenNull() { assertThat(this.encoder.encode(null)).isNull(); } @Test void matchesWhenEncodedPasswordNullThenFalse() { assertThat(this.encoder.matches("raw", null)).isFalse(); } @Test void matchesWhenEncodedPasswordEmptyThenFalse() { assertThat(this.encoder.matches("raw", "")).isFalse(); } @Test void matchesWhenRawPasswordNullThenFalse() { assertThat(this.encoder.matches(null, this.encoder.encode("password"))).isFalse(); } @Test void matchesWhenRawPasswordEmptyThenFalse() { assertThat(this.encoder.matches("", this.encoder.encode("password"))).isFalse(); } }
AbstractPasswordEncoderValidationTests
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/byte2darray/Byte2DArrayAssert_doesNotContain_at_Index_Test.java
{ "start": 1112, "end": 1556 }
class ____ extends Byte2DArrayAssertBaseTest { private final Index index = someIndex(); @Override protected Byte2DArrayAssert invoke_api_method() { return assertions.doesNotContain(new byte[] { 8, 9 }, index); } @Override protected void verify_internal_effects() { verify(arrays).assertDoesNotContain(getInfo(assertions), getActual(assertions), new byte[] { 8, 9 }, index); } }
Byte2DArrayAssert_doesNotContain_at_Index_Test
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/internal/JdbcLiteralFormatterBoolean.java
{ "start": 570, "end": 955 }
class ____<T> extends BasicJdbcLiteralFormatter<T> { public JdbcLiteralFormatterBoolean(JavaType<T> javaType) { super( javaType ); } @Override public void appendJdbcLiteral(SqlAppender appender, T value, Dialect dialect, WrapperOptions wrapperOptions) { dialect.appendBooleanValueString( appender, unwrap( value, Boolean.class, wrapperOptions ) ); } }
JdbcLiteralFormatterBoolean
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/session/ShoppingController.java
{ "start": 1035, "end": 2031 }
class ____ { private static final String ATTR_CART = "cart"; // <1> // end::class[] // tag::view[] @Get("/cart") @SessionValue(ATTR_CART) // <1> Cart viewCart(@SessionValue @Nullable Cart cart) { // <2> if (cart == null) { cart = new Cart(); } return cart; } // end::view[] // tag::add[] @Post("/cart/{name}") Cart addItem(Session session, @NotBlank String name) { // <2> Cart cart = session.get(ATTR_CART, Cart.class).orElseGet(() -> { // <3> Cart newCart = new Cart(); session.put(ATTR_CART, newCart); // <4> return newCart; }); cart.getItems().add(name); return cart; } // end::add[] // tag::clear[] @Post("/cart/clear") void clearCart(@Nullable Session session) { if (session != null) { session.remove(ATTR_CART); } } // end::clear[] // tag::endclass[] } // end::endclass[]
ShoppingController
java
apache__avro
lang/java/mapred/src/test/java/org/apache/avro/mapred/TestAvroInputFormat.java
{ "start": 1402, "end": 2780 }
class ____ { @TempDir public File DIR; private JobConf conf; private FileSystem fs; private Path inputDir; @BeforeEach public void setUp() throws Exception { conf = new JobConf(); fs = FileSystem.getLocal(conf); inputDir = new Path(DIR.getPath()); } @AfterEach public void tearDown() throws Exception { fs.delete(inputDir, true); } @SuppressWarnings("rawtypes") @Test void ignoreFilesWithoutExtension() throws Exception { fs.mkdirs(inputDir); Path avroFile = new Path(inputDir, "somefile.avro"); Path textFile = new Path(inputDir, "someotherfile.txt"); fs.create(avroFile).close(); fs.create(textFile).close(); FileInputFormat.setInputPaths(conf, inputDir); AvroInputFormat inputFormat = new AvroInputFormat(); FileStatus[] statuses = inputFormat.listStatus(conf); assertEquals(1, statuses.length); assertEquals("somefile.avro", statuses[0].getPath().getName()); conf.setBoolean(AvroInputFormat.IGNORE_FILES_WITHOUT_EXTENSION_KEY, false); statuses = inputFormat.listStatus(conf); assertEquals(2, statuses.length); Set<String> names = new HashSet<>(); names.add(statuses[0].getPath().getName()); names.add(statuses[1].getPath().getName()); assertTrue(names.contains("somefile.avro")); assertTrue(names.contains("someotherfile.txt")); } }
TestAvroInputFormat
java
quarkusio__quarkus
integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/GeneratedKubernetesResourcesBuildItemTest.java
{ "start": 2857, "end": 3514 }
class ____ extends ProdModeTestBuildStep { public CustomGeneratedKubernetesResourcesHandler(Map<String, Object> testContext) { super(testContext); } @Override public void execute(BuildContext context) { List<GeneratedKubernetesResourceBuildItem> k8sResources = context .consumeMulti(GeneratedKubernetesResourceBuildItem.class); for (GeneratedKubernetesResourceBuildItem bi : k8sResources) { context.produce(new GeneratedResourceBuildItem("dummy-" + bi.getName(), bi.getContent())); } } } }
CustomGeneratedKubernetesResourcesHandler
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQLDialect.java
{ "start": 32952, "end": 53281 }
enum ____! // Workaround for postgres bug #1453 return "cast(null as " + typeConfiguration.getDdlTypeRegistry().getDescriptor( sqlType ).getRawTypeName() + ")"; } @Override public String getSelectClauseNullString(SqlTypedMapping sqlType, TypeConfiguration typeConfiguration) { final DdlTypeRegistry ddlTypeRegistry = typeConfiguration.getDdlTypeRegistry(); final String castTypeName = ddlTypeRegistry .getDescriptor( sqlType.getJdbcMapping().getJdbcType().getDdlTypeCode() ) .getCastTypeName( sqlType.toSize(), (SqlExpressible) sqlType.getJdbcMapping(), ddlTypeRegistry ); // PostgreSQL assumes a plain null literal in the select statement to be of type text, // which can lead to issues in e.g. the union subclass strategy, so do a cast return "cast(null as " + castTypeName + ")"; } @Override public String quoteCollation(String collation) { return '\"' + collation + '\"'; } @Override public boolean supportsCommentOn() { return true; } @Override public boolean supportsCurrentTimestampSelection() { return true; } @Override public boolean isCurrentTimestampSelectStringCallable() { return false; } @Override public String getCurrentTimestampSelectString() { return "select now()"; } @Override public boolean supportsTupleCounts() { return true; } @Override public boolean supportsIsTrue() { return true; } @Override public boolean requiresParensForTupleDistinctCounts() { return true; } @Override public void appendBooleanValueString(SqlAppender appender, boolean bool) { appender.appendSql( bool ); } @Override public IdentifierHelper buildIdentifierHelper(IdentifierHelperBuilder builder, DatabaseMetaData metadata) throws SQLException { if ( metadata == null ) { builder.setUnquotedCaseStrategy( IdentifierCaseStrategy.LOWER ); builder.setQuotedCaseStrategy( IdentifierCaseStrategy.MIXED ); } return super.buildIdentifierHelper( builder, metadata ); } @Override public SqmMultiTableMutationStrategy getFallbackSqmMutationStrategy( EntityMappingType rootEntityDescriptor, RuntimeModelCreationContext runtimeModelCreationContext) { return new CteMutationStrategy( rootEntityDescriptor, runtimeModelCreationContext ); } @Override public SqmMultiTableInsertStrategy getFallbackSqmInsertStrategy( EntityMappingType rootEntityDescriptor, RuntimeModelCreationContext runtimeModelCreationContext) { return new CteInsertStrategy( rootEntityDescriptor, runtimeModelCreationContext ); } @Override public TemporaryTableStrategy getLocalTemporaryTableStrategy() { return StandardLocalTemporaryTableStrategy.INSTANCE; } @Override public SqlAstTranslatorFactory getSqlAstTranslatorFactory() { return new StandardSqlAstTranslatorFactory() { @Override protected <T extends JdbcOperation> SqlAstTranslator<T> buildTranslator( SessionFactoryImplementor sessionFactory, Statement statement) { return new PostgreSQLSqlAstTranslator<>( sessionFactory, statement ); } }; } @Override public ViolatedConstraintNameExtractor getViolatedConstraintNameExtractor() { return EXTRACTOR; } /** * Constraint-name extractor for Postgres constraint violation exceptions. * Originally contributed by Denny Bartelt. */ private static final ViolatedConstraintNameExtractor EXTRACTOR = new TemplatedViolatedConstraintNameExtractor( sqle -> { final String sqlState = extractSqlState( sqle ); return sqlState == null ? null : switch ( parseInt( sqlState ) ) { case 23505, 23514, 23503 -> // UNIQUE, CHECK, OR FOREIGN KEY VIOLATION extractUsingTemplate( "constraint \"", "\"", sqle.getMessage() ); case 23502 -> // NOT NULL VIOLATION extractUsingTemplate( "column \"", "\"", sqle.getMessage() ); default -> null; }; } ); @Override public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return (sqlException, message, sql) -> { final String sqlState = extractSqlState( sqlException ); return sqlState == null ? null : switch ( sqlState ) { case "40P01" -> // DEADLOCK DETECTED new LockAcquisitionException( message, sqlException, sql ); case "55P03" -> // LOCK NOT AVAILABLE //TODO: should we check that the message is "canceling statement due to lock timeout" // and return LockAcquisitionException if it is not? new LockTimeoutException( message, sqlException, sql ); case "57014" -> // QUERY CANCELLED new QueryTimeoutException( message, sqlException, sql ); default -> null; }; }; } @Override public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException { // Register the type of the out param - PostgreSQL uses Types.OTHER statement.registerOutParameter( col++, Types.OTHER ); return col; } @Override public ResultSet getResultSet(CallableStatement ps) throws SQLException { ps.execute(); return (ResultSet) ps.getObject( 1 ); } // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Override public boolean supportsLobValueChangePropagation() { return false; } @Override public boolean supportsUnboundedLobLocatorMaterialization() { return false; } @Override public SelectItemReferenceStrategy getGroupBySelectItemReferenceStrategy() { return SelectItemReferenceStrategy.POSITION; } @Override public CallableStatementSupport getCallableStatementSupport() { return PostgreSQLCallableStatementSupport.INSTANCE; } @Override public ResultSet getResultSet(CallableStatement statement, int position) throws SQLException { if ( position != 1 ) { throw new UnsupportedOperationException( "PostgreSQL only supports REF_CURSOR parameters as the first parameter" ); } return (ResultSet) statement.getObject( 1 ); } @Override public ResultSet getResultSet(CallableStatement statement, String name) throws SQLException { throw new UnsupportedOperationException( "PostgreSQL only supports accessing REF_CURSOR parameters by position" ); } @Override public boolean qualifyIndexName() { return false; } @Override public IdentityColumnSupport getIdentityColumnSupport() { return PostgreSQLIdentityColumnSupport.INSTANCE; } @Override public NationalizationSupport getNationalizationSupport() { return NationalizationSupport.IMPLICIT; } @Override public int getMaxIdentifierLength() { return 63; } @Override public boolean supportsUserDefinedTypes() { return true; } @Override public boolean supportsStandardArrays() { return true; } @Override public boolean supportsJdbcConnectionLobCreation(DatabaseMetaData databaseMetaData) { return false; } @Override public boolean supportsMaterializedLobAccess() { // Prefer using text and bytea over oid (LOB), because oid is very restricted. // If someone really wants a type bigger than 1GB, they should ask for it by using @Lob explicitly return false; } @Override public boolean supportsTemporalLiteralOffset() { return true; } @Override public void appendDatetimeFormat(SqlAppender appender, String format) { appender.appendSql( datetimeFormat( format ).result() ); } public Replacer datetimeFormat(String format) { return OracleDialect.datetimeFormat( format, true, false ) .replace("SSSSSS", "US") .replace("SSSSS", "US") .replace("SSSS", "US") .replace("SSS", "MS") .replace("SS", "MS") .replace("S", "MS") //use ISO day in week, as per DateTimeFormatter .replace("ee", "ID") .replace("e", "fmID") //TZR is TZ in Postgres .replace("zzz", "TZ") .replace("zz", "TZ") .replace("z", "TZ") .replace("xxx", "OF") .replace("xx", "OF") .replace("x", "OF"); } @Override public String translateExtractField(TemporalUnit unit) { return switch (unit) { //WEEK means the ISO week number on Postgres case DAY_OF_MONTH -> "day"; case DAY_OF_YEAR -> "doy"; case DAY_OF_WEEK -> "dow"; default -> super.translateExtractField( unit ); }; } @Override public AggregateSupport getAggregateSupport() { return PostgreSQLAggregateSupport.valueOf( this ); } @Override public void appendBinaryLiteral(SqlAppender appender, byte[] bytes) { appender.appendSql( "bytea '\\x" ); PrimitiveByteArrayJavaType.INSTANCE.appendString( appender, bytes ); appender.appendSql( '\'' ); } @Override public void appendDateTimeLiteral( SqlAppender appender, TemporalAccessor temporalAccessor, @SuppressWarnings("deprecation") TemporalType precision, TimeZone jdbcTimeZone) { switch ( precision ) { case DATE: appender.appendSql( "date '" ); appendAsDate( appender, temporalAccessor ); appender.appendSql( '\'' ); break; case TIME: if ( supportsTemporalLiteralOffset() && temporalAccessor.isSupported( ChronoField.OFFSET_SECONDS ) ) { appender.appendSql( "time with time zone '" ); appendAsTime( appender, temporalAccessor, true, jdbcTimeZone ); } else { appender.appendSql( "time '" ); appendAsLocalTime( appender, temporalAccessor ); } appender.appendSql( '\'' ); break; case TIMESTAMP: if ( supportsTemporalLiteralOffset() && temporalAccessor.isSupported( ChronoField.OFFSET_SECONDS ) ) { appender.appendSql( "timestamp with time zone '" ); appendAsTimestampWithMicros( appender, temporalAccessor, true, jdbcTimeZone ); appender.appendSql( '\'' ); } else { appender.appendSql( "timestamp '" ); appendAsTimestampWithMicros( appender, temporalAccessor, false, jdbcTimeZone ); appender.appendSql( '\'' ); } break; default: throw new IllegalArgumentException(); } } @Override public void appendDateTimeLiteral( SqlAppender appender, Date date, @SuppressWarnings("deprecation") TemporalType precision, TimeZone jdbcTimeZone) { switch ( precision ) { case DATE: appender.appendSql( "date '" ); appendAsDate( appender, date ); appender.appendSql( '\'' ); break; case TIME: appender.appendSql( "time with time zone '" ); appendAsTime( appender, date, jdbcTimeZone ); appender.appendSql( '\'' ); break; case TIMESTAMP: appender.appendSql( "timestamp with time zone '" ); appendAsTimestampWithMicros( appender, date, jdbcTimeZone ); appender.appendSql( '\'' ); break; default: throw new IllegalArgumentException(); } } @Override public void appendDateTimeLiteral( SqlAppender appender, Calendar calendar, @SuppressWarnings("deprecation") TemporalType precision, TimeZone jdbcTimeZone) { switch ( precision ) { case DATE: appender.appendSql( "date '" ); appendAsDate( appender, calendar ); appender.appendSql( '\'' ); break; case TIME: appender.appendSql( "time with time zone '" ); appendAsTime( appender, calendar, jdbcTimeZone ); appender.appendSql( '\'' ); break; case TIMESTAMP: appender.appendSql( "timestamp with time zone '" ); appendAsTimestampWithMillis( appender, calendar, jdbcTimeZone ); appender.appendSql( '\'' ); break; default: throw new IllegalArgumentException(); } } @Override public LockingSupport getLockingSupport() { return PostgreSQLLockingSupport.LOCKING_SUPPORT; } private String withTimeout(String lockString, Timeout timeout) { return switch (timeout.milliseconds()) { case Timeouts.NO_WAIT_MILLI -> supportsNoWait() ? lockString + " nowait" : lockString; case Timeouts.SKIP_LOCKED_MILLI -> supportsSkipLocked() ? lockString + " skip locked" : lockString; default -> lockString; }; } @Override public String getWriteLockString(Timeout timeout) { return withTimeout( getForUpdateString(), timeout ); } @Override public String getWriteLockString(String aliases, Timeout timeout) { return withTimeout( getForUpdateString( aliases ), timeout ); } @Override public String getReadLockString(Timeout timeout) { return withTimeout(" for share", timeout ); } @Override public String getReadLockString(String aliases, Timeout timeout) { return withTimeout(" for share of " + aliases, timeout ); } private String withTimeout(String lockString, int timeout) { return switch (timeout) { case Timeouts.NO_WAIT_MILLI -> supportsNoWait() ? lockString + " nowait" : lockString; case Timeouts.SKIP_LOCKED_MILLI -> supportsSkipLocked() ? lockString + " skip locked" : lockString; default -> lockString; }; } @Override public String getWriteLockString(int timeout) { return withTimeout( getForUpdateString(), timeout ); } @Override public String getWriteLockString(String aliases, int timeout) { return withTimeout( getForUpdateString( aliases ), timeout ); } @Override public String getReadLockString(int timeout) { return withTimeout(" for share", timeout ); } @Override public String getReadLockString(String aliases, int timeout) { return withTimeout(" for share of " + aliases, timeout ); } @Override public String getForUpdateString() { return " for no key update"; } @Override public String getForUpdateNowaitString() { return supportsNoWait() ? " for update nowait" : getForUpdateString(); } @Override public String getForUpdateNowaitString(String aliases) { return supportsNoWait() ? " for update of " + aliases + " nowait" : getForUpdateString(aliases); } @Override public String getForUpdateSkipLockedString() { return supportsSkipLocked() ? " for update skip locked" : getForUpdateString(); } @Override public String getForUpdateSkipLockedString(String aliases) { return supportsSkipLocked() ? " for update of " + aliases + " skip locked" : getForUpdateString( aliases ); } @Override public boolean supportsInsertReturning() { return true; } @Override public boolean supportsOffsetInSubquery() { return true; } @Override public boolean supportsWindowFunctions() { return true; } @Override public boolean supportsLateral() { return true; } @Override public boolean supportsRecursiveCTE() { return true; } @Override public boolean supportsFetchClause(FetchClauseType type) { return switch (type) { case ROWS_ONLY -> true; case PERCENT_ONLY, PERCENT_WITH_TIES -> false; case ROWS_WITH_TIES -> true; }; } @Override public FunctionalDependencyAnalysisSupport getFunctionalDependencyAnalysisSupport() { return FunctionalDependencyAnalysisSupportImpl.TABLE_REFERENCE; } @Override public void augmentRecognizedTableTypes(List<String> tableTypesList) { super.augmentRecognizedTableTypes( tableTypesList ); tableTypesList.add( "MATERIALIZED VIEW" ); //PostgreSQL 10 and later adds support for Partition table. tableTypesList.add( "PARTITIONED TABLE" ); } @Override public void contributeTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { super.contributeTypes(typeContributions, serviceRegistry); contributePostgreSQLTypes(typeContributions, serviceRegistry); } /** * Allow for extension points to override this only */ protected void contributePostgreSQLTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { final JdbcTypeRegistry jdbcTypeRegistry = typeContributions.getTypeConfiguration() .getJdbcTypeRegistry(); // For discussion of BLOB support in Postgres, as of 8.4, see: // http://jdbc.postgresql.org/documentation/84/binary-data.html // For how this affects Hibernate, see: // http://in.relation.to/15492.lace // Force BLOB binding. Otherwise, byte[] fields annotated // with @Lob will attempt to use // BlobTypeDescriptor.PRIMITIVE_ARRAY_BINDING. Since the // dialect uses oid for Blobs, byte arrays cannot be used. jdbcTypeRegistry.addDescriptor( Types.BLOB, BlobJdbcType.BLOB_BINDING ); jdbcTypeRegistry.addDescriptor( Types.CLOB, ClobJdbcType.CLOB_BINDING ); // Don't use this type due to https://github.com/pgjdbc/pgjdbc/issues/2862 //jdbcTypeRegistry.addDescriptor( TimestampUtcAsOffsetDateTimeJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptor( XmlJdbcType.INSTANCE ); if ( driverKind == PostgreSQLDriverKind.PG_JDBC ) { if ( PgJdbcHelper.isUsable( serviceRegistry ) ) { jdbcTypeRegistry.addDescriptorIfAbsent( PgJdbcHelper.getInetJdbcType( serviceRegistry ) ); jdbcTypeRegistry.addDescriptorIfAbsent( PgJdbcHelper.getIntervalJdbcType( serviceRegistry ) ); jdbcTypeRegistry.addDescriptorIfAbsent( PgJdbcHelper.getStructJdbcType( serviceRegistry ) ); jdbcTypeRegistry.addDescriptorIfAbsent( PgJdbcHelper.getJsonbJdbcType( serviceRegistry ) ); jdbcTypeRegistry.addTypeConstructorIfAbsent( PgJdbcHelper.getJsonbArrayJdbcType( serviceRegistry ) ); } else { jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingInetJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingIntervalSecondJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLStructCastingJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingJsonJdbcType.JSONB_INSTANCE ); jdbcTypeRegistry.addTypeConstructorIfAbsent( PostgreSQLCastingJsonArrayJdbcTypeConstructor.JSONB_INSTANCE ); } } else { jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingInetJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingIntervalSecondJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLStructCastingJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingJsonJdbcType.JSONB_INSTANCE ); jdbcTypeRegistry.addTypeConstructorIfAbsent( PostgreSQLCastingJsonArrayJdbcTypeConstructor.JSONB_INSTANCE ); } // PostgreSQL requires a custom binder for binding untyped nulls as VARBINARY typeContributions.contributeJdbcType( ObjectNullAsBinaryTypeJdbcType.INSTANCE ); // Until we remove StandardBasicTypes, we have to keep this typeContributions.contributeType( new JavaObjectType( ObjectNullAsBinaryTypeJdbcType.INSTANCE, typeContributions.getTypeConfiguration() .getJavaTypeRegistry() .resolveDescriptor( Object.class ) ) ); jdbcTypeRegistry.addDescriptor( PostgreSQLEnumJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptor( PostgreSQLOrdinalEnumJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptor( PostgreSQLUUIDJdbcType.INSTANCE ); // Replace the standard array constructor jdbcTypeRegistry.addTypeConstructor( PostgreSQLArrayJdbcTypeConstructor.INSTANCE ); } @Override public UniqueDelegate getUniqueDelegate() { return uniqueDelegate; } @Override public Exporter<Table> getTableExporter() { return postgresqlTableExporter; } /** * @return {@code true}, but only because we can "batch" truncate */ @Override public boolean canBatchTruncate() { return true; } // disabled foreign key constraints still prevent 'truncate table' // (these would help if we used 'delete' instead of 'truncate') @Override public String rowId(String rowId) { return "ctid"; } @Override public int rowIdSqlType() { return OTHER; } @Override public String getQueryHintString(String sql, String hints) { return "/*+ " + hints + " */ " + sql; } @Override public String addSqlHintOrComment(String sql, QueryOptions queryOptions, boolean commentsEnabled) { // PostgreSQL's extension pg_hint_plan needs the hint to be the first comment if ( commentsEnabled && queryOptions.getComment() != null ) { sql = prependComment( sql, queryOptions.getComment() ); } if ( queryOptions.getDatabaseHints() != null && !queryOptions.getDatabaseHints().isEmpty() ) { sql = getQueryHintString( sql, queryOptions.getDatabaseHints() ); } return sql; } @Override public MutationOperation createOptionalTableUpdateOperation( EntityMutationTarget mutationTarget, OptionalTableUpdate optionalTableUpdate, SessionFactoryImplementor factory) { if ( supportsMerge ) { return new PostgreSQLSqlAstTranslator<>( factory, optionalTableUpdate ) .createMergeOperation( optionalTableUpdate ); } else { return super.createOptionalTableUpdateOperation( mutationTarget, optionalTableUpdate, factory ); } } @Override public ParameterMarkerStrategy getNativeParameterMarkerStrategy() { return parameterRenderer; } private static
types
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/target/AbstractPoolingTargetSource.java
{ "start": 2102, "end": 2378 }
interface ____ order to force subclasses to implement a {@link #destroy()} * method, closing down their object pool. * * @author Rod Johnson * @author Juergen Hoeller * @see #getTarget * @see #releaseTarget * @see #destroy */ @SuppressWarnings("serial") public abstract
in
java
apache__camel
components/camel-twilio/src/generated/java/org/apache/camel/component/twilio/internal/SipDomainIpAccessControlListMappingApiMethod.java
{ "start": 710, "end": 3381 }
enum ____ implements ApiMethod { CREATOR( com.twilio.rest.api.v2010.account.sip.domain.IpAccessControlListMappingCreator.class, "creator", arg("pathDomainSid", String.class), arg("ipAccessControlListSid", String.class)), CREATOR_1( com.twilio.rest.api.v2010.account.sip.domain.IpAccessControlListMappingCreator.class, "creator", arg("pathAccountSid", String.class), arg("pathDomainSid", String.class), arg("ipAccessControlListSid", String.class)), DELETER( com.twilio.rest.api.v2010.account.sip.domain.IpAccessControlListMappingDeleter.class, "deleter", arg("pathDomainSid", String.class), arg("pathSid", String.class)), DELETER_1( com.twilio.rest.api.v2010.account.sip.domain.IpAccessControlListMappingDeleter.class, "deleter", arg("pathAccountSid", String.class), arg("pathDomainSid", String.class), arg("pathSid", String.class)), FETCHER( com.twilio.rest.api.v2010.account.sip.domain.IpAccessControlListMappingFetcher.class, "fetcher", arg("pathDomainSid", String.class), arg("pathSid", String.class)), FETCHER_1( com.twilio.rest.api.v2010.account.sip.domain.IpAccessControlListMappingFetcher.class, "fetcher", arg("pathAccountSid", String.class), arg("pathDomainSid", String.class), arg("pathSid", String.class)), READER( com.twilio.rest.api.v2010.account.sip.domain.IpAccessControlListMappingReader.class, "reader", arg("pathDomainSid", String.class)), READER_1( com.twilio.rest.api.v2010.account.sip.domain.IpAccessControlListMappingReader.class, "reader", arg("pathAccountSid", String.class), arg("pathDomainSid", String.class)); private final ApiMethod apiMethod; SipDomainIpAccessControlListMappingApiMethod(Class<?> resultType, String name, ApiMethodArg... args) { this.apiMethod = new ApiMethodImpl(IpAccessControlListMapping.class, resultType, name, args); } @Override public String getName() { return apiMethod.getName(); } @Override public Class<?> getResultType() { return apiMethod.getResultType(); } @Override public List<String> getArgNames() { return apiMethod.getArgNames(); } @Override public List<String> getSetterArgNames() { return apiMethod.getSetterArgNames(); } @Override public List<Class<?>> getArgTypes() { return apiMethod.getArgTypes(); } @Override public Method getMethod() { return apiMethod.getMethod(); } }
SipDomainIpAccessControlListMappingApiMethod
java
apache__logging-log4j2
log4j-api-test/src/test/java/org/apache/logging/log4j/LogManagerTest.java
{ "start": 1568, "end": 1679 }
class ____ { final Logger LOGGER = LogManager.getLogger(InnerByClass.class); } static
InnerByClass
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDeadNodeDetection.java
{ "start": 16747, "end": 17653 }
class ____ { private Queue<Object> queue = new LinkedBlockingQueue<Object>(1); public boolean addToQueue() { return queue.offer(new Object()); } public Object removeFromQueue() { return queue.poll(); } public void sync() { while (removeFromQueue() == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } } private void startWaitForDeadNodeThread(DFSClient dfsClient, int size) { new SubjectInheritingThread(() -> { DeadNodeDetector deadNodeDetector = dfsClient.getClientContext().getDeadNodeDetector(); while (deadNodeDetector.clearAndGetDetectedDeadNodes().size() != size) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } addToQueue(); }).start(); } } }
DefaultCoordination
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/SqmTypedNode.java
{ "start": 460, "end": 982 }
interface ____<T> extends SqmNode, SqmExpressibleAccessor<T>, SqmVisitableNode { /** * The Java type descriptor for this node. */ default @Nullable JavaType<T> getNodeJavaType() { final SqmExpressible<T> nodeType = getNodeType(); return nodeType == null ? null : nodeType.getExpressibleJavaType(); } @Override default @Nullable SqmBindableType<T> getExpressible() { return getNodeType(); } @Nullable SqmBindableType<T> getNodeType(); @Override SqmTypedNode<T> copy(SqmCopyContext context); }
SqmTypedNode
java
quarkusio__quarkus
devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/extension-codestarts/websockets-codestart/java/src/main/java/org/acme/StartWebSocket.java
{ "start": 523, "end": 1179 }
class ____ { @OnOpen public void onOpen(Session session, @PathParam("name") String name) { System.out.println("onOpen> " + name); } @OnClose public void onClose(Session session, @PathParam("name") String name) { System.out.println("onClose> " + name); } @OnError public void onError(Session session, @PathParam("name") String name, Throwable throwable) { System.out.println("onError> " + name + ": " + throwable); } @OnMessage public void onMessage(String message, @PathParam("name") String name) { System.out.println("onMessage> " + name + ": " + message); } }
StartWebSocket
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_515/Issue515Test.java
{ "start": 459, "end": 647 }
class ____ { @ProcessorTest @WithClasses( { Issue515Mapper.class, Source.class, Target.class } ) public void shouldIgnoreParanthesesOpenInStringDefinition() { } }
Issue515Test
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java
{ "start": 9381, "end": 9787 }
class ____ extends GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory { private DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler(); @Override public DefaultWebSecurityExpressionHandler getBean() { this.handler.setDefaultRolePrefix(this.rolePrefix); return this.handler; } } }
DefaultWebSecurityExpressionHandlerBeanFactory
java
elastic__elasticsearch
x-pack/plugin/ccr/src/internalClusterTest/java/org/elasticsearch/xpack/ccr/CcrRetentionLeaseIT.java
{ "start": 4145, "end": 4223 }
class ____ extends CcrIntegTestCase { public static final
CcrRetentionLeaseIT
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/handler/predicate/PathRoutePredicateFactoryTests.java
{ "start": 2313, "end": 5752 }
class ____ extends BaseWebClientTests { @Test public void pathRouteWorks() { expectPathRoute("/abc/123/function", "www.path.org", "path_test"); } // FIXME: 5.0.0 trailing slash @Disabled @Test public void trailingSlashReturns404() { // since the configuration does not allow the trailing / to match this should fail testClient.get() .uri("/abc/123/function/") .header(HttpHeaders.HOST, "www.path.org") .exchange() .expectStatus() .isNotFound(); } @Test public void defaultPathRouteWorks() { expectPathRoute("/get", "www.thispathshouldnotmatch.org", "default_path_to_httpbin"); } private void expectPathRoute(String uri, String host, String routeId) { testClient.get() .uri(uri) .header(HttpHeaders.HOST, host) .exchange() .expectStatus() .isOk() .expectHeader() .valueEquals(HANDLER_MAPPER_HEADER, RoutePredicateHandlerMapping.class.getSimpleName()) .expectHeader() .valueEquals(ROUTE_ID_HEADER, routeId); } @Test public void mulitPathRouteWorks() { expectPathRoute("/anything/multi11", "www.pathmulti.org", "path_multi"); expectPathRoute("/anything/multi22", "www.pathmulti.org", "path_multi"); expectPathRoute("/anything/multi33", "www.pathmulti.org", "default_path_to_httpbin"); } @Test public void mulitPathDslRouteWorks() { expectPathRoute("/anything/multidsl1", "www.pathmultidsl.org", "path_multi_dsl"); expectPathRoute("/anything/multidsl2", "www.pathmultidsl.org", "default_path_to_httpbin"); expectPathRoute("/anything/multidsl3", "www.pathmultidsl.org", "path_multi_dsl"); } @Test // @Disabled public void pathRouteWorksWithPercent() { testClient.get() .uri("/abc/123%/function") .header(HttpHeaders.HOST, "www.path.org") .exchange() .expectStatus() .isOk() .expectHeader() .valueEquals(HANDLER_MAPPER_HEADER, RoutePredicateHandlerMapping.class.getSimpleName()) .expectHeader() .valueEquals(ROUTE_ID_HEADER, "path_test"); } @Test public void pathRouteWorksWithRegex() { testClient.get() .uri("/regex/123") .header(HttpHeaders.HOST, "www.pathregex.org") .exchange() .expectStatus() .isOk() .expectHeader() .valueEquals(HANDLER_MAPPER_HEADER, RoutePredicateHandlerMapping.class.getSimpleName()) .expectHeader() .valueEquals(ROUTE_ID_HEADER, "path_regex"); } @Test public void matchOptionalTrailingSeparatorCopiedToMatchTrailingSlash() { Config config = new Config().setPatterns(Arrays.asList("patternA", "patternB")).setMatchTrailingSlash(false); assertThat(config.isMatchTrailingSlash()).isEqualTo(false); } @Test public void toStringFormat() { Config config = new Config().setPatterns(Arrays.asList("patternA", "patternB")).setMatchTrailingSlash(false); Predicate predicate = new PathRoutePredicateFactory(new WebFluxProperties()).apply(config); assertThat(predicate.toString()).contains("patternA").contains("patternB").contains("false"); } @Test public void toStringFormatMatchTrailingSlashTrue() { Config config = new Config().setPatterns(Arrays.asList("patternA", "patternB")).setMatchTrailingSlash(true); Predicate<ServerWebExchange> predicate = new PathRoutePredicateFactory(new WebFluxProperties()).apply(config); assertThat(predicate.toString()).contains("patternA").contains("patternB").contains("true"); } @EnableAutoConfiguration @SpringBootConfiguration @Import(DefaultTestConfig.class) public static
PathRoutePredicateFactoryTests
java
grpc__grpc-java
interop-testing/src/generated/main/grpc/io/grpc/testing/integration/MetricsServiceGrpc.java
{ "start": 16694, "end": 16864 }
class ____ extends MetricsServiceBaseDescriptorSupplier { MetricsServiceFileDescriptorSupplier() {} } private static final
MetricsServiceFileDescriptorSupplier
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/operators/CrossTaskTest.java
{ "start": 1649, "end": 18751 }
class ____ extends DriverTestBase<CrossFunction<Record, Record, Record>> { private static final long CROSS_MEM = 1024 * 1024; private final double cross_frac; private final CountingOutputCollector output = new CountingOutputCollector(); CrossTaskTest(ExecutionConfig config) { super(config, CROSS_MEM, 0); cross_frac = (double) CROSS_MEM / this.getMemoryManager().getMemorySize(); } @TestTemplate void testBlock1CrossTask() { int keyCnt1 = 10; int valCnt1 = 1; int keyCnt2 = 100; int valCnt2 = 4; final int expCnt = keyCnt1 * valCnt1 * keyCnt2 * valCnt2; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt1, valCnt1, false)); addInput(new UniformRecordGenerator(keyCnt2, valCnt2, false)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_BLOCKED_OUTER_FIRST); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); try { testDriver(testTask, MockCrossStub.class); } catch (Exception e) { e.printStackTrace(); fail("Test failed due to an exception."); } assertThat(this.output.getNumberOfRecords()) .withFailMessage("Wrong result size.") .isEqualTo(expCnt); } @TestTemplate void testBlock2CrossTask() { int keyCnt1 = 10; int valCnt1 = 1; int keyCnt2 = 100; int valCnt2 = 4; final int expCnt = keyCnt1 * valCnt1 * keyCnt2 * valCnt2; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt1, valCnt1, false)); addInput(new UniformRecordGenerator(keyCnt2, valCnt2, false)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_BLOCKED_OUTER_SECOND); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); try { testDriver(testTask, MockCrossStub.class); } catch (Exception e) { e.printStackTrace(); fail("Test failed due to an exception."); } assertThat(this.output.getNumberOfRecords()) .withFailMessage("Wrong result size.") .isEqualTo(expCnt); } @TestTemplate void testFailingBlockCrossTask() { int keyCnt1 = 10; int valCnt1 = 1; int keyCnt2 = 100; int valCnt2 = 4; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt1, valCnt1, false)); addInput(new UniformRecordGenerator(keyCnt2, valCnt2, false)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_BLOCKED_OUTER_FIRST); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); assertThatThrownBy(() -> testDriver(testTask, MockFailingCrossStub.class)) .isInstanceOf(ExpectedTestException.class); } @TestTemplate void testFailingBlockCrossTask2() { int keyCnt1 = 10; int valCnt1 = 1; int keyCnt2 = 100; int valCnt2 = 4; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt1, valCnt1, false)); addInput(new UniformRecordGenerator(keyCnt2, valCnt2, false)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_BLOCKED_OUTER_SECOND); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); assertThatThrownBy(() -> testDriver(testTask, MockFailingCrossStub.class)) .isInstanceOf(ExpectedTestException.class); } @TestTemplate void testStream1CrossTask() { int keyCnt1 = 10; int valCnt1 = 1; int keyCnt2 = 100; int valCnt2 = 4; final int expCnt = keyCnt1 * valCnt1 * keyCnt2 * valCnt2; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt1, valCnt1, false)); addInput(new UniformRecordGenerator(keyCnt2, valCnt2, false)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_STREAMED_OUTER_FIRST); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); try { testDriver(testTask, MockCrossStub.class); } catch (Exception e) { e.printStackTrace(); fail("Test failed due to an exception."); } assertThat(this.output.getNumberOfRecords()) .withFailMessage("Wrong result size.") .isEqualTo(expCnt); } @TestTemplate void testStream2CrossTask() { int keyCnt1 = 10; int valCnt1 = 1; int keyCnt2 = 100; int valCnt2 = 4; final int expCnt = keyCnt1 * valCnt1 * keyCnt2 * valCnt2; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt1, valCnt1, false)); addInput(new UniformRecordGenerator(keyCnt2, valCnt2, false)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_STREAMED_OUTER_SECOND); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); try { testDriver(testTask, MockCrossStub.class); } catch (Exception e) { e.printStackTrace(); fail("Test failed due to an exception."); } assertThat(this.output.getNumberOfRecords()) .withFailMessage("Wrong result size.") .isEqualTo(expCnt); } @TestTemplate void testFailingStreamCrossTask() { int keyCnt1 = 10; int valCnt1 = 1; int keyCnt2 = 100; int valCnt2 = 4; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt1, valCnt1, false)); addInput(new UniformRecordGenerator(keyCnt2, valCnt2, false)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_STREAMED_OUTER_FIRST); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); assertThatThrownBy(() -> testDriver(testTask, MockFailingCrossStub.class)) .isInstanceOf(ExpectedTestException.class); } @TestTemplate void testFailingStreamCrossTask2() { int keyCnt1 = 10; int valCnt1 = 1; int keyCnt2 = 100; int valCnt2 = 4; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt1, valCnt1, false)); addInput(new UniformRecordGenerator(keyCnt2, valCnt2, false)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_STREAMED_OUTER_SECOND); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); assertThatThrownBy(() -> testDriver(testTask, MockFailingCrossStub.class)) .isInstanceOf(ExpectedTestException.class); } @TestTemplate void testStreamEmptyInnerCrossTask() { int keyCnt1 = 10; int valCnt1 = 1; int keyCnt2 = 0; int valCnt2 = 0; final int expCnt = keyCnt1 * valCnt1 * keyCnt2 * valCnt2; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt1, valCnt1, false)); addInput(new UniformRecordGenerator(keyCnt2, valCnt2, false)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_STREAMED_OUTER_FIRST); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); try { testDriver(testTask, MockCrossStub.class); } catch (Exception e) { e.printStackTrace(); fail("Test failed due to an exception."); } assertThat(this.output.getNumberOfRecords()) .withFailMessage("Wrong result size.") .isEqualTo(expCnt); } @TestTemplate void testStreamEmptyOuterCrossTask() { int keyCnt1 = 10; int valCnt1 = 1; int keyCnt2 = 0; int valCnt2 = 0; final int expCnt = keyCnt1 * valCnt1 * keyCnt2 * valCnt2; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt1, valCnt1, false)); addInput(new UniformRecordGenerator(keyCnt2, valCnt2, false)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_STREAMED_OUTER_SECOND); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); try { testDriver(testTask, MockCrossStub.class); } catch (Exception e) { e.printStackTrace(); fail("Test failed due to an exception."); } assertThat(this.output.getNumberOfRecords()) .withFailMessage("Wrong result size.") .isEqualTo(expCnt); } @TestTemplate void testBlockEmptyInnerCrossTask() { int keyCnt1 = 10; int valCnt1 = 1; int keyCnt2 = 0; int valCnt2 = 0; final int expCnt = keyCnt1 * valCnt1 * keyCnt2 * valCnt2; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt1, valCnt1, false)); addInput(new UniformRecordGenerator(keyCnt2, valCnt2, false)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_BLOCKED_OUTER_FIRST); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); try { testDriver(testTask, MockCrossStub.class); } catch (Exception e) { e.printStackTrace(); fail("Test failed due to an exception."); } assertThat(this.output.getNumberOfRecords()) .withFailMessage("Wrong result size.") .isEqualTo(expCnt); } @TestTemplate void testBlockEmptyOuterCrossTask() { int keyCnt1 = 10; int valCnt1 = 1; int keyCnt2 = 0; int valCnt2 = 0; final int expCnt = keyCnt1 * valCnt1 * keyCnt2 * valCnt2; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt1, valCnt1, false)); addInput(new UniformRecordGenerator(keyCnt2, valCnt2, false)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_BLOCKED_OUTER_SECOND); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); try { testDriver(testTask, MockCrossStub.class); } catch (Exception e) { e.printStackTrace(); fail("Test failed due to an exception."); } assertThat(this.output.getNumberOfRecords()) .withFailMessage("Wrong result size.") .isEqualTo(expCnt); } @TestTemplate void testCancelBlockCrossTaskInit() { int keyCnt = 10; int valCnt = 1; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt, valCnt, false)); addInput(new DelayingInfinitiveInputIterator(100)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_BLOCKED_OUTER_FIRST); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); final AtomicBoolean success = new AtomicBoolean(false); Thread taskRunner = new Thread() { @Override public void run() { try { testDriver(testTask, MockCrossStub.class); success.set(true); } catch (Exception ie) { ie.printStackTrace(); } } }; taskRunner.start(); TaskCancelThread tct = new TaskCancelThread(1, taskRunner, this); tct.start(); try { tct.join(); taskRunner.join(); } catch (InterruptedException ie) { fail("Joining threads failed"); } assertThat(success) .withFailMessage("Exception was thrown despite proper canceling.") .isTrue(); } @TestTemplate void testCancelBlockCrossTaskCrossing() { int keyCnt = 10; int valCnt = 1; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt, valCnt, false)); addInput(new DelayingInfinitiveInputIterator(100)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_BLOCKED_OUTER_SECOND); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); final AtomicBoolean success = new AtomicBoolean(false); Thread taskRunner = new Thread() { @Override public void run() { try { testDriver(testTask, MockCrossStub.class); success.set(true); } catch (Exception ie) { ie.printStackTrace(); } } }; taskRunner.start(); TaskCancelThread tct = new TaskCancelThread(1, taskRunner, this); tct.start(); try { tct.join(); taskRunner.join(); } catch (InterruptedException ie) { fail("Joining threads failed"); } assertThat(success) .withFailMessage("Exception was thrown despite proper canceling.") .isTrue(); } @TestTemplate void testCancelStreamCrossTaskInit() { int keyCnt = 10; int valCnt = 1; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt, valCnt, false)); addInput(new DelayingInfinitiveInputIterator(100)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_STREAMED_OUTER_FIRST); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); final AtomicBoolean success = new AtomicBoolean(false); Thread taskRunner = new Thread() { @Override public void run() { try { testDriver(testTask, MockCrossStub.class); success.set(true); } catch (Exception ie) { ie.printStackTrace(); } } }; taskRunner.start(); TaskCancelThread tct = new TaskCancelThread(1, taskRunner, this); tct.start(); try { tct.join(); taskRunner.join(); } catch (InterruptedException ie) { fail("Joining threads failed"); } assertThat(success) .withFailMessage("Exception was thrown despite proper canceling.") .isTrue(); } @TestTemplate void testCancelStreamCrossTaskCrossing() { int keyCnt = 10; int valCnt = 1; setOutput(this.output); addInput(new UniformRecordGenerator(keyCnt, valCnt, false)); addInput(new DelayingInfinitiveInputIterator(100)); getTaskConfig().setDriverStrategy(DriverStrategy.NESTEDLOOP_STREAMED_OUTER_SECOND); getTaskConfig().setRelativeMemoryDriver(cross_frac); final CrossDriver<Record, Record, Record> testTask = new CrossDriver<>(); final AtomicBoolean success = new AtomicBoolean(false); Thread taskRunner = new Thread() { @Override public void run() { try { testDriver(testTask, MockCrossStub.class); success.set(true); } catch (Exception ie) { ie.printStackTrace(); } } }; taskRunner.start(); TaskCancelThread tct = new TaskCancelThread(1, taskRunner, this); tct.start(); try { tct.join(); taskRunner.join(); } catch (InterruptedException ie) { fail("Joining threads failed"); } assertThat(success) .withFailMessage("Exception was thrown despite proper canceling.") .isTrue(); } public static final
CrossTaskTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/validation/beanvalidation/SpringValidatorAdapterTests.java
{ "start": 2254, "end": 11263 }
class ____ { private final Validator nativeValidator = Validation.buildDefaultValidatorFactory().getValidator(); private final SpringValidatorAdapter validatorAdapter = new SpringValidatorAdapter(nativeValidator); private final StaticMessageSource messageSource = new StaticMessageSource(); @BeforeEach void setupSpringValidatorAdapter() { messageSource.addMessage("Size", Locale.ENGLISH, "Size of {0} must be between {2} and {1}"); messageSource.addMessage("Same", Locale.ENGLISH, "{2} must be same value as {1}"); messageSource.addMessage("password", Locale.ENGLISH, "Password"); messageSource.addMessage("confirmPassword", Locale.ENGLISH, "Password(Confirm)"); } @Test void testUnwrap() { Validator nativeValidator = validatorAdapter.unwrap(Validator.class); assertThat(nativeValidator).isSameAs(this.nativeValidator); } @Test // SPR-13406 public void testNoStringArgumentValue() throws Exception { TestBean testBean = new TestBean(); testBean.setPassword("pass"); testBean.setConfirmPassword("pass"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); assertThat(errors.getFieldErrorCount("password")).isEqualTo(1); assertThat(errors.getFieldValue("password")).isEqualTo("pass"); FieldError error = errors.getFieldError("password"); assertThat(error).isNotNull(); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Size of Password must be between 8 and 128"); assertThat(error.contains(ConstraintViolation.class)).isTrue(); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password"); assertThat(SerializationTestUtils.serializeAndDeserialize(error.toString())).isEqualTo(error.toString()); } @Test // SPR-13406 public void testApplyMessageSourceResolvableToStringArgumentValueWithResolvedLogicalFieldName() throws Exception { TestBean testBean = new TestBean(); testBean.setPassword("password"); testBean.setConfirmPassword("PASSWORD"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); assertThat(errors.getFieldErrorCount("password")).isEqualTo(1); assertThat(errors.getFieldValue("password")).isEqualTo("password"); FieldError error = errors.getFieldError("password"); assertThat(error).isNotNull(); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Password must be same value as Password(Confirm)"); assertThat(error.contains(ConstraintViolation.class)).isTrue(); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password"); assertThat(SerializationTestUtils.serializeAndDeserialize(error.toString())).isEqualTo(error.toString()); } @Test // SPR-13406 public void testApplyMessageSourceResolvableToStringArgumentValueWithUnresolvedLogicalFieldName() { TestBean testBean = new TestBean(); testBean.setEmail("test@example.com"); testBean.setConfirmEmail("TEST@EXAMPLE.IO"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); assertThat(errors.getFieldErrorCount("email")).isEqualTo(1); assertThat(errors.getFieldValue("email")).isEqualTo("test@example.com"); assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1); FieldError error1 = errors.getFieldError("email"); FieldError error2 = errors.getFieldError("confirmEmail"); assertThat(error1).isNotNull(); assertThat(error2).isNotNull(); assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail"); assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required"); assertThat(error1.contains(ConstraintViolation.class)).isTrue(); assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email"); assertThat(error2.contains(ConstraintViolation.class)).isTrue(); assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail"); } @Test // SPR-15123 public void testApplyMessageSourceResolvableToStringArgumentValueWithAlwaysUseMessageFormat() { messageSource.setAlwaysUseMessageFormat(true); TestBean testBean = new TestBean(); testBean.setEmail("test@example.com"); testBean.setConfirmEmail("TEST@EXAMPLE.IO"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); assertThat(errors.getFieldErrorCount("email")).isEqualTo(1); assertThat(errors.getFieldValue("email")).isEqualTo("test@example.com"); assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1); FieldError error1 = errors.getFieldError("email"); FieldError error2 = errors.getFieldError("confirmEmail"); assertThat(error1).isNotNull(); assertThat(error2).isNotNull(); assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail"); assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required"); assertThat(error1.contains(ConstraintViolation.class)).isTrue(); assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email"); assertThat(error2.contains(ConstraintViolation.class)).isTrue(); assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail"); } @Test void testPatternMessage() { TestBean testBean = new TestBean(); testBean.setEmail("X"); testBean.setConfirmEmail("X"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); assertThat(errors.getFieldErrorCount("email")).isEqualTo(1); assertThat(errors.getFieldValue("email")).isEqualTo("X"); FieldError error = errors.getFieldError("email"); assertThat(error).isNotNull(); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).contains("[\\w.'-]{1,}@[\\w.'-]{1,}"); assertThat(error.contains(ConstraintViolation.class)).isTrue(); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email"); } @Test // SPR-16177 public void testWithList() { Parent parent = new Parent(); parent.setName("Parent whit list"); parent.getChildList().addAll(createChildren(parent)); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(parent, "parent"); validatorAdapter.validate(parent, errors); assertThat(errors.getErrorCount()).isGreaterThan(0); } @Test // SPR-16177 public void testWithSet() { Parent parent = new Parent(); parent.setName("Parent with set"); parent.getChildSet().addAll(createChildren(parent)); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(parent, "parent"); validatorAdapter.validate(parent, errors); assertThat(errors.getErrorCount()).isGreaterThan(0); } private List<Child> createChildren(Parent parent) { Child child1 = new Child(); child1.setName("Child1"); child1.setAge(null); child1.setParent(parent); Child child2 = new Child(); child2.setName(null); child2.setAge(17); child2.setParent(parent); return Arrays.asList(child1, child2); } @Test // SPR-15839 public void testListElementConstraint() { BeanWithListElementConstraint bean = new BeanWithListElementConstraint(); bean.setProperty(Arrays.asList("no", "element", "can", "be", null)); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(bean, "bean"); validatorAdapter.validate(bean, errors); assertThat(errors.getFieldErrorCount("property[4]")).isEqualTo(1); assertThat(errors.getFieldValue("property[4]")).isNull(); } @Test // SPR-15839 public void testMapValueConstraint() { Map<String, String> property = new HashMap<>(); property.put("no value can be", null); BeanWithMapEntryConstraint bean = new BeanWithMapEntryConstraint(); bean.setProperty(property); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(bean, "bean"); validatorAdapter.validate(bean, errors); assertThat(errors.getFieldErrorCount("property[no value can be]")).isEqualTo(1); assertThat(errors.getFieldValue("property[no value can be]")).isNull(); } @Test // SPR-15839 public void testMapEntryConstraint() { Map<String, String> property = new HashMap<>(); property.put(null, null); BeanWithMapEntryConstraint bean = new BeanWithMapEntryConstraint(); bean.setProperty(property); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(bean, "bean"); validatorAdapter.validate(bean, errors); assertThat(errors.hasFieldErrors("property[]")).isTrue(); assertThat(errors.getFieldValue("property[]")).isNull(); } @Same(field = "password", comparingField = "confirmPassword") @Same(field = "email", comparingField = "confirmEmail") static
SpringValidatorAdapterTests
java
bumptech__glide
library/src/main/java/com/bumptech/glide/manager/RequestTracker.java
{ "start": 379, "end": 484 }
class ____ tracking, canceling, and restarting in progress, completed, and failed requests. * * <p>This
for
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/TestJsonSerialize3.java
{ "start": 769, "end": 1369 }
class ____ { @JsonSerialize(contentUsing = FooToBarSerializer.class) List<String> list; } /* /********************************************************** /* Test methods /********************************************************** */ @Test public void testCustomContentSerializer() throws Exception { ObjectMapper m = new ObjectMapper(); MyObject object = new MyObject(); object.list = Arrays.asList("foo"); String json = m.writeValueAsString(object); assertEquals("{\"list\":[\"bar\"]}", json); } }
MyObject
java
spring-projects__spring-boot
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/net/protocol/jar/JarUrlClassLoader.java
{ "start": 3195, "end": 6995 }
class ____ being found */ protected final void definePackageIfNecessary(String className) { if (className.startsWith("java.")) { return; } int lastDot = className.lastIndexOf('.'); if (lastDot >= 0) { String packageName = className.substring(0, lastDot); if (getDefinedPackage(packageName) == null) { try { definePackage(className, packageName); } catch (IllegalArgumentException ex) { tolerateRaceConditionDueToBeingParallelCapable(ex, packageName); } } } } private void definePackage(String className, String packageName) { if (this.undefinablePackages.contains(packageName)) { return; } String packageEntryName = packageName.replace('.', '/') + "/"; String classEntryName = className.replace('.', '/') + ".class"; for (URL url : this.urls) { try { JarFile jarFile = getJarFile(url); if (jarFile != null) { if (hasEntry(jarFile, classEntryName) && hasEntry(jarFile, packageEntryName) && jarFile.getManifest() != null) { definePackage(packageName, jarFile.getManifest(), url); return; } } } catch (IOException ex) { // Ignore } } this.undefinablePackages.add(packageName); } private void tolerateRaceConditionDueToBeingParallelCapable(IllegalArgumentException ex, String packageName) throws AssertionError { if (getDefinedPackage(packageName) == null) { // This should never happen as the IllegalArgumentException indicates that the // package has already been defined and, therefore, getDefinedPackage(name) // should not have returned null. throw new AssertionError( "Package %s has already been defined but it could not be found".formatted(packageName), ex); } } private boolean hasEntry(JarFile jarFile, String name) { return (jarFile instanceof NestedJarFile nestedJarFile) ? nestedJarFile.hasEntry(name) : jarFile.getEntry(name) != null; } private JarFile getJarFile(URL url) throws IOException { JarFile jarFile = this.jarFiles.get(url); if (jarFile != null) { return jarFile; } URLConnection connection = url.openConnection(); if (!(connection instanceof JarURLConnection)) { return null; } connection.setUseCaches(false); jarFile = ((JarURLConnection) connection).getJarFile(); synchronized (this.jarFiles) { JarFile previous = this.jarFiles.putIfAbsent(url, jarFile); if (previous != null) { jarFile.close(); jarFile = previous; } } return jarFile; } /** * Clear any caches. This method is called reflectively by * {@code ClearCachesApplicationListener}. */ public void clearCache() { Handler.clearCache(); org.springframework.boot.loader.net.protocol.nested.Handler.clearCache(); try { clearJarFiles(); } catch (IOException ex) { // Ignore } for (URL url : this.urls) { if (isJarUrl(url)) { clearCache(url); } } } private void clearCache(URL url) { try { URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection jarUrlConnection) { clearCache(jarUrlConnection); } } catch (IOException ex) { // Ignore } } private void clearCache(JarURLConnection connection) throws IOException { JarFile jarFile = connection.getJarFile(); if (jarFile instanceof NestedJarFile nestedJarFile) { nestedJarFile.clearCache(); } } private boolean isJarUrl(URL url) { return "jar".equals(url.getProtocol()); } @Override public void close() throws IOException { super.close(); clearJarFiles(); } private void clearJarFiles() throws IOException { synchronized (this.jarFiles) { for (JarFile jarFile : this.jarFiles.values()) { jarFile.close(); } this.jarFiles.clear(); } } /** * {@link Enumeration} that uses fast connections. */ private static
name
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/domain/SpecificationComposition.java
{ "start": 1361, "end": 4584 }
interface ____ extends Serializable { @Nullable Predicate combine(CriteriaBuilder builder, Predicate lhs, Predicate rhs); } static <T> Specification<T> composed(@Nullable Specification<T> lhs, @Nullable Specification<T> rhs, Combiner combiner) { return (root, query, builder) -> { Predicate thisPredicate = toPredicate(lhs, root, query, builder); Predicate otherPredicate = toPredicate(rhs, root, query, builder); if (thisPredicate == null) { return otherPredicate; } return otherPredicate == null ? thisPredicate : combiner.combine(builder, thisPredicate, otherPredicate); }; } private static <T> @Nullable Predicate toPredicate(@Nullable Specification<T> specification, Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) { return specification == null ? null : specification.toPredicate(root, query, builder); } @Contract("_, _, !null -> new") @SuppressWarnings("NullAway") static <T> DeleteSpecification<T> composed(@Nullable DeleteSpecification<T> lhs, @Nullable DeleteSpecification<T> rhs, Combiner combiner) { return (root, query, builder) -> { Predicate thisPredicate = toPredicate(lhs, root, query, builder); Predicate otherPredicate = toPredicate(rhs, root, query, builder); if (thisPredicate == null) { return otherPredicate; } return otherPredicate == null ? thisPredicate : combiner.combine(builder, thisPredicate, otherPredicate); }; } private static <T> @Nullable Predicate toPredicate(@Nullable DeleteSpecification<T> specification, Root<T> root, @Nullable CriteriaDelete<T> delete, CriteriaBuilder builder) { return specification == null || delete == null ? null : specification.toPredicate(root, delete, builder); } static <T> UpdateSpecification<T> composed(@Nullable UpdateSpecification<T> lhs, @Nullable UpdateSpecification<T> rhs, Combiner combiner) { return (root, query, builder) -> { Predicate thisPredicate = toPredicate(lhs, root, query, builder); Predicate otherPredicate = toPredicate(rhs, root, query, builder); if (thisPredicate == null) { return otherPredicate; } return otherPredicate == null ? thisPredicate : combiner.combine(builder, thisPredicate, otherPredicate); }; } private static <T> @Nullable Predicate toPredicate(@Nullable UpdateSpecification<T> specification, Root<T> root, CriteriaUpdate<T> update, CriteriaBuilder builder) { return specification == null ? null : specification.toPredicate(root, update, builder); } static <T> PredicateSpecification<T> composed(PredicateSpecification<T> lhs, PredicateSpecification<T> rhs, Combiner combiner) { return (root, builder) -> { Predicate thisPredicate = toPredicate(lhs, root, builder); Predicate otherPredicate = toPredicate(rhs, root, builder); if (thisPredicate == null) { return otherPredicate; } return otherPredicate == null ? thisPredicate : combiner.combine(builder, thisPredicate, otherPredicate); }; } private static <T> @Nullable Predicate toPredicate(@Nullable PredicateSpecification<T> specification, From<?, T> from, CriteriaBuilder builder) { return specification == null ? null : specification.toPredicate(from, builder); } }
Combiner
java
apache__kafka
tools/src/main/java/org/apache/kafka/tools/DelegationTokenCommand.java
{ "start": 2191, "end": 9310 }
class ____ { public static void main(String... args) { Exit.exit(mainNoExit(args)); } static int mainNoExit(String... args) { try { execute(args); return 0; } catch (TerseException e) { System.err.println(e.getMessage()); return 1; } catch (Throwable e) { System.err.println(e.getMessage()); System.err.println(Utils.stackTrace(e)); return 1; } } static void execute(String... args) throws Exception { DelegationTokenCommandOptions opts = new DelegationTokenCommandOptions(args); CommandLineUtils.maybePrintHelpOrVersion(opts, "This tool helps to create, renew, expire, or describe delegation tokens."); // should have exactly one action long numberOfActions = Stream.of(opts.hasCreateOpt(), opts.hasRenewOpt(), opts.hasExpireOpt(), opts.hasDescribeOpt()).filter(b -> b).count(); if (numberOfActions != 1) { CommandLineUtils.printUsageAndExit(opts.parser, "Command must include exactly one action: --create, --renew, --expire or --describe"); } opts.checkArgs(); try (Admin adminClient = createAdminClient(opts)) { if (opts.hasCreateOpt()) { createToken(adminClient, opts); } else if (opts.hasRenewOpt()) { renewToken(adminClient, opts); } else if (opts.hasExpireOpt()) { expireToken(adminClient, opts); } else if (opts.hasDescribeOpt()) { describeToken(adminClient, opts); } } } public static DelegationToken createToken(Admin adminClient, DelegationTokenCommandOptions opts) throws ExecutionException, InterruptedException { List<KafkaPrincipal> renewerPrincipals = getPrincipals(opts, opts.renewPrincipalsOpt); long maxLifeTimeMs = opts.maxLifeTime(); System.out.println("Calling create token operation with renewers :" + renewerPrincipals + " , max-life-time-period :" + maxLifeTimeMs); CreateDelegationTokenOptions createDelegationTokenOptions = new CreateDelegationTokenOptions().maxLifetimeMs(maxLifeTimeMs).renewers(renewerPrincipals); List<KafkaPrincipal> ownerPrincipals = getPrincipals(opts, opts.ownerPrincipalsOpt); if (!ownerPrincipals.isEmpty()) { createDelegationTokenOptions.owner(ownerPrincipals.get(0)); } CreateDelegationTokenResult createResult = adminClient.createDelegationToken(createDelegationTokenOptions); DelegationToken token = createResult.delegationToken().get(); System.out.println("Created delegation token with tokenId : " + token.tokenInfo().tokenId()); printToken(List.of(token)); return token; } private static void printToken(List<DelegationToken> tokens) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm"); System.out.printf("%n%-15s %-30s %-15s %-15s %-25s %-15s %-15s %-15s%n", "TOKENID", "HMAC", "OWNER", "REQUESTER", "RENEWERS", "ISSUEDATE", "EXPIRYDATE", "MAXDATE"); for (DelegationToken token : tokens) { TokenInformation tokenInfo = token.tokenInfo(); System.out.printf("%n%-15s %-30s %-15s %-15s %-25s %-15s %-15s %-15s%n", tokenInfo.tokenId(), token.hmacAsBase64String(), tokenInfo.owner(), tokenInfo.tokenRequester(), tokenInfo.renewersAsString(), dateFormat.format(tokenInfo.issueTimestamp()), dateFormat.format(tokenInfo.expiryTimestamp()), dateFormat.format(tokenInfo.maxTimestamp())); } } private static List<KafkaPrincipal> getPrincipals(DelegationTokenCommandOptions opts, OptionSpec<String> principalOptionSpec) { List<KafkaPrincipal> principals = new ArrayList<>(); if (opts.options.has(principalOptionSpec)) { for (String e : opts.options.valuesOf(principalOptionSpec)) principals.add(SecurityUtils.parseKafkaPrincipal(e.trim())); } return principals; } public static Long renewToken(Admin adminClient, DelegationTokenCommandOptions opts) throws ExecutionException, InterruptedException { String hmac = opts.hmac(); long renewTimePeriodMs = opts.renewTimePeriod(); System.out.println("Calling renew token operation with hmac :" + hmac + " , renew-time-period :" + renewTimePeriodMs); RenewDelegationTokenResult renewResult = adminClient.renewDelegationToken(Base64.getDecoder().decode(hmac), new RenewDelegationTokenOptions().renewTimePeriodMs(renewTimePeriodMs)); Long expiryTimeStamp = renewResult.expiryTimestamp().get(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm"); System.out.printf("Completed renew operation. New expiry date : %s", dateFormat.format(expiryTimeStamp)); return expiryTimeStamp; } public static void expireToken(Admin adminClient, DelegationTokenCommandOptions opts) throws ExecutionException, InterruptedException { String hmac = opts.hmac(); long expiryTimePeriodMs = opts.expiryTimePeriod(); System.out.println("Calling expire token operation with hmac :" + hmac + " , expire-time-period :" + expiryTimePeriodMs); ExpireDelegationTokenResult renewResult = adminClient.expireDelegationToken(Base64.getDecoder().decode(hmac), new ExpireDelegationTokenOptions().expiryTimePeriodMs(expiryTimePeriodMs)); Long expiryTimeStamp = renewResult.expiryTimestamp().get(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm"); System.out.printf("Completed expire operation. New expiry date : %s", dateFormat.format(expiryTimeStamp)); } public static List<DelegationToken> describeToken(Admin adminClient, DelegationTokenCommandOptions opts) throws ExecutionException, InterruptedException { List<KafkaPrincipal> ownerPrincipals = getPrincipals(opts, opts.ownerPrincipalsOpt); if (ownerPrincipals.isEmpty()) { System.out.println("Calling describe token operation for current user."); } else { System.out.printf("Calling describe token operation for owners: %s%n", ownerPrincipals); } DescribeDelegationTokenResult describeResult = adminClient.describeDelegationToken(new DescribeDelegationTokenOptions().owners(ownerPrincipals)); List<DelegationToken> tokens = describeResult.delegationTokens().get(); System.out.printf("Total number of tokens : %d", tokens.size()); printToken(tokens); return tokens; } private static Admin createAdminClient(DelegationTokenCommandOptions opts) throws IOException { Properties props = Utils.loadProps(opts.options.valueOf(opts.commandConfigOpt)); props.put("bootstrap.servers", opts.options.valueOf(opts.bootstrapServerOpt)); return Admin.create(props); } static
DelegationTokenCommand
java
apache__dubbo
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ChangeTelnet.java
{ "start": 1356, "end": 3257 }
class ____ implements BaseCommand { public static final AttributeKey<String> SERVICE_KEY = AttributeKey.valueOf("telnet.service"); private final DubboProtocol dubboProtocol; public ChangeTelnet(FrameworkModel frameworkModel) { this.dubboProtocol = DubboProtocol.getDubboProtocol(frameworkModel); } @Override public String execute(CommandContext commandContext, String[] args) { Channel channel = commandContext.getRemote(); if (ArrayUtils.isEmpty(args)) { return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService"; } String message = args[0]; StringBuilder buf = new StringBuilder(); if ("/".equals(message) || "..".equals(message)) { String service = channel.attr(SERVICE_KEY).getAndRemove(); buf.append("Cancelled default service ").append(service).append('.'); } else { boolean found = false; for (Exporter<?> exporter : dubboProtocol.getExporters()) { if (message.equals(exporter.getInvoker().getInterface().getSimpleName()) || message.equals(exporter.getInvoker().getInterface().getName()) || message.equals(exporter.getInvoker().getUrl().getPath()) || message.equals(exporter.getInvoker().getUrl().getServiceKey())) { found = true; break; } } if (found) { channel.attr(SERVICE_KEY).set(message); buf.append("Used the ") .append(message) .append(" as default.\r\nYou can cancel default service by command: cd /"); } else { buf.append("No such service ").append(message); } } return buf.toString(); } }
ChangeTelnet
java
elastic__elasticsearch
libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedModulePath.java
{ "start": 5554, "end": 5686 }
class ____ services files. record ScanResult(Set<String> classFiles, Set<String> serviceFiles) {} // Scans a given path for
and
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/EvalOperator.java
{ "start": 5743, "end": 5936 }
interface ____ extends Releasable { /** * A Factory for creating ExpressionEvaluators. This <strong>must</strong> * be thread safe. */
ExpressionEvaluator
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/DoublePredicateAssert.java
{ "start": 900, "end": 3082 }
class ____ extends AbstractPredicateLikeAssert<DoublePredicateAssert, DoublePredicate, Double> { public static DoublePredicateAssert assertThatDoublePredicate(DoublePredicate actual) { return new DoublePredicateAssert(actual); } public DoublePredicateAssert(DoublePredicate actual) { super(actual, toPredicate(actual), DoublePredicateAssert.class); } private static Predicate<Double> toPredicate(DoublePredicate actual) { return actual != null ? actual::test : null; } /** * Verifies that {@link DoublePredicate} evaluates all the given values to {@code true}. * <p> * Example : * <pre><code class='java'> DoublePredicate tallSize = size -&gt; size &gt; 1.90; * * // assertion succeeds: * assertThat(tallSize).accepts(1.95, 2.00, 2.05); * * // assertion fails: * assertThat(tallSize).accepts(1.85, 1.95, 2.05);</code></pre> * * @param values values that the actual {@code Predicate} should accept. * @return this assertion object. * @throws AssertionError if the actual {@code Predicate} does not accept all given values. */ public DoublePredicateAssert accepts(double... values) { if (values.length == 1) return acceptsInternal(values[0]); return acceptsAllInternal(DoubleStream.of(values).boxed().collect(Collectors.toList())); } /** * Verifies that {@link DoublePredicate} evaluates all the given values to {@code false}. * <p> * Example : * <pre><code class='java'> DoublePredicate tallSize = size -&gt; size &gt; 1.90; * * // assertion succeeds: * assertThat(tallSize).rejects(1.75, 1.80, 1.85); * * // assertion fails because of 1.90 size: * assertThat(tallSize).rejects(1.80, 1.85, 1.90);</code></pre> * * @param values values that the actual {@code Predicate} should reject. * @return this assertion object. * @throws AssertionError if the actual {@code Predicate} accepts one of the given values. */ public DoublePredicateAssert rejects(double... values) { if (values.length == 1) return rejectsInternal(values[0]); return rejectsAllInternal(DoubleStream.of(values).boxed().collect(Collectors.toList())); } }
DoublePredicateAssert
java
apache__camel
components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
{ "start": 2180, "end": 2531 }
class ____ implements RemoteFileOperations<FTPFile> { protected final Logger log = LoggerFactory.getLogger(getClass()); protected final FTPClient client; protected final FTPClientConfig clientConfig; protected FtpEndpoint<FTPFile> endpoint; protected FtpClientActivityListener clientActivityListener; private static
FtpOperations
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTaskRegistrarTests.java
{ "start": 1114, "end": 3220 }
class ____ { private static final Runnable no_op = () -> {}; private final ScheduledTaskRegistrar taskRegistrar = new ScheduledTaskRegistrar(); @BeforeEach void preconditions() { assertThat(this.taskRegistrar.getTriggerTaskList()).isEmpty(); assertThat(this.taskRegistrar.getCronTaskList()).isEmpty(); assertThat(this.taskRegistrar.getFixedRateTaskList()).isEmpty(); assertThat(this.taskRegistrar.getFixedDelayTaskList()).isEmpty(); } @Test void getTriggerTasks() { TriggerTask mockTriggerTask = mock(); this.taskRegistrar.setTriggerTasksList(Collections.singletonList(mockTriggerTask)); assertThat(this.taskRegistrar.getTriggerTaskList()).containsExactly(mockTriggerTask); } @Test void getCronTasks() { CronTask mockCronTask = mock(); this.taskRegistrar.setCronTasksList(Collections.singletonList(mockCronTask)); assertThat(this.taskRegistrar.getCronTaskList()).containsExactly(mockCronTask); } @Test void getFixedRateTasks() { IntervalTask mockFixedRateTask = mock(); this.taskRegistrar.setFixedRateTasksList(Collections.singletonList(mockFixedRateTask)); assertThat(this.taskRegistrar.getFixedRateTaskList()).containsExactly(mockFixedRateTask); } @Test void getFixedDelayTasks() { IntervalTask mockFixedDelayTask = mock(); this.taskRegistrar.setFixedDelayTasksList(Collections.singletonList(mockFixedDelayTask)); assertThat(this.taskRegistrar.getFixedDelayTaskList()).containsExactly(mockFixedDelayTask); } @Test void addCronTaskWithValidExpression() { this.taskRegistrar.addCronTask(no_op, "* * * * * ?"); assertThat(this.taskRegistrar.getCronTaskList()).hasSize(1); } @Test void addCronTaskWithInvalidExpression() { assertThatIllegalArgumentException() .isThrownBy(() -> this.taskRegistrar.addCronTask(no_op, "* * *")) .withMessage("Cron expression must consist of 6 fields (found 3 in \"* * *\")"); } @Test void addCronTaskWithDisabledExpression() { this.taskRegistrar.addCronTask(no_op, ScheduledTaskRegistrar.CRON_DISABLED); assertThat(this.taskRegistrar.getCronTaskList()).isEmpty(); } }
ScheduledTaskRegistrarTests
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/LegacyKeyedProcessOperator.java
{ "start": 3870, "end": 4913 }
class ____ extends ProcessFunction<IN, OUT>.Context { private final TimerService timerService; private StreamRecord<IN> element; ContextImpl(ProcessFunction<IN, OUT> function, TimerService timerService) { function.super(); this.timerService = checkNotNull(timerService); } @Override public Long timestamp() { checkState(element != null); if (element.hasTimestamp()) { return element.getTimestamp(); } else { return null; } } @Override public TimerService timerService() { return timerService; } @Override public <X> void output(OutputTag<X> outputTag, X value) { if (outputTag == null) { throw new IllegalArgumentException("OutputTag must not be null."); } output.collect(outputTag, new StreamRecord<>(value, element.getTimestamp())); } } private
ContextImpl
java
FasterXML__jackson-core
src/test/java/tools/jackson/core/unittest/write/PrettyPrinterTest.java
{ "start": 594, "end": 13146 }
class ____ extends MinimalPrettyPrinter { @Override public void writeEndObject(JsonGenerator jg, int nrOfEntries) { jg.writeRaw("("+nrOfEntries+")}"); } @Override public void writeEndArray(JsonGenerator jg, int nrOfValues) { jg.writeRaw("("+nrOfValues+")]"); } } /* /********************************************************** /* Test methods /********************************************************** */ private final JsonFactory JSON_F = newStreamFactory(); @Test void objectCount() throws Exception { final String EXP = "{\"x\":{\"a\":1,\"b\":2(2)}(1)}"; for (int i = 0; i < 2; ++i) { boolean useBytes = (i > 0); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); StringWriter sw = new StringWriter(); ObjectWriteContext ppContext = new ObjectWriteContext.Base() { @Override public PrettyPrinter getPrettyPrinter() { return new CountPrinter(); } }; JsonGenerator gen = useBytes ? JSON_F.createGenerator(ppContext, bytes) : JSON_F.createGenerator(ppContext, sw); gen.writeStartObject(); gen.writeName("x"); gen.writeStartObject(); gen.writeNumberProperty("a", 1); gen.writeNumberProperty("b", 2); gen.writeEndObject(); gen.writeEndObject(); gen.close(); String json = useBytes ? bytes.toString("UTF-8") : sw.toString(); assertEquals(EXP, json); } } @Test void arrayCount() throws Exception { final String EXP = "[6,[1,2,9(3)](2)]"; for (int i = 0; i < 2; ++i) { boolean useBytes = (i > 0); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); StringWriter sw = new StringWriter(); ObjectWriteContext ppContext = new ObjectWriteContext.Base() { @Override public PrettyPrinter getPrettyPrinter() { return new CountPrinter(); } }; JsonGenerator gen = useBytes ? JSON_F.createGenerator(ppContext, bytes) : JSON_F.createGenerator(ppContext, sw); gen.writeStartArray(); gen.writeNumber(6); gen.writeStartArray(); gen.writeNumber(1); gen.writeNumber(2); gen.writeNumber(9); gen.writeEndArray(); gen.writeEndArray(); gen.close(); String json = useBytes ? bytes.toString("UTF-8") : sw.toString(); assertEquals(EXP, json); } } @SuppressWarnings("resource") @Test void simpleDocWithMinimal() throws Exception { final PrettyPrinter MINIMAL = new MinimalPrettyPrinter(); StringWriter sw = new StringWriter(); // first with standard minimal ObjectWriteContext ppContext = new ObjectWriteContext.Base() { @Override public PrettyPrinter getPrettyPrinter() { return MINIMAL; } }; JsonGenerator gen = JSON_F.createGenerator(ppContext, sw); // Verify instance uses stateless PP assertSame(MINIMAL, gen.getPrettyPrinter()); String docStr = _verifyPrettyPrinter(gen, sw); // which should have no linefeeds, tabs assertEquals(-1, docStr.indexOf('\n')); assertEquals(-1, docStr.indexOf('\t')); // And then with slightly customized variant ppContext = new ObjectWriteContext.Base() { @Override public PrettyPrinter getPrettyPrinter() { return new MinimalPrettyPrinter() { @Override // use TAB between array values public void beforeArrayValues(JsonGenerator g) { g.writeRaw("\t"); } }; } }; gen = new JsonFactory().createGenerator(ppContext, sw); docStr = _verifyPrettyPrinter(gen, sw); assertEquals(-1, docStr.indexOf('\n')); assertTrue(docStr.indexOf('\t') >= 0); gen.close(); } // [core#26] @Test void rootSeparatorWithoutPP() throws Exception { // no pretty-printing (will still separate root values with a space!) assertEquals("{} {} []", _generateRoot(JSON_F, null)); } // [core#26] @Test void defaultRootSeparatorWithPP() throws Exception { assertEquals("{ } { } [ ]", _generateRoot(JSON_F, new DefaultPrettyPrinter())); } // [core#26] @Test void customRootSeparatorWithPPNew() throws Exception { Separators separators = Separators.createDefaultInstance() .withRootSeparator("|"); DefaultPrettyPrinter pp = new DefaultPrettyPrinter(separators); assertEquals("{ }|{ }|[ ]", _generateRoot(JSON_F, pp)); } // Alternative solution for [jackson-core#26] @Test void customRootSeparatorWithFactory() throws Exception { JsonFactory f = JsonFactory.builder() .rootValueSeparator("##") .build(); StringWriter sw = new StringWriter(); JsonGenerator gen = f.createGenerator(ObjectWriteContext.empty(), sw); gen.writeNumber(13); gen.writeBoolean(false); gen.writeNull(); gen.close(); assertEquals("13##false##null", sw.toString()); } @Test void customSeparatorsWithMinimal() throws Exception { StringWriter sw = new StringWriter(); ObjectWriteContext ppContext = new ObjectWriteContext.Base() { @Override public PrettyPrinter getPrettyPrinter() { return new MinimalPrettyPrinter().setSeparators(Separators.createDefaultInstance() .withObjectNameValueSeparator('=') .withObjectEntrySeparator(';') .withArrayElementSeparator('|')); } }; JsonGenerator gen = JSON_F.createGenerator(ppContext, sw); _writeTestDocument(gen); gen.close(); assertEquals("[3|\"abc\"|[true]|{\"f\"=null;\"f2\"=null}]", sw.toString()); // and with byte-backed too ByteArrayOutputStream bytes = new ByteArrayOutputStream(); gen = JSON_F.createGenerator(ppContext, bytes); _writeTestDocument(gen); gen.close(); assertEquals("[3|\"abc\"|[true]|{\"f\"=null;\"f2\"=null}]", bytes.toString("UTF-8")); } @Test void customSeparatorsWithPP() throws Exception { StringWriter sw = new StringWriter(); ObjectWriteContext ppContext = new ObjectWriteContext.Base() { @Override public PrettyPrinter getPrettyPrinter() { return new DefaultPrettyPrinter().withSeparators(Separators.createDefaultInstance() .withObjectNameValueSeparator('=') .withObjectEntrySeparator(';') .withArrayElementSeparator('|')); } }; JsonGenerator gen = new JsonFactory().createGenerator(ppContext, sw); _writeTestDocument(gen); gen.close(); assertEquals("[ 3| \"abc\"| [ true ]| {" + DefaultIndenter.SYS_LF + " \"f\" = null;" + DefaultIndenter.SYS_LF + " \"f2\" = null" + DefaultIndenter.SYS_LF + "} ]", sw.toString()); } private static final String EXPECTED_CUSTOM_SEPARATORS_WITH_PP_WITHOUT_SPACES = "[ 3| \"abc\"| [ true ]| {" + DefaultIndenter.SYS_LF + " \"f\"=null;" + DefaultIndenter.SYS_LF + " \"f2\"=null" + DefaultIndenter.SYS_LF + "} ]"; @Test void customSeparatorsWithPPWithoutSpacesNew() throws Exception { final Separators separators = Separators.createDefaultInstance() .withObjectNameValueSeparator('=') .withObjectNameValueSpacing(Spacing.NONE) .withObjectEntrySeparator(';') .withArrayElementSeparator('|'); ObjectWriteContext ppContext = new ObjectWriteContext.Base() { @Override public PrettyPrinter getPrettyPrinter() { return new DefaultPrettyPrinter(separators); } }; StringWriter sw = new StringWriter(); try (JsonGenerator gen = new JsonFactory().createGenerator(ppContext, sw)) { _writeTestDocument(gen); } assertEquals(EXPECTED_CUSTOM_SEPARATORS_WITH_PP_WITHOUT_SPACES, sw.toString()); } // [core#1480]: access to configured/actual PrettyPrinter @Test void accessToPrettyPrinterInUse() throws Exception { // By default, no pretty-printer try (JsonGenerator gen = JSON_F.createGenerator(ObjectWriteContext.empty(), new StringWriter())) { assertNull(gen.getPrettyPrinter()); } // But we can configure Default PP final PrettyPrinter DEFAULT_PP = new DefaultPrettyPrinter(); try (JsonGenerator gen = JSON_F.createGenerator(objectWriteContext(DEFAULT_PP), new StringWriter())) { PrettyPrinter pp = gen.getPrettyPrinter(); assertNotNull(pp); // Note: stateful, new instance created by our OWC assertEquals(DEFAULT_PP.getClass(), pp.getClass()); assertNotSame(DEFAULT_PP, pp); } } /* /********************************************************** /* Helper methods /********************************************************** */ private String _verifyPrettyPrinter(JsonGenerator gen, StringWriter sw) throws Exception { _writeTestDocument(gen); String docStr = sw.toString(); JsonParser jp = createParserUsingReader(docStr); assertEquals(JsonToken.START_ARRAY, jp.nextToken()); assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); assertEquals(3, jp.getIntValue()); assertEquals(JsonToken.VALUE_STRING, jp.nextToken()); assertEquals("abc", jp.getString()); assertEquals(JsonToken.START_ARRAY, jp.nextToken()); assertEquals(JsonToken.VALUE_TRUE, jp.nextToken()); assertEquals(JsonToken.END_ARRAY, jp.nextToken()); assertEquals(JsonToken.START_OBJECT, jp.nextToken()); assertEquals(JsonToken.PROPERTY_NAME, jp.nextToken()); assertEquals("f", jp.getString()); assertEquals(JsonToken.VALUE_NULL, jp.nextToken()); assertEquals(JsonToken.PROPERTY_NAME, jp.nextToken()); assertEquals("f2", jp.getString()); assertEquals(JsonToken.VALUE_NULL, jp.nextToken()); assertEquals(JsonToken.END_OBJECT, jp.nextToken()); assertEquals(JsonToken.END_ARRAY, jp.nextToken()); jp.close(); return docStr; } private void _writeTestDocument(JsonGenerator gen) throws IOException { gen.writeStartArray(); gen.writeNumber(3); gen.writeString("abc"); gen.writeStartArray(); gen.writeBoolean(true); gen.writeEndArray(); gen.writeStartObject(); gen.writeName("f"); gen.writeNull(); // for better test coverage also use alt method gen.writeName(new SerializedString("f2")); gen.writeNull(); gen.writeEndObject(); gen.writeEndArray(); gen.close(); } protected String _generateRoot(TokenStreamFactory f, PrettyPrinter pp) throws IOException { StringWriter sw = new StringWriter(); try (JsonGenerator gen = f.createGenerator(objectWriteContext(pp), sw)) { gen.writeStartObject(); gen.writeEndObject(); gen.writeStartObject(); gen.writeEndObject(); gen.writeStartArray(); gen.writeEndArray(); } return sw.toString(); } protected ObjectWriteContext objectWriteContext(final PrettyPrinter pp) { return new ObjectWriteContext.Base() { @SuppressWarnings("unchecked") @Override public PrettyPrinter getPrettyPrinter() { if (pp instanceof Instantiatable) { return ((Instantiatable<PrettyPrinter>) pp).createInstance(); } return pp; } }; } }
CountPrinter
java
apache__flink
flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultJobInfo.java
{ "start": 1022, "end": 1506 }
class ____ implements JobInfo { private final String jobName; private final JobType jobType; public DefaultJobInfo(String jobName, JobType jobType) { this.jobName = jobName; this.jobType = jobType; } @Override public String getJobName() { return jobName; } @Override public ExecutionMode getExecutionMode() { return jobType == JobType.STREAMING ? ExecutionMode.STREAMING : ExecutionMode.BATCH; } }
DefaultJobInfo
java
apache__camel
components/camel-zipfile/src/test/java/org/apache/camel/dataformat/zipfile/ZipSplitterRouteIssueTest.java
{ "start": 1181, "end": 2471 }
class ____ extends CamelTestSupport { @BeforeEach public void deleteTestDirs() { deleteDirectory("target/zip"); } @Test public void testSplitter() throws Exception { getMockEndpoint("mock:entry").expectedMessageCount(2); template.sendBody("direct:decompressFiles", new File("src/test/resources/data.zip")); MockEndpoint.assertIsSatisfied(context); } @Test public void testSplitterWithWrongFile() throws Exception { getMockEndpoint("mock:entry").expectedMessageCount(0); getMockEndpoint("mock:errors").expectedMessageCount(1); //Send a file which is not exit template.sendBody("direct:decompressFiles", new File("src/test/resources/data")); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { errorHandler(deadLetterChannel("mock:errors")); from("direct:decompressFiles") .split(new ZipSplitter()).streaming().shareUnitOfWork() .to("log:entry") .to("mock:entry"); } }; } }
ZipSplitterRouteIssueTest
java
apache__flink
flink-annotations/src/main/java/org/apache/flink/annotation/docs/Documentation.java
{ "start": 6345, "end": 6736 }
enum ____ { BATCH("Batch"), STREAMING("Streaming"), BATCH_STREAMING("Batch and Streaming"); private final String name; ExecMode(String name) { this.name = name; } @Override public String toString() { return name; } } /** * Annotation used on config option fields or options
ExecMode
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/TestGenericRefresh.java
{ "start": 1734, "end": 9519 }
class ____ { private static MiniDFSCluster cluster; private static Configuration config; private static RefreshHandler firstHandler; private static RefreshHandler secondHandler; @BeforeAll public static void setUpBeforeClass() throws Exception { config = new Configuration(); config.set("hadoop.security.authorization", "true"); FileSystem.setDefaultUri(config, "hdfs://localhost:0"); cluster = new MiniDFSCluster.Builder(config).build(); cluster.waitActive(); } @AfterAll public static void tearDownBeforeClass() throws Exception { if (cluster != null) { cluster.shutdown(); } } @BeforeEach public void setUp() throws Exception { // Register Handlers, first one just sends an ok response firstHandler = Mockito.mock(RefreshHandler.class); Mockito.when(firstHandler.handleRefresh(Mockito.anyString(), Mockito.any(String[].class))) .thenReturn(RefreshResponse.successResponse()); RefreshRegistry.defaultRegistry().register("firstHandler", firstHandler); // Second handler has conditional response for testing args secondHandler = Mockito.mock(RefreshHandler.class); Mockito.when(secondHandler.handleRefresh("secondHandler", new String[]{"one", "two"})) .thenReturn(new RefreshResponse(3, "three")); Mockito.when(secondHandler.handleRefresh("secondHandler", new String[]{"one"})) .thenReturn(new RefreshResponse(2, "two")); RefreshRegistry.defaultRegistry().register("secondHandler", secondHandler); } @AfterEach public void tearDown() throws Exception { RefreshRegistry.defaultRegistry().unregisterAll("firstHandler"); RefreshRegistry.defaultRegistry().unregisterAll("secondHandler"); } @Test public void testInvalidCommand() throws Exception { DFSAdmin admin = new DFSAdmin(config); String [] args = new String[]{"-refresh", "nn"}; int exitCode = admin.run(args); assertEquals(-1, exitCode, "DFSAdmin should fail due to bad args"); } @Test public void testInvalidIdentifier() throws Exception { DFSAdmin admin = new DFSAdmin(config); String [] args = new String[]{"-refresh", "localhost:" + cluster.getNameNodePort(), "unregisteredIdentity"}; int exitCode = admin.run(args); assertEquals(-1, exitCode, "DFSAdmin should fail due to no handler registered"); } @Test public void testValidIdentifier() throws Exception { DFSAdmin admin = new DFSAdmin(config); String[] args = new String[]{"-refresh", "localhost:" + cluster.getNameNodePort(), "firstHandler"}; int exitCode = admin.run(args); assertEquals(0, exitCode, "DFSAdmin should succeed"); Mockito.verify(firstHandler).handleRefresh("firstHandler", new String[]{}); // Second handler was never called Mockito.verify(secondHandler, Mockito.never()) .handleRefresh(Mockito.anyString(), Mockito.any(String[].class)); } @Test public void testVariableArgs() throws Exception { DFSAdmin admin = new DFSAdmin(config); String[] args = new String[]{"-refresh", "localhost:" + cluster.getNameNodePort(), "secondHandler", "one"}; int exitCode = admin.run(args); assertEquals(2, exitCode, "DFSAdmin should return 2"); exitCode = admin.run(new String[]{"-refresh", "localhost:" + cluster.getNameNodePort(), "secondHandler", "one", "two"}); assertEquals(3, exitCode, "DFSAdmin should now return 3"); Mockito.verify(secondHandler).handleRefresh("secondHandler", new String[]{"one"}); Mockito.verify(secondHandler).handleRefresh("secondHandler", new String[]{"one", "two"}); } @Test public void testUnregistration() throws Exception { RefreshRegistry.defaultRegistry().unregisterAll("firstHandler"); // And now this should fail DFSAdmin admin = new DFSAdmin(config); String[] args = new String[]{"-refresh", "localhost:" + cluster.getNameNodePort(), "firstHandler"}; int exitCode = admin.run(args); assertEquals(-1, exitCode, "DFSAdmin should return -1"); } @Test public void testUnregistrationReturnValue() { RefreshHandler mockHandler = Mockito.mock(RefreshHandler.class); RefreshRegistry.defaultRegistry().register("test", mockHandler); boolean ret = RefreshRegistry.defaultRegistry().unregister("test", mockHandler); assertTrue(ret); } @Test public void testMultipleRegistration() throws Exception { RefreshRegistry.defaultRegistry().register("sharedId", firstHandler); RefreshRegistry.defaultRegistry().register("sharedId", secondHandler); // this should trigger both DFSAdmin admin = new DFSAdmin(config); String[] args = new String[]{"-refresh", "localhost:" + cluster.getNameNodePort(), "sharedId", "one"}; int exitCode = admin.run(args); assertEquals(-1, exitCode); // -1 because one of the responses is unregistered // verify we called both Mockito.verify(firstHandler).handleRefresh("sharedId", new String[]{"one"}); Mockito.verify(secondHandler).handleRefresh("sharedId", new String[]{"one"}); RefreshRegistry.defaultRegistry().unregisterAll("sharedId"); } @Test public void testMultipleReturnCodeMerging() throws Exception { // Two handlers which return two non-zero values RefreshHandler handlerOne = Mockito.mock(RefreshHandler.class); Mockito.when(handlerOne.handleRefresh(Mockito.anyString(), Mockito.any(String[].class))) .thenReturn(new RefreshResponse(23, "Twenty Three")); RefreshHandler handlerTwo = Mockito.mock(RefreshHandler.class); Mockito.when(handlerTwo.handleRefresh(Mockito.anyString(), Mockito.any(String[].class))) .thenReturn(new RefreshResponse(10, "Ten")); // Then registered to the same ID RefreshRegistry.defaultRegistry().register("shared", handlerOne); RefreshRegistry.defaultRegistry().register("shared", handlerTwo); // We refresh both DFSAdmin admin = new DFSAdmin(config); String[] args = new String[]{"-refresh", "localhost:" + cluster.getNameNodePort(), "shared"}; int exitCode = admin.run(args); assertEquals(-1, exitCode); // We get -1 because of our logic for melding non-zero return codes // Verify we called both Mockito.verify(handlerOne).handleRefresh("shared", new String[]{}); Mockito.verify(handlerTwo).handleRefresh("shared", new String[]{}); RefreshRegistry.defaultRegistry().unregisterAll("shared"); } @Test public void testExceptionResultsInNormalError() throws Exception { // In this test, we ensure that all handlers are called even if we throw an exception in one RefreshHandler exceptionalHandler = Mockito.mock(RefreshHandler.class); Mockito.when(exceptionalHandler.handleRefresh(Mockito.anyString(), Mockito.any(String[].class))) .thenThrow(new RuntimeException("Exceptional Handler Throws Exception")); RefreshHandler otherExceptionalHandler = Mockito.mock(RefreshHandler.class); Mockito.when(otherExceptionalHandler.handleRefresh(Mockito.anyString(), Mockito.any(String[].class))) .thenThrow(new RuntimeException("More Exceptions")); RefreshRegistry.defaultRegistry().register("exceptional", exceptionalHandler); RefreshRegistry.defaultRegistry().register("exceptional", otherExceptionalHandler); DFSAdmin admin = new DFSAdmin(config); String[] args = new String[]{"-refresh", "localhost:" + cluster.getNameNodePort(), "exceptional"}; int exitCode = admin.run(args); assertEquals(-1, exitCode); // Exceptions result in a -1 Mockito.verify(exceptionalHandler).handleRefresh("exceptional", new String[]{}); Mockito.verify(otherExceptionalHandler).handleRefresh("exceptional", new String[]{}); RefreshRegistry.defaultRegistry().unregisterAll("exceptional"); } }
TestGenericRefresh
java
apache__kafka
streams/src/test/java/org/apache/kafka/streams/kstream/internals/KStreamPeekTest.java
{ "start": 1663, "end": 3550 }
class ____ { private final String topicName = "topic"; private final Properties props = StreamsTestUtils.getStreamsConfig(Serdes.Integer(), Serdes.String()); @Test public void shouldObserveStreamElements() { final StreamsBuilder builder = new StreamsBuilder(); final KStream<Integer, String> stream = builder.stream(topicName, Consumed.with(Serdes.Integer(), Serdes.String())); final List<KeyValue<Integer, String>> peekObserved = new ArrayList<>(), streamObserved = new ArrayList<>(); stream.peek(collect(peekObserved)).foreach(collect(streamObserved)); try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) { final TestInputTopic<Integer, String> inputTopic = driver.createInputTopic(topicName, new IntegerSerializer(), new StringSerializer()); final List<KeyValue<Integer, String>> expected = new ArrayList<>(); for (int key = 0; key < 32; key++) { final String value = "V" + key; inputTopic.pipeInput(key, value); expected.add(new KeyValue<>(key, value)); } assertEquals(expected, peekObserved); assertEquals(expected, streamObserved); } } @Test public void shouldNotAllowNullAction() { final StreamsBuilder builder = new StreamsBuilder(); final KStream<Integer, String> stream = builder.stream(topicName, Consumed.with(Serdes.Integer(), Serdes.String())); try { stream.peek(null); fail("expected null action to throw NPE"); } catch (final NullPointerException expected) { // do nothing } } private static <K, V> ForeachAction<K, V> collect(final List<KeyValue<K, V>> into) { return (key, value) -> into.add(new KeyValue<>(key, value)); } }
KStreamPeekTest
java
spring-projects__spring-framework
spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java
{ "start": 27160, "end": 27378 }
interface ____<E> { @PostMapping("/23791") default Mono<String> test(@RequestBody Mono<E> body) { return body.map(value -> value.getClass().getSimpleName()); } } @RestController private static
Controller23791
java
google__error-prone
core/src/main/java/com/google/errorprone/refaster/CouldNotResolveImportException.java
{ "start": 679, "end": 772 }
class ____ could not be resolved by the compiler. * * @author Louis Wasserman */ public
symbol
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/BeanDeserializerFactory4920Test.java
{ "start": 2967, "end": 3299 }
class ____ implements Value { private final String value; @JsonCreator(mode = JsonCreator.Mode.DELEGATING) public StringValue(String value) { this.value = value; } @JsonValue public String getValue() { return value; } } static final
StringValue
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/messaging/WebSocketStompClient.java
{ "start": 16615, "end": 19818 }
class ____ { private static final StompEncoder ENCODER = new StompEncoder(); private static final StompDecoder DECODER = new StompDecoder(); private final BufferingStompDecoder bufferingDecoder; private final @Nullable SplittingStompEncoder splittingEncoder; public StompWebSocketMessageCodec(int inboundMessageSizeLimit, @Nullable Integer outboundMessageSizeLimit) { this.bufferingDecoder = new BufferingStompDecoder(DECODER, inboundMessageSizeLimit); this.splittingEncoder = (outboundMessageSizeLimit != null ? new SplittingStompEncoder(ENCODER, outboundMessageSizeLimit) : null); } public List<Message<byte[]>> decode(WebSocketMessage<?> webSocketMessage) { List<Message<byte[]>> result = Collections.emptyList(); ByteBuffer byteBuffer; if (webSocketMessage instanceof TextMessage textMessage) { byteBuffer = ByteBuffer.wrap(textMessage.asBytes()); } else if (webSocketMessage instanceof BinaryMessage binaryMessage) { byteBuffer = binaryMessage.getPayload(); } else { return result; } result = this.bufferingDecoder.decode(byteBuffer); if (result.isEmpty()) { if (logger.isTraceEnabled()) { logger.trace("Incomplete STOMP frame content received, bufferSize=" + this.bufferingDecoder.getBufferSize() + ", bufferSizeLimit=" + this.bufferingDecoder.getBufferSizeLimit() + "."); } } return result; } public boolean hasSplittingEncoder() { return (this.splittingEncoder != null); } public WebSocketMessage<?> encode(Message<byte[]> message, Class<? extends WebSocketSession> sessionType) { StompHeaderAccessor accessor = getStompHeaderAccessor(message); byte[] payload = message.getPayload(); byte[] frame = ENCODER.encode(accessor.getMessageHeaders(), payload); return (useBinary(accessor, payload, sessionType) ? new BinaryMessage(frame) : new TextMessage(frame)); } public List<WebSocketMessage<?>> encodeAndSplit(Message<byte[]> message, Class<? extends WebSocketSession> sessionType) { Assert.state(this.splittingEncoder != null, "No SplittingEncoder"); StompHeaderAccessor accessor = getStompHeaderAccessor(message); byte[] payload = message.getPayload(); List<byte[]> frames = this.splittingEncoder.encode(accessor.getMessageHeaders(), payload); boolean useBinary = useBinary(accessor, payload, sessionType); List<WebSocketMessage<?>> messages = new ArrayList<>(frames.size()); frames.forEach(frame -> messages.add(useBinary ? new BinaryMessage(frame) : new TextMessage(frame))); return messages; } private static StompHeaderAccessor getStompHeaderAccessor(Message<byte[]> message) { StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); Assert.notNull(accessor, "No StompHeaderAccessor available"); return accessor; } private static boolean useBinary( StompHeaderAccessor accessor, byte[] payload, Class<? extends WebSocketSession> sessionType) { return (payload.length > 0 && !(SockJsSession.class.isAssignableFrom(sessionType)) && MimeTypeUtils.APPLICATION_OCTET_STREAM.isCompatibleWith(accessor.getContentType())); } } }
StompWebSocketMessageCodec
java
apache__flink
flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/ManuallyTriggeredScheduledExecutorService.java
{ "start": 1712, "end": 1897 }
class ____ helpful when implementing tests tasks synchronous and control when they run, * which would otherwise asynchronous and require complex triggers and latches to test. */ public
is
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest4.java
{ "start": 881, "end": 1481 }
class ____ { private String name; public User(){ } public User(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } private List<Address> addresses = new ArrayList<Address>(); public List<Address> getAddresses() { return addresses; } public void setAddresses(List<Address> addresses) { this.addresses = addresses; } } public static
User
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/util/BoundedFIFOQueue.java
{ "start": 1270, "end": 3071 }
class ____<T> implements Iterable<T>, Serializable { private static final long serialVersionUID = -890727339944580409L; private final int maxSize; private final Queue<T> elements; /** * Creates a {@code BoundedFIFOQueue} with the given maximum size. * * @param maxSize The maximum size of this queue. Exceeding this limit would result in removing * the oldest element (FIFO). * @throws IllegalArgumentException If {@code maxSize} is less than 0. */ public BoundedFIFOQueue(int maxSize) { Preconditions.checkArgument(maxSize >= 0, "The maximum size should be at least 0."); this.maxSize = maxSize; this.elements = new LinkedList<>(); } /** * Adds an element to the end of the queue. An element will be removed from the head of the * queue if the queue would exceed its maximum size by adding the new element. * * @param element The element that should be added to the end of the queue. * @throws NullPointerException If {@code null} is passed as an element. */ public void add(T element) { Preconditions.checkNotNull(element); if (elements.add(element) && elements.size() > maxSize) { elements.poll(); } } public ArrayList<T> toArrayList() { return new ArrayList<>(elements); } /** * Returns the number of currently stored elements. * * @return The number of currently stored elements. */ public int size() { return this.elements.size(); } /** * Returns the {@code BoundedFIFOQueue}'s {@link Iterator}. * * @return The queue's {@code Iterator}. */ @Override public Iterator<T> iterator() { return elements.iterator(); } }
BoundedFIFOQueue
java
apache__camel
components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/consumer/integration/deployments/KubernetesDeploymentsConsumerResourceNameIT.java
{ "start": 1957, "end": 3100 }
class ____ extends KubernetesConsumerTestSupport { @Test public void resourceNameTest() { createDeployment(ns1, WATCH_RESOURCE_NAME, null); createDeployment(ns2, WATCH_RESOURCE_NAME, null); Awaitility.await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> { final List<String> list = result.getExchanges().stream().map(ex -> ex.getIn().getBody(String.class)).toList(); assertThat(list, everyItem(allOf( containsString(WATCH_RESOURCE_NAME), containsString(ns2), not(containsString(ns1))))); }); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { fromF("kubernetes-deployments://%s?oauthToken=%s&resourceName=%s&namespace=%s", host, authToken, WATCH_RESOURCE_NAME, ns2) .process(new KubernetesProcessor()) .to(result); } }; } }
KubernetesDeploymentsConsumerResourceNameIT
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestErasureCodeBenchmarkThroughput.java
{ "start": 1490, "end": 4038 }
class ____ { private static MiniDFSCluster cluster; private static Configuration conf; private static FileSystem fs; @BeforeAll public static void setup() throws IOException { conf = new HdfsConfiguration(); int numDN = ErasureCodeBenchmarkThroughput.getEcPolicy().getNumDataUnits() + ErasureCodeBenchmarkThroughput.getEcPolicy().getNumParityUnits(); cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDN).build(); cluster.waitActive(); fs = cluster.getFileSystem(); ((DistributedFileSystem)fs).enableErasureCodingPolicy( ErasureCodeBenchmarkThroughput.getEcPolicy().getName()); } @AfterAll public static void tearDown() { if (cluster != null) { cluster.shutdown(true); } } private static void runBenchmark(String[] args) throws Exception { assertNotNull(conf); assertNotNull(fs); assertEquals(0, ToolRunner.run(conf, new ErasureCodeBenchmarkThroughput(fs), args)); } private static void verifyNumFile(final int dataSize, final boolean isEc, int numFile) throws IOException { Path path = isEc ? new Path(ErasureCodeBenchmarkThroughput.EC_DIR) : new Path(ErasureCodeBenchmarkThroughput.REP_DIR); FileStatus[] statuses = fs.listStatus(path, new PathFilter() { @Override public boolean accept(Path path) { return path.toString().contains( ErasureCodeBenchmarkThroughput.getFilePath(dataSize, isEc)); } }); assertEquals(numFile, statuses.length); } @Test public void testReplicaReadWrite() throws Exception { Integer dataSize = 10; Integer numClient = 3; String[] args = new String[]{"write", dataSize.toString(), "rep", numClient.toString()}; runBenchmark(args); args[0] = "gen"; runBenchmark(args); args[0] = "read"; runBenchmark(args); } @Test public void testECReadWrite() throws Exception { Integer dataSize = 5; Integer numClient = 5; String[] args = new String[]{"write", dataSize.toString(), "ec", numClient.toString()}; runBenchmark(args); args[0] = "gen"; runBenchmark(args); args[0] = "read"; runBenchmark(args); } @Test public void testCleanUp() throws Exception { Integer dataSize = 5; Integer numClient = 5; String[] args = new String[]{"gen", dataSize.toString(), "ec", numClient.toString()}; runBenchmark(args); args[0] = "clean"; runBenchmark(args); verifyNumFile(dataSize, true, 0); } }
TestErasureCodeBenchmarkThroughput
java
apache__camel
components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsSendDynamicAware.java
{ "start": 1570, "end": 4522 }
class ____ extends ServiceSupport implements SendDynamicAware { private CamelContext camelContext; private String scheme; @Override public String getScheme() { return scheme; } @Override public void setScheme(String scheme) { this.scheme = scheme; } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public boolean isLenientProperties() { return false; } @Override public DynamicAwareEntry prepare(Exchange exchange, String uri, String originalUri) throws Exception { return new DynamicAwareEntry(uri, originalUri, null, null); } @Override public String resolveStaticUri(Exchange exchange, DynamicAwareEntry entry) throws Exception { String destination = parseDestinationName(entry.getUri()); if (destination != null) { String originalDestination = parseDestinationName(entry.getOriginalUri()); if (!destination.equals(originalDestination)) { // okay the destination was dynamic, so use the original as endpoint name String answer = entry.getUri(); answer = StringHelper.replaceFirst(answer, destination, originalDestination); return answer; } } return null; } @Override public Processor createPreProcessor(Exchange exchange, DynamicAwareEntry entry) throws Exception { if (exchange.getMessage().getHeader(JmsConstants.JMS_DESTINATION_NAME) != null) { return null; } final String destinationName = parseDestinationName(entry.getUri()); return new Processor() { @Override public void process(Exchange exchange) { exchange.getMessage().setHeader(JmsConstants.JMS_DESTINATION_NAME, destinationName); } }; } @Override public Processor createPostProcessor(Exchange exchange, DynamicAwareEntry entry) throws Exception { // no post processor is needed return null; } private String parseDestinationName(String uri) { // strip query uri = uri.replaceFirst(scheme + "://", ":"); uri = StringHelper.before(uri, "?", uri); // destination name is after last colon (but not after double colon) String shortUri = StringHelper.before(uri, "::"); final int lastIdx = lastIndexOneOf(uri, shortUri); if (lastIdx != -1) { return uri.substring(lastIdx + 1); } else { return null; } } private static int lastIndexOneOf(String uri, String shortUri) { if (shortUri == null) { return uri.lastIndexOf(':'); } return shortUri.lastIndexOf(':'); } }
JmsSendDynamicAware
java
apache__hadoop
hadoop-tools/hadoop-gridmix/src/main/java/org/apache/hadoop/mapred/gridmix/GenerateData.java
{ "start": 7046, "end": 7827 }
class ____ extends Mapper<NullWritable,LongWritable,NullWritable,BytesWritable> { private BytesWritable val; private final Random r = new Random(); @Override protected void setup(Context context) throws IOException, InterruptedException { val = new BytesWritable(new byte[ context.getConfiguration().getInt(GRIDMIX_VAL_BYTES, 1024 * 1024)]); } @Override public void map(NullWritable key, LongWritable value, Context context) throws IOException, InterruptedException { for (long bytes = value.get(); bytes > 0; bytes -= val.getLength()) { r.nextBytes(val.getBytes()); val.setSize((int)Math.min(val.getLength(), bytes)); context.write(key, val); } } } static
GenDataMapper
java
micronaut-projects__micronaut-core
http-server-netty/src/main/java/io/micronaut/http/server/netty/HttpPipelineBuilder.java
{ "start": 40160, "end": 40919 }
class ____ extends Http23GracefulShutdownBase { private final Http2ConnectionHandler connectionHandler; public Http2GracefulShutdown(ChannelHandlerContext ctx, Http2ConnectionHandler connectionHandler) { super(ctx); this.connectionHandler = connectionHandler; } @Override protected int numberOfActiveStreams() { return connectionHandler.connection().numActiveStreams(); } @Override protected ChannelFuture goAway() { return connectionHandler.goAway(ctx, connectionHandler.connection().remote().lastStreamCreated(), Http2Error.NO_ERROR.code(), Unpooled.EMPTY_BUFFER, ctx.newPromise()); } } private static final
Http2GracefulShutdown
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/mappingcomposition/StorageMapper.java
{ "start": 312, "end": 632 }
interface ____ { StorageMapper INSTANCE = Mappers.getMapper( StorageMapper.class ); @ToEntity @Mapping( target = "weightLimit", source = "maxWeight") ShelveEntity map(ShelveDto source); @ToEntity @Mapping( target = "label", source = "designation") BoxEntity map(BoxDto source); }
StorageMapper
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MasterEndpointBuilderFactory.java
{ "start": 1632, "end": 1950 }
interface ____ extends EndpointConsumerBuilder { default AdvancedMasterEndpointBuilder advanced() { return (AdvancedMasterEndpointBuilder) this; } } /** * Advanced builder for endpoint for the Master component. */ public
MasterEndpointBuilder
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/placement/CandidateNodeSet.java
{ "start": 1480, "end": 1661 }
class ____ check if it's required to * invalidate local caches, etc. * 3) Node partition of the candidate set. */ @InterfaceAudience.Private @InterfaceStability.Unstable public
to
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDelegatingLinuxContainerRuntime.java
{ "start": 1632, "end": 8367 }
class ____ { private DelegatingLinuxContainerRuntime delegatingLinuxContainerRuntime; private Configuration conf; private Map<String, String> env = new HashMap<>(); @BeforeEach public void setUp() throws Exception { delegatingLinuxContainerRuntime = new DelegatingLinuxContainerRuntime(); conf = new Configuration(); env.clear(); } @Test public void testIsRuntimeAllowedDefault() throws Exception { conf.set(YarnConfiguration.LINUX_CONTAINER_RUNTIME_ALLOWED_RUNTIMES, YarnConfiguration.DEFAULT_LINUX_CONTAINER_RUNTIME_ALLOWED_RUNTIMES[0]); System.out.println(conf.get( YarnConfiguration.LINUX_CONTAINER_RUNTIME_ALLOWED_RUNTIMES)); delegatingLinuxContainerRuntime.initialize(conf, null); assertTrue(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.DEFAULT.name())); assertFalse(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.DOCKER.name())); assertFalse(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.JAVASANDBOX.name())); } @Test public void testIsRuntimeAllowedDocker() throws Exception { conf.set(YarnConfiguration.LINUX_CONTAINER_RUNTIME_ALLOWED_RUNTIMES, ContainerRuntimeConstants.CONTAINER_RUNTIME_DOCKER); delegatingLinuxContainerRuntime.initialize(conf, null); assertTrue(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.DOCKER.name())); assertFalse(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.DEFAULT.name())); assertFalse(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.JAVASANDBOX.name())); } @Test public void testIsRuntimeAllowedJavaSandbox() throws Exception { conf.set(YarnConfiguration.LINUX_CONTAINER_RUNTIME_ALLOWED_RUNTIMES, "javasandbox"); delegatingLinuxContainerRuntime.initialize(conf, null); assertTrue(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.JAVASANDBOX.name())); assertFalse(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.DEFAULT.name())); assertFalse(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.DOCKER.name())); } @Test public void testIsRuntimeAllowedMultiple() throws Exception { conf.set(YarnConfiguration.LINUX_CONTAINER_RUNTIME_ALLOWED_RUNTIMES, "docker,javasandbox"); delegatingLinuxContainerRuntime.initialize(conf, null); assertTrue(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.DOCKER.name())); assertTrue(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.JAVASANDBOX.name())); assertFalse(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.DEFAULT.name())); } @Test public void testIsRuntimeAllowedAll() throws Exception { conf.set(YarnConfiguration.LINUX_CONTAINER_RUNTIME_ALLOWED_RUNTIMES, "default,docker,javasandbox"); delegatingLinuxContainerRuntime.initialize(conf, null); assertTrue(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.DEFAULT.name())); assertTrue(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.DOCKER.name())); assertTrue(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.JAVASANDBOX.name())); } @Test public void testInitializeMissingRuntimeClass() throws Exception { conf.set(YarnConfiguration.LINUX_CONTAINER_RUNTIME_ALLOWED_RUNTIMES, "mock"); try { delegatingLinuxContainerRuntime.initialize(conf, null); fail("initialize should fail"); } catch (ContainerExecutionException e) { assert(e.getMessage().contains("Invalid runtime set")); } } @Test public void testIsRuntimeAllowedMock() throws Exception { conf.set(YarnConfiguration.LINUX_CONTAINER_RUNTIME_ALLOWED_RUNTIMES, "mock"); conf.set(String.format(YarnConfiguration.LINUX_CONTAINER_RUNTIME_CLASS_FMT, "mock"), MockLinuxContainerRuntime.class.getName()); delegatingLinuxContainerRuntime.initialize(conf, null); assertFalse(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.DEFAULT.name())); assertFalse(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.DOCKER.name())); assertFalse(delegatingLinuxContainerRuntime.isRuntimeAllowed( LinuxContainerRuntimeConstants.RuntimeType.JAVASANDBOX.name())); assertTrue(delegatingLinuxContainerRuntime.isRuntimeAllowed("mock")); } @Test public void testJavaSandboxNotAllowedButPermissive() throws Exception { conf.set(YarnConfiguration.LINUX_CONTAINER_RUNTIME_ALLOWED_RUNTIMES, "default,docker"); conf.set(YarnConfiguration.YARN_CONTAINER_SANDBOX, "permissive"); delegatingLinuxContainerRuntime.initialize(conf, null); ContainerRuntime runtime = delegatingLinuxContainerRuntime.pickContainerRuntime(env); assertTrue(runtime instanceof DefaultLinuxContainerRuntime); } @Test public void testJavaSandboxNotAllowedButPermissiveDockerRequested() throws Exception { env.put(ContainerRuntimeConstants.ENV_CONTAINER_TYPE, ContainerRuntimeConstants.CONTAINER_RUNTIME_DOCKER); conf.set(YarnConfiguration.LINUX_CONTAINER_RUNTIME_ALLOWED_RUNTIMES, "default,docker"); conf.set(YarnConfiguration.YARN_CONTAINER_SANDBOX, "permissive"); delegatingLinuxContainerRuntime.initialize(conf, null); ContainerRuntime runtime = delegatingLinuxContainerRuntime.pickContainerRuntime(env); assertTrue(runtime instanceof DockerLinuxContainerRuntime); } @Test public void testMockRuntimeSelected() throws Exception { env.put(ContainerRuntimeConstants.ENV_CONTAINER_TYPE, "mock"); conf.set(String.format(YarnConfiguration.LINUX_CONTAINER_RUNTIME_CLASS_FMT, "mock"), MockLinuxContainerRuntime.class.getName()); conf.set(YarnConfiguration.LINUX_CONTAINER_RUNTIME_ALLOWED_RUNTIMES, "mock"); delegatingLinuxContainerRuntime.initialize(conf, null); ContainerRuntime runtime = delegatingLinuxContainerRuntime.pickContainerRuntime(env); assertTrue(runtime instanceof MockLinuxContainerRuntime); } }
TestDelegatingLinuxContainerRuntime
java
quarkusio__quarkus
independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/codestarts/extension/QuarkusExtensionCodestartCatalog.java
{ "start": 2905, "end": 4151 }
enum ____ implements DataKey { GIT } public static QuarkusExtensionCodestartCatalog fromBaseCodestartsResources(MessageWriter log) throws IOException { final Map<String, Codestart> codestarts = loadCodestartsFromResources(getCodestartResourceLoaders(log), QUARKUS_EXTENSION_CODESTARTS_DIR); return new QuarkusExtensionCodestartCatalog(codestarts.values()); } @Override protected Collection<Codestart> select(QuarkusExtensionCodestartProjectInput projectInput) { projectInput.getSelection().addNames(getCodestarts(projectInput)); return super.select(projectInput); } private List<String> getCodestarts(QuarkusExtensionCodestartProjectInput projectInput) { final List<String> codestarts = new ArrayList<>(); codestarts.add(Code.EXTENSION_BASE.key()); if (!projectInput.withoutDevModeTest()) { codestarts.add(Code.DEVMODE_TEST.key()); } if (!projectInput.withoutIntegrationTests()) { codestarts.add(Code.INTEGRATION_TESTS.key()); } if (!projectInput.withoutUnitTest()) { codestarts.add(Code.UNIT_TEST.key()); } return codestarts; } }
Tooling
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/preprocessor/TagAddProcessor.java
{ "start": 1135, "end": 1655 }
class ____ implements ContextProcessor { @Override public void process(String host, String value, ApplicationId applicationId, ApplicationSubmissionContext submissionContext) { Set<String> applicationTags = submissionContext.getApplicationTags(); if (applicationTags == null) { applicationTags = new HashSet<>(); } else { applicationTags = new HashSet<>(applicationTags); } applicationTags.add(value); submissionContext.setApplicationTags(applicationTags); } }
TagAddProcessor
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TempDirectoryTests.java
{ "start": 25113, "end": 25722 }
class ____ { @Test void createReadonlyFile(@TempDir Path tempDir) throws IOException { // Removal of setWritable(false) files might fail (e.g. for Windows) // The test verifies that @TempDir is capable of removing of such files var path = Files.write(tempDir.resolve("test.txt"), new byte[0]); assumeTrue(path.toFile().setWritable(false), () -> "Unable to set file " + path + " readonly via .toFile().setWritable(false)"); } } // https://github.com/junit-team/junit-framework/issues/2171 @SuppressWarnings("JUnitMalformedDeclaration") static
NonWritableFileDoesNotCauseFailureTestCase
java
resilience4j__resilience4j
resilience4j-timelimiter/src/main/java/io/github/resilience4j/timelimiter/event/TimeLimiterOnSuccessEvent.java
{ "start": 671, "end": 1056 }
class ____ extends AbstractTimeLimiterEvent { public TimeLimiterOnSuccessEvent(String timeLimiterName) { super(timeLimiterName, Type.SUCCESS); } @Override public String toString() { return String.format("%s: TimeLimiter '%s' recorded a successful call.", getCreationTime(), getTimeLimiterName()); } }
TimeLimiterOnSuccessEvent
java
quarkusio__quarkus
core/processor/src/main/java/io/quarkus/annotation/processor/documentation/config/merger/ModelMerger.java
{ "start": 1312, "end": 10306 }
class ____ { private ModelMerger() { } /** * Merge all the resolved models obtained from a list of build output directories (e.g. in the case of Maven, the list of * target/ directories found in the parent directory scanned). */ public static MergedModel mergeModel(List<Path> buildOutputDirectories) { return mergeModel(null, buildOutputDirectories); } /** * Merge all the resolved models obtained from a list of build output directories (e.g. in the case of Maven, the list of * target/ directories found in the parent directory scanned). */ public static MergedModel mergeModel(JavadocRepository javadocRepository, List<Path> buildOutputDirectories) { return mergeModel(javadocRepository, buildOutputDirectories, false); } /** * Merge all the resolved models obtained from a list of build output directories (e.g. in the case of Maven, the list of * target/ directories found in the parent directory scanned). */ public static MergedModel mergeModel(List<Path> buildOutputDirectories, boolean mergeCommonOrInternalExtensions) { return mergeModel(null, buildOutputDirectories, mergeCommonOrInternalExtensions); } /** * Merge all the resolved models obtained from a list of build output directories (e.g. in the case of Maven, the list of * target/ directories found in the parent directory scanned). */ public static MergedModel mergeModel(JavadocRepository javadocRepository, List<Path> buildOutputDirectories, boolean mergeCommonOrInternalExtensions) { // keyed on extension and then top level prefix Map<Extension, Map<ConfigRootKey, ConfigRoot>> configRoots = new HashMap<>(); // keyed on file name Map<String, ConfigRoot> configRootsInSpecificFile = new TreeMap<>(); // keyed on extension Map<Extension, List<ConfigSection>> generatedConfigSections = new HashMap<>(); for (Path buildOutputDirectory : buildOutputDirectories) { Path resolvedModelPath = buildOutputDirectory.resolve(Outputs.QUARKUS_CONFIG_DOC_MODEL); if (!Files.isReadable(resolvedModelPath)) { continue; } try (InputStream resolvedModelIs = Files.newInputStream(resolvedModelPath)) { ResolvedModel resolvedModel = JacksonMappers.yamlObjectReader().readValue(resolvedModelIs, ResolvedModel.class); if (resolvedModel.getConfigRoots() == null || resolvedModel.getConfigRoots().isEmpty()) { continue; } for (ConfigRoot configRoot : resolvedModel.getConfigRoots()) { if (configRoot.getOverriddenDocFileName() != null) { ConfigRoot existingConfigRootInSpecificFile = configRootsInSpecificFile .get(configRoot.getOverriddenDocFileName()); if (existingConfigRootInSpecificFile == null) { configRootsInSpecificFile.put(configRoot.getOverriddenDocFileName(), configRoot); } else { if (!existingConfigRootInSpecificFile.getExtension().equals(configRoot.getExtension()) || !existingConfigRootInSpecificFile.getPrefix().equals(configRoot.getPrefix())) { throw new IllegalStateException( "Two config roots with different extensions or prefixes cannot be merged in the same specific config file: " + configRoot.getOverriddenDocFileName()); } existingConfigRootInSpecificFile.merge(configRoot); } continue; } Map<ConfigRootKey, ConfigRoot> extensionConfigRoots = configRoots.computeIfAbsent( normalizeExtension(configRoot.getExtension(), mergeCommonOrInternalExtensions), e -> new TreeMap<>()); ConfigRootKey configRootKey = getConfigRootKey(javadocRepository, configRoot); ConfigRoot existingConfigRoot = extensionConfigRoots.get(configRootKey); if (existingConfigRoot == null) { extensionConfigRoots.put(configRootKey, configRoot); } else { existingConfigRoot.merge(configRoot); } } } catch (IOException e) { throw new IllegalStateException("Unable to parse: " + resolvedModelPath, e); } } // note that the configRoots are now sorted by extension name configRoots = retainBestExtensionKey(configRoots); for (Entry<Extension, Map<ConfigRootKey, ConfigRoot>> extensionConfigRootsEntry : configRoots.entrySet()) { List<ConfigSection> extensionGeneratedConfigSections = generatedConfigSections .computeIfAbsent(extensionConfigRootsEntry.getKey(), e -> new ArrayList<>()); for (ConfigRoot configRoot : extensionConfigRootsEntry.getValue().values()) { collectGeneratedConfigSections(extensionGeneratedConfigSections, configRoot); } } return new MergedModel(configRoots, configRootsInSpecificFile, generatedConfigSections); } private static Extension normalizeExtension(Extension extension, boolean mergeCommonOrInternalExtensions) { if (!mergeCommonOrInternalExtensions) { return extension; } if (extension.commonOrInternal()) { return extension.normalizeCommonOrInternal(); } return extension; } private static Map<Extension, Map<ConfigRootKey, ConfigRoot>> retainBestExtensionKey( Map<Extension, Map<ConfigRootKey, ConfigRoot>> configRoots) { return configRoots.entrySet().stream().collect(Collectors.toMap(e -> { Extension extension = e.getKey(); for (ConfigRoot configRoot : e.getValue().values()) { if (configRoot.getExtension().nameSource().isBetterThan(extension.nameSource())) { extension = configRoot.getExtension(); } if (NameSource.EXTENSION_METADATA.equals(extension.nameSource())) { // we won't find any better break; } } return extension; }, e -> e.getValue(), (k1, k2) -> k1, TreeMap::new)); } private static void collectGeneratedConfigSections(List<ConfigSection> extensionGeneratedConfigSections, ConfigItemCollection configItemCollection) { for (AbstractConfigItem configItem : configItemCollection.getItems()) { if (!configItem.isSection()) { continue; } ConfigSection configSection = (ConfigSection) configItem; if (configSection.isGenerated()) { extensionGeneratedConfigSections.add(configSection); } collectGeneratedConfigSections(extensionGeneratedConfigSections, configSection); } } private static ConfigRootKey getConfigRootKey(JavadocRepository javadocRepository, ConfigRoot configRoot) { return new ConfigRootKey(configRoot.getTopLevelPrefix(), getConfigRootDescription(javadocRepository, configRoot)); } // here we only return a description if all the qualified names of the config root have a similar description private static String getConfigRootDescription(JavadocRepository javadocRepository, ConfigRoot configRoot) { if (!configRoot.getExtension().splitOnConfigRootDescription()) { return null; } if (javadocRepository == null) { return null; } String description = null; for (String qualifiedName : configRoot.getQualifiedNames()) { Optional<JavadocElement> javadocElement = javadocRepository.getElement(qualifiedName); if (javadocElement.isEmpty()) { return null; } String descriptionCandidate = trimFinalDot(javadocElement.get().description()); if (description == null) { description = descriptionCandidate; } else if (!description.equals(descriptionCandidate)) { return null; } } return description; } private static String trimFinalDot(String javadoc) { if (javadoc == null || javadoc.isBlank()) { return null; } javadoc = javadoc.trim(); int dotIndex = javadoc.indexOf("."); if (dotIndex == -1) { return javadoc; } return javadoc.substring(0, dotIndex); } }
ModelMerger
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/files/Files_assertIsAbsolute_Test.java
{ "start": 1307, "end": 2069 }
class ____ extends FilesBaseTest { @Test void should_fail_if_actual_is_null() { // GIVEN File actual = null; // WHEN var error = expectAssertionError(() -> underTest.assertIsAbsolute(INFO, actual)); // THEN then(error).hasMessage(actualIsNull()); } @Test void should_fail_if_actual_is_not_absolute_path() { // GIVEN File actual = new File("xyz"); // WHEN expectAssertionError(() -> underTest.assertIsAbsolute(INFO, actual)); // THEN verify(failures).failure(INFO, shouldBeAbsolutePath(actual)); } @Test void should_pass_if_actual_is_absolute_path() { File actual = new File(tempDir.getAbsolutePath() + "/file.txt"); underTest.assertIsAbsolute(INFO, actual); } }
Files_assertIsAbsolute_Test
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/helper/JsonCustomResourceTypeTestcase.java
{ "start": 1257, "end": 1654 }
class ____ the implementation details of how to verify the structure of * JSON responses. Tests should only provide the path of the * {@link WebTarget}, the response from the resource and * the verifier Consumer to * {@link JsonCustomResourceTypeTestcase#verify(Consumer)}. An instance of * {@link JSONObject} will be passed to that consumer to be able to * verify the response. */ public
hides
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanRegistrationsAotContribution.java
{ "start": 7926, "end": 8530 }
class ____ implements BeanRegistrationsCode { private final GeneratedClass generatedClass; public BeanRegistrationsCodeGenerator(GeneratedClass generatedClass) { this.generatedClass = generatedClass; } @Override public ClassName getClassName() { return this.generatedClass.getName(); } @Override public GeneratedMethods getMethods() { return this.generatedClass.getMethods(); } } /** * Generate code for bean registrations. Limited to {@value #MAX_REGISTRATIONS_PER_METHOD} * beans per method to avoid hitting a limit. */ static final
BeanRegistrationsCodeGenerator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ConstantPatternCompileTest.java
{ "start": 11577, "end": 12142 }
class ____ { public void myPopularStaticMethod() { Matcher m = MY_PATTERN.matcher("aaaaab"); } private final Pattern MY_PATTERN = Pattern.compile(MY_COOL_PATTERN); } } """) .doTest(); } @Test public void negativeCases() { compilationHelper .addSourceLines( "in/Test.java", """ import com.google.errorprone.annotations.CompileTimeConstant; import java.util.regex.Pattern;
Inner
java
apache__maven
impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvnup/goals/InferenceStrategyTest.java
{ "start": 24528, "end": 35548 }
class ____ { @Test @DisplayName("should remove child groupId and version when they match parent in 4.0.0") void shouldRemoveChildGroupIdAndVersionWhenTheyMatchParentIn400() throws Exception { String parentPomXml = """ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>parent-project</artifactId> <version>1.0.0</version> <packaging>pom</packaging> </project> """; String childPomXml = """ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.example</groupId> <artifactId>parent-project</artifactId> <version>1.0.0</version> <relativePath>../pom.xml</relativePath> </parent> <groupId>com.example</groupId> <artifactId>child-project</artifactId> <version>1.0.0</version> <!-- Child groupId and version match parent - can be inferred --> </project> """; Document parentDoc = Document.of(parentPomXml); Document childDoc = Document.of(childPomXml); Map<Path, Document> pomMap = new HashMap<>(); pomMap.put(Paths.get("project", "pom.xml"), parentDoc); pomMap.put(Paths.get("project", "child", "pom.xml"), childDoc); Editor editor = new Editor(childDoc); Element childRoot = editor.root(); Element parentElement = DomUtils.findChildElement(childRoot, "parent"); // Verify child and parent elements exist before inference assertNotNull(childRoot.child("groupId").orElse(null)); assertNotNull(childRoot.child("version").orElse(null)); assertNotNull(parentElement.child("groupId").orElse(null)); assertNotNull(parentElement.child("artifactId").orElse(null)); assertNotNull(parentElement.child("version").orElse(null)); // Apply inference UpgradeContext context = createMockContext(); strategy.apply(context, pomMap); // Verify child groupId and version were removed (Maven 4.0.0 can infer these from parent) assertNull(childRoot.child("groupId").orElse(null)); assertNull(childRoot.child("version").orElse(null)); // Child artifactId should remain (always required) assertNotNull(childRoot.child("artifactId").orElse(null)); // Parent elements should all remain (no relativePath inference in 4.0.0) assertNotNull(parentElement.child("groupId").orElse(null)); assertNotNull(parentElement.child("artifactId").orElse(null)); assertNotNull(parentElement.child("version").orElse(null)); } @Test @DisplayName("should keep child groupId when it differs from parent in 4.0.0") void shouldKeepChildGroupIdWhenItDiffersFromParentIn400() throws Exception { String parentPomXml = """ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>parent-project</artifactId> <version>1.0.0</version> <packaging>pom</packaging> </project> """; String childPomXml = """ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.example</groupId> <artifactId>parent-project</artifactId> <version>1.0.0</version> <relativePath>../pom.xml</relativePath> </parent> <groupId>com.example.child</groupId> <artifactId>child-project</artifactId> <version>2.0.0</version> </project> """; Document parentDoc = Document.of(parentPomXml); Document childDoc = Document.of(childPomXml); Map<Path, Document> pomMap = new HashMap<>(); pomMap.put(Paths.get("project", "pom.xml"), parentDoc); pomMap.put(Paths.get("project", "child", "pom.xml"), childDoc); Editor editor = new Editor(childDoc); Element childRoot = editor.root(); Element parentElement = childRoot.child("parent").orElse(null); // Apply inference UpgradeContext context = createMockContext(); strategy.apply(context, pomMap); // Verify child elements are kept (since they differ from parent) assertNotNull(childRoot.child("groupId").orElse(null)); assertNotNull(childRoot.child("version").orElse(null)); assertNotNull(childRoot.child("artifactId").orElse(null)); // Parent elements should all remain (no relativePath inference in 4.0.0) assertNotNull(parentElement.child("groupId").orElse(null)); assertNotNull(parentElement.child("artifactId").orElse(null)); assertNotNull(parentElement.child("version").orElse(null)); } @Test @DisplayName("should handle partial inheritance in 4.0.0") void shouldHandlePartialInheritanceIn400() throws Exception { String parentPomXml = """ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>parent-project</artifactId> <version>1.0.0</version> <packaging>pom</packaging> </project> """; String childPomXml = """ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.example</groupId> <artifactId>parent-project</artifactId> <version>1.0.0</version> <relativePath>../pom.xml</relativePath> </parent> <groupId>com.example</groupId> <artifactId>child-project</artifactId> <version>2.0.0</version> <!-- Child groupId matches parent, but version differs --> </project> """; Document parentDoc = Document.of(parentPomXml); Document childDoc = Document.of(childPomXml); Map<Path, Document> pomMap = new HashMap<>(); pomMap.put(Paths.get("project", "pom.xml"), parentDoc); pomMap.put(Paths.get("project", "child", "pom.xml"), childDoc); Editor editor = new Editor(childDoc); Element childRoot = editor.root(); Element parentElement = DomUtils.findChildElement(childRoot, "parent"); // Apply inference UpgradeContext context = createMockContext(); strategy.apply(context, pomMap); // Verify child groupId was removed (matches parent, can be inferred) assertNull(childRoot.child("groupId").orElse(null)); // Verify child version was kept (differs from parent, cannot be inferred) assertNotNull(childRoot.child("version").orElse(null)); // Verify child artifactId was kept (always required) assertNotNull(childRoot.child("artifactId").orElse(null)); // Parent elements should all remain (no relativePath inference in 4.0.0) assertNotNull(parentElement.child("groupId").orElse(null)); assertNotNull(parentElement.child("artifactId").orElse(null)); assertNotNull(parentElement.child("version").orElse(null)); } @Test @DisplayName("should not apply dependency inference to 4.0.0 models") void shouldNotApplyDependencyInferenceTo400Models() throws Exception { String moduleAPomXml = PomBuilder.create() .namespace("http://maven.apache.org/POM/4.0.0") .modelVersion("4.0.0") .groupId("com.example") .artifactId("module-a") .version("1.0.0") .build(); String moduleBPomXml = PomBuilder.create() .namespace("http://maven.apache.org/POM/4.0.0") .modelVersion("4.0.0") .groupId("com.example") .artifactId("module-b") .version("1.0.0") .dependency("com.example", "module-a", "1.0.0") .build(); Document moduleADoc = Document.of(moduleAPomXml); Document moduleBDoc = Document.of(moduleBPomXml); Map<Path, Document> pomMap = new HashMap<>(); pomMap.put(Paths.get("project", "module-a", "pom.xml"), moduleADoc); pomMap.put(Paths.get("project", "module-b", "pom.xml"), moduleBDoc); Editor editor = new Editor(moduleBDoc); Element moduleBRoot = editor.root(); Element dependency = moduleBRoot .child("dependencies") .orElse(null) .children("dependency") .findFirst() .orElse(null); // Verify dependency elements exist before inference assertNotNull(dependency.child("groupId").orElse(null)); assertNotNull(dependency.child("artifactId").orElse(null)); assertNotNull(dependency.child("version").orElse(null)); // Apply inference UpgradeContext context = createMockContext(); strategy.apply(context, pomMap); // Verify dependency inference was NOT applied (all elements should remain for 4.0.0) assertNotNull(dependency.child("groupId").orElse(null)); assertNotNull(dependency.child("artifactId").orElse(null)); assertNotNull(dependency.child("version").orElse(null)); } } @Nested @DisplayName("Strategy Description")
Maven400LimitedInferenceTests
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/FormListTest.java
{ "start": 1609, "end": 1686 }
class ____ { @RestForm public List<String> input2; } }
Holder
java
playframework__playframework
dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/tests/test/LongParamTest.java
{ "start": 395, "end": 13000 }
class ____ extends AbstractRoutesTest { private static final List<Long> defaultList = List.of(1L, 2L, 3L); private static final List<Long> testList = List.of(7L, -8L, 3_000_000_000L); /** Tests route {@code /long-p} {@link LongController#path}. */ @Test public void checkPath() { var path = "/long-p"; // Correct value checkResult(path + "/789", okContains("789")); checkResult(path + "/-789", okContains("-789")); // Without param checkResult(path, this::notFound); // Incorrect value checkResult( path + "/10000000000000000000", this::badRequestCannotParseParameter); // 10^19 > 2^63 checkResult(path + "/1.0", this::badRequestCannotParseParameter); checkResult(path + "/invalid", this::badRequestCannotParseParameter); // Reverse route assertThat(LongController.path(null).url()).isEqualTo(path + "/0"); assertThat(LongController.path(789L).url()).isEqualTo(path + "/789"); assertThat(LongController.path(-789L).url()).isEqualTo(path + "/-789"); } /** Tests route {@code /long} {@link LongController#query}. */ @Test public void checkQuery() { var path = "/long"; // Correct value checkResult(path, "x=789", okContains("789")); checkResult(path, "x=-789", okContains("-789")); // Without/Empty/NoValue param checkResult(path, this::badRequestMissingParameter); checkResult(path, "x", this::badRequestMissingParameter); checkResult(path, "x=", this::badRequestMissingParameter); // Incorrect value checkResult( path, "x=10000000000000000000", this::badRequestCannotParseParameter); // 10^19 > 2^63 checkResult(path, "x=1.0", this::badRequestCannotParseParameter); checkResult(path, "x=invalid", this::badRequestCannotParseParameter); // Reverse route assertThat(LongController.query(null).url()).isEqualTo(path + "?x=0"); assertThat(LongController.query(789L).url()).isEqualTo(path + "?x=789"); assertThat(LongController.query(-789L).url()).isEqualTo(path + "?x=-789"); } /** Tests route {@code /long-d} {@link LongController#queryDefault}. */ @Test public void checkQueryDefault() { var path = "/long-d"; // Correct value checkResult(path, "x?%3D=789", okContains("789")); checkResult(path, "x?%3D=-789", okContains("-789")); // Without/Empty/NoValue param checkResult(path, okContains("123")); checkResult(path, "x?%3D", okContains("123")); checkResult(path, "x?%3D=", okContains("123")); // Incorrect value checkResult( path, "x?%3D=10000000000000000000", this::badRequestCannotParseParameter); // 10^19 > 2^63 checkResult(path, "x?%3D=1.0", this::badRequestCannotParseParameter); checkResult(path, "x?%3D=invalid", this::badRequestCannotParseParameter); // Reverse route assertThat(LongController.queryDefault(null).url()).isEqualTo(path + "?x%3F%3D=0"); assertThat(LongController.queryDefault(123L).url()).isEqualTo(path); assertThat(LongController.queryDefault(789L).url()).isEqualTo(path + "?x%3F%3D=789"); assertThat(LongController.queryDefault(-789L).url()).isEqualTo(path + "?x%3F%3D=-789"); } /** Tests route {@code /long-f} {@link LongController#queryFixed}. */ @Test public void checkQueryFixed() { var path = "/long-f"; // Correct value checkResult(path, "x=789", okContains("123")); // Without/Empty/NoValue param checkResult(path, okContains("123")); checkResult(path, "x", okContains("123")); checkResult(path, "x=", okContains("123")); // Incorrect value checkResult(path, "x=invalid", okContains("123")); // Reverse route assertThat(LongController.queryFixed().url()).isEqualTo(path); } /** Tests route {@code /long-null} {@link LongController#queryNullable}. */ @Test public void checkQueryNullable() { var path = "/long-null"; // Correct value checkResult(path, "x?=789", okContains("789")); checkResult(path, "x?=-789", okContains("-789")); // Without/Empty/NoValue param checkResult(path, okContains("null")); checkResult(path, "x?", okContains("null")); checkResult(path, "x?=", okContains("null")); // Incorrect value checkResult( path, "x?=10000000000000000000", this::badRequestCannotParseParameter); // 10^19 > 2^63 checkResult(path, "x?=1.0", this::badRequestCannotParseParameter); checkResult(path, "x?=invalid", this::badRequestCannotParseParameter); // Reverse route assertThat(LongController.queryNullable(null).url()).isEqualTo(path); assertThat(LongController.queryNullable(789L).url()).isEqualTo(path + "?x%3F=789"); assertThat(LongController.queryNullable(-789L).url()).isEqualTo(path + "?x%3F=-789"); } /** Tests route {@code /long-opt} {@link LongController#queryOptional}. */ @Test public void checkQueryOptional() { var path = "/long-opt"; // Correct value checkResult(path, "x?=789", okContains("789")); checkResult(path, "x?=-789", okContains("-789")); // Without/Empty/NoValue param checkResult(path, this::okEmptyOptional); checkResult(path, "x?", this::okEmptyOptional); checkResult(path, "x?=", this::okEmptyOptional); // Incorrect value checkResult( path, "x?=10000000000000000000", this::badRequestCannotParseParameter); // 10^19 > 2^63 checkResult(path, "x?=1.0", this::badRequestCannotParseParameter); checkResult(path, "x?=invalid", this::badRequestCannotParseParameter); // Reverse route assertThat(LongController.queryOptional(Optional.empty()).url()).isEqualTo(path); assertThat(LongController.queryOptional(Optional.of(789L)).url()).isEqualTo(path + "?x%3F=789"); assertThat(LongController.queryOptional(Optional.of(-789L)).url()) .isEqualTo(path + "?x%3F=-789"); } /** Tests route {@code /long-opt-d} {@link LongController#queryOptionalDefault}. */ @Test public void checkQueryOptionalDefault() { var path = "/long-opt-d"; // Correct value checkResult(path, "x?%3D=789", okContains("789")); checkResult(path, "x?%3D=-789", okContains("-789")); // Without/Empty/NoValue param checkResult(path, okContains("123")); checkResult(path, "x?%3D", okContains("123")); checkResult(path, "x?%3D=", okContains("123")); // Incorrect value checkResult( path, "x?%3D=10000000000000000000", this::badRequestCannotParseParameter); // 10^19 > 2^63 checkResult(path, "x?%3D=1.0", this::badRequestCannotParseParameter); checkResult(path, "x?%3D=invalid", this::badRequestCannotParseParameter); // Reverse route assertThat(LongController.queryOptionalDefault(Optional.empty()).url()).isEqualTo(path); assertThat(LongController.queryOptionalDefault(Optional.of(123L)).url()).isEqualTo(path); assertThat(LongController.queryOptionalDefault(Optional.of(789L)).url()) .isEqualTo(path + "?x%3F%3D=789"); assertThat(LongController.queryOptionalDefault(Optional.of(-789L)).url()) .isEqualTo(path + "?x%3F%3D=-789"); } /** Tests route {@code /long-list} {@link LongController#queryList}. */ @Test public void checkQueryList() { var path = "/long-list"; // Correct value checkResult(path, "x[]=7&x[]=-8&x[]=", okContains("7,-8")); // Without/Empty/NoValue param checkResult(path, this::okEmpty); checkResult(path, "x[]", this::okEmpty); checkResult(path, "x[]=", this::okEmpty); // Incorrect value checkResult( path, "x[]=10000000000000000000", this::badRequestCannotParseParameter); // 10^19 > 2^63 checkResult(path, "x[]=1.0", this::badRequestCannotParseParameter); checkResult(path, "x[]=invalid", this::badRequestCannotParseParameter); // Reverse route assertThat(LongController.queryList(List.of()).url()).isEqualTo(path); assertThat(LongController.queryList(testList).url()) .isEqualTo(path + "?x%5B%5D=7&x%5B%5D=-8&x%5B%5D=3000000000"); } /** Tests route {@code /long-list-d} {@link LongController#queryListDefault}. */ @Test public void checkQueryListDefault() { var path = "/long-list-d"; // Correct value checkResult(path, "x[]%3D=7&x[]%3D=-8&x[]%3D=", okContains("7,-8")); // Without/Empty/NoValue param checkResult(path, okContains("1,2,3")); checkResult(path, "x[]%3D", okContains("1,2,3")); checkResult(path, "x[]%3D=", okContains("1,2,3")); // Incorrect value checkResult( path, "x[]%3D=1&x[]%3D=10000000000000000000", // 10^19 > 2^63 this::badRequestCannotParseParameter); checkResult(path, "x[]%3D=1&x[]%3D=1.0", this::badRequestCannotParseParameter); checkResult(path, "x[]%3D=1&x[]%3D=invalid", this::badRequestCannotParseParameter); // Reverse route assertThat(LongController.queryListDefault(List.of()).url()).isEqualTo(path); assertThat(LongController.queryListDefault(defaultList).url()).isEqualTo(path); assertThat(LongController.queryListDefault(testList).url()) .isEqualTo(path + "?x%5B%5D%3D=7&x%5B%5D%3D=-8&x%5B%5D%3D=3000000000"); } /** Tests route {@code /long-list-null} {@link LongController#queryListNullable}. */ @Test public void checkQueryListNullable() { var path = "/long-list-null"; // Correct value checkResult(path, "x[]?=7&x[]?=-8&x[]?=", okContains("7,-8")); // Without/Empty/NoValue param checkResult(path, okContains("null")); checkResult(path, "x[]?", okContains("null")); checkResult(path, "x[]?=", okContains("null")); // Incorrect value checkResult( path, "x[]?=1&x[]?=10000000000000000000", // 10^19 > 2^63 this::badRequestCannotParseParameter); checkResult(path, "x[]?=1&x[]?=1.0", this::badRequestCannotParseParameter); checkResult(path, "x[]?=1&x[]?=invalid", this::badRequestCannotParseParameter); // Reverse route assertThat(LongController.queryListNullable(null).url()).isEqualTo(path); assertThat(LongController.queryListNullable(List.of()).url()).isEqualTo(path); assertThat(LongController.queryListNullable(testList).url()) .isEqualTo(path + "?x%5B%5D%3F=7&x%5B%5D%3F=-8&x%5B%5D%3F=3000000000"); } /** Tests route {@code /long-list-opt} {@link LongController#queryListOptional}. */ @Test public void checkQueryListOptional() { var path = "/long-list-opt"; // Correct value checkResult(path, "x[]?=7&x[]?=-8&x[]?=", okContains("7,-8")); // Without/Empty/NoValue param checkResult(path, this::okEmpty); checkResult(path, "x[]?", this::okEmpty); checkResult(path, "x[]?=", this::okEmpty); // Incorrect value checkResult( path, "x[]?=1&x[]?=10000000000000000000", // 10^19 > 2^63 this::badRequestCannotParseParameter); checkResult(path, "x[]?=1&x[]?=1.0", this::badRequestCannotParseParameter); checkResult(path, "x[]?=1&x[]?=invalid", this::badRequestCannotParseParameter); // Reverse route assertThat(LongController.queryListOptional(Optional.empty()).url()).isEqualTo(path); assertThat(LongController.queryListOptional(Optional.of(List.of())).url()).isEqualTo(path); assertThat(LongController.queryListOptional(Optional.of(testList)).url()) .isEqualTo(path + "?x%5B%5D%3F=7&x%5B%5D%3F=-8&x%5B%5D%3F=3000000000"); } /** Tests route {@code /long-list-opt-d} {@link LongController#queryListOptionalDefault}. */ @Test public void checkQueryListOptionalDefault() { var path = "/long-list-opt-d"; // Correct value checkResult(path, "x[]?%3D=7&x[]?%3D=-8&x[]?%3D=", okContains("7,-8")); // Without/Empty/NoValue param checkResult(path, okContains("1,2,3")); checkResult(path, "x[]?%3D", okContains("1,2,3")); checkResult(path, "x[]?%3D=", okContains("1,2,3")); // Incorrect value checkResult( path, "x[]?%3D=1&x[]?%3D=10000000000000000000", // 10^19 > 2^63 this::badRequestCannotParseParameter); checkResult(path, "x[]?%3D=1&x[]?%3D=1.0", this::badRequestCannotParseParameter); checkResult(path, "x[]?%3D=1&x[]?%3D=invalid", this::badRequestCannotParseParameter); // Reverse route assertThat(LongController.queryListOptionalDefault(Optional.empty()).url()).isEqualTo(path); assertThat(LongController.queryListOptionalDefault(Optional.of(List.of())).url()) .isEqualTo(path); assertThat(LongController.queryListOptionalDefault(Optional.of(defaultList)).url()) .isEqualTo(path); assertThat(LongController.queryListOptionalDefault(Optional.of(testList)).url()) .isEqualTo(path + "?x%5B%5D%3F%3D=7&x%5B%5D%3F%3D=-8&x%5B%5D%3F%3D=3000000000"); } }
LongParamTest
java
spring-projects__spring-boot
module/spring-boot-restclient-test/src/main/java/org/springframework/boot/restclient/test/MockServerRestClientCustomizer.java
{ "start": 3368, "end": 5945 }
class ____ use */ public MockServerRestClientCustomizer(Class<? extends RequestExpectationManager> expectationManager) { this(() -> BeanUtils.instantiateClass(expectationManager)); Assert.notNull(expectationManager, "'expectationManager' must not be null"); } /** * Create a new {@link MockServerRestClientCustomizer} instance. * @param expectationManagerSupplier a supplier that provides the * {@link RequestExpectationManager} to use */ public MockServerRestClientCustomizer(Supplier<? extends RequestExpectationManager> expectationManagerSupplier) { Assert.notNull(expectationManagerSupplier, "'expectationManagerSupplier' must not be null"); this.expectationManagerSupplier = expectationManagerSupplier; } /** * Set if the {@link BufferingClientHttpRequestFactory} wrapper should be used to * buffer the input and output streams, and for example, allow multiple reads of the * response body. * @param bufferContent if request and response content should be buffered */ public void setBufferContent(boolean bufferContent) { this.bufferContent = bufferContent; } @Override public void customize(RestClient.Builder restClientBuilder) { RequestExpectationManager expectationManager = createExpectationManager(); MockRestServiceServerBuilder serverBuilder = MockRestServiceServer.bindTo(restClientBuilder); if (this.bufferContent) { serverBuilder.bufferContent(); } MockRestServiceServer server = serverBuilder.build(expectationManager); this.expectationManagers.put(restClientBuilder, expectationManager); this.servers.put(restClientBuilder, server); } protected RequestExpectationManager createExpectationManager() { return this.expectationManagerSupplier.get(); } public MockRestServiceServer getServer() { Assert.state(!this.servers.isEmpty(), "Unable to return a single MockRestServiceServer since " + "MockServerRestClientCustomizer has not been bound to a RestClient"); Assert.state(this.servers.size() == 1, "Unable to return a single MockRestServiceServer since " + "MockServerRestClientCustomizer has been bound to more than one RestClient"); return this.servers.values().iterator().next(); } public Map<RestClient.Builder, RequestExpectationManager> getExpectationManagers() { return this.expectationManagers; } public @Nullable MockRestServiceServer getServer(RestClient.Builder restClientBuilder) { return this.servers.get(restClientBuilder); } public Map<RestClient.Builder, MockRestServiceServer> getServers() { return Collections.unmodifiableMap(this.servers); } }
to
java
hibernate__hibernate-orm
local-build-plugins/src/main/java/org/hibernate/orm/antlr/AntlrSpec.java
{ "start": 481, "end": 1762 }
class ____ { public static final String REGISTRATION_NAME = "antlr4"; private final DirectoryProperty grammarBaseDirectory; private final DirectoryProperty outputBaseDirectory; private final NamedDomainObjectContainer<SplitGrammarDescriptor> grammarDescriptors; @Inject @SuppressWarnings("UnstableApiUsage") public AntlrSpec(Project project, TaskProvider<Task> groupingTask) { final ObjectFactory objectFactory = project.getObjects(); final ProjectLayout layout = project.getLayout(); grammarBaseDirectory = objectFactory.directoryProperty(); grammarBaseDirectory.convention( layout.getProjectDirectory().dir( "src/main/antlr" ) ); outputBaseDirectory = objectFactory.directoryProperty(); outputBaseDirectory.convention( layout.getBuildDirectory().dir( "generated/sources/antlr/main" ) ); grammarDescriptors = objectFactory.domainObjectContainer( SplitGrammarDescriptor.class, new GrammarDescriptorFactory( this, groupingTask, project ) ); } public DirectoryProperty getGrammarBaseDirectory() { return grammarBaseDirectory; } public DirectoryProperty getOutputBaseDirectory() { return outputBaseDirectory; } public NamedDomainObjectContainer<SplitGrammarDescriptor> getGrammarDescriptors() { return grammarDescriptors; } }
AntlrSpec
java
apache__camel
components/camel-dapr/src/generated/java/org/apache/camel/component/dapr/DaprTypeConverterLoader.java
{ "start": 880, "end": 2200 }
class ____ implements TypeConverterLoader, CamelContextAware { private CamelContext camelContext; public DaprTypeConverterLoader() { } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void load(TypeConverterRegistry registry) throws TypeConverterLoaderException { registerConverters(registry); } private void registerConverters(TypeConverterRegistry registry) { addTypeConverter(registry, io.dapr.client.domain.HttpExtension.class, java.lang.String.class, true, (type, exchange, value) -> { Object answer = org.apache.camel.component.dapr.DaprTypeConverter.toHttpExtension((java.lang.String) value); if (true && answer == null) { answer = Void.class; } return answer; }); } private static void addTypeConverter(TypeConverterRegistry registry, Class<?> toType, Class<?> fromType, boolean allowNull, SimpleTypeConverter.ConversionMethod method) { registry.addTypeConverter(toType, fromType, new SimpleTypeConverter(allowNull, method)); } }
DaprTypeConverterLoader
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/iterables/Iterables_assertAreAtMost_Test.java
{ "start": 1532, "end": 2891 }
class ____ extends IterablesWithConditionsBaseTest { @Test void should_pass_if_satisfies_at_most_times_condition() { actual = newArrayList("Yoda", "Luke", "Leia"); iterables.assertAreAtMost(someInfo(), actual, 2, jedi); verify(conditions).assertIsNotNull(jedi); } @Test void should_pass_if_never_satisfies_condition_() { actual = newArrayList("Chewbacca", "Leia", "Obiwan"); iterables.assertAreAtMost(someInfo(), actual, 2, jedi); verify(conditions).assertIsNotNull(jedi); } @Test void should_throw_error_if_condition_is_null() { assertThatNullPointerException().isThrownBy(() -> { actual = newArrayList("Yoda", "Luke"); iterables.assertAreAtMost(someInfo(), actual, 2, null); }).withMessage("The condition to evaluate should not be null"); verify(conditions).assertIsNotNull(null); } @Test void should_fail_if_condition_is_not_met_much() { testCondition.shouldMatch(false); AssertionInfo info = someInfo(); actual = newArrayList("Yoda", "Luke", "Obiwan"); Throwable error = catchThrowable(() -> iterables.assertAreAtMost(someInfo(), actual, 2, jedi)); assertThat(error).isInstanceOf(AssertionError.class); verify(conditions).assertIsNotNull(jedi); verify(failures).failure(info, elementsShouldBeAtMost(actual, 2, jedi)); } }
Iterables_assertAreAtMost_Test
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/accesstype/AttributeAccessorTest.java
{ "start": 1011, "end": 1715 }
class ____ { @Test public void testAttributeAccessor(EntityManagerFactoryScope scope) { scope.getEntityManagerFactory(); // force building the metamodel // Verify that the accessor was triggered during metadata building phase. assertTrue( BasicAttributeAccessor.invoked ); // Create an audited entity scope.inTransaction( entityManager -> { final Foo foo = new Foo( 1, "ABC" ); entityManager.persist( foo ); } ); // query the entity. scope.inEntityManager( entityManager -> { final Foo foo = AuditReaderFactory.get( entityManager ).find( Foo.class, 1, 1 ); assertEquals( "ABC", foo.getName() ); } ); } @Entity(name = "Foo") @Audited public static
AttributeAccessorTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/common/util/ObjectObjectPagedHashMapTests.java
{ "start": 1057, "end": 3723 }
class ____ extends ESTestCase { private BigArrays mockBigArrays(CircuitBreakerService service) { return new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), service, true); } public void testDuel() { // first with cranky try { doTestDuel(mockBigArrays(new CrankyCircuitBreakerService())); } catch (CircuitBreakingException ex) { assertThat(ex.getMessage(), equalTo("cranky breaker")); } // then to the end doTestDuel(mockBigArrays(new NoneCircuitBreakerService())); } private void doTestDuel(BigArrays bigArrays) { final Map<BytesRef, Object> map1 = new HashMap<>(); try ( ObjectObjectPagedHashMap<BytesRef, Object> map2 = new ObjectObjectPagedHashMap<>( randomInt(42), 0.6f + randomFloat() * 0.39f, bigArrays ) ) { final int maxKey = randomIntBetween(1, 10000); BytesRef[] bytesRefs = new BytesRef[maxKey]; for (int i = 0; i < maxKey; i++) { bytesRefs[i] = randomBytesRef(); } final int iters = scaledRandomIntBetween(10000, 100000); for (int i = 0; i < iters; ++i) { final boolean put = randomBoolean(); final int iters2 = randomIntBetween(1, 100); for (int j = 0; j < iters2; ++j) { final BytesRef key = bytesRefs[random().nextInt(maxKey)]; if (put) { final Object value = new Object(); assertSame(map1.put(key, value), map2.put(key, value)); } else { assertSame(map1.remove(key), map2.remove(key)); } assertEquals(map1.size(), map2.size()); } } for (int i = 0; i < maxKey; i++) { assertSame(map1.get(bytesRefs[i]), map2.get(bytesRefs[i])); } final Map<BytesRef, Object> copy = new HashMap<>(); for (ObjectObjectPagedHashMap.Cursor<BytesRef, Object> cursor : map2) { copy.put(cursor.key, cursor.value); } assertEquals(map1, copy); } } private BytesRef randomBytesRef() { byte[] bytes = new byte[randomIntBetween(2, 20)]; random().nextBytes(bytes); return new BytesRef(bytes); } public void testAllocation() { MockBigArrays.assertFitsIn(ByteSizeValue.ofBytes(256), bigArrays -> new ObjectObjectPagedHashMap<>(1, bigArrays)); } }
ObjectObjectPagedHashMapTests
java
google__guice
extensions/assistedinject/src/com/google/inject/assistedinject/internal/LookupTester.java
{ "start": 427, "end": 536 }
interface ____ { default Hidden method() { return null; } } private LookupTester() {} }
Hidden
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AtmosphereWebsocketEndpointBuilderFactory.java
{ "start": 1610, "end": 17597 }
interface ____ extends EndpointConsumerBuilder { default AdvancedAtmosphereWebsocketEndpointConsumerBuilder advanced() { return (AdvancedAtmosphereWebsocketEndpointConsumerBuilder) this; } /** * If this option is false the Servlet will disable the HTTP streaming * and set the content-length header on the response. * * The option is a: <code>boolean</code> type. * * Default: true * Group: common * * @param chunked the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder chunked(boolean chunked) { doSetProperty("chunked", chunked); return this; } /** * If this option is false the Servlet will disable the HTTP streaming * and set the content-length header on the response. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: common * * @param chunked the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder chunked(String chunked) { doSetProperty("chunked", chunked); return this; } /** * Determines whether or not the raw input stream is cached or not. The * Camel consumer (camel-servlet, camel-jetty etc.) will by default * cache the input stream to support reading it multiple times to ensure * it Camel can retrieve all data from the stream. However you can set * this option to true when you for example need to access the raw * stream, such as streaming it directly to a file or other persistent * store. DefaultHttpBinding will copy the request input stream into a * stream cache and put it into message body if this option is false to * support reading the stream multiple times. If you use Servlet to * bridge/proxy an endpoint then consider enabling this option to * improve performance, in case you do not need to read the message * payload multiple times. The producer (camel-http) will by default * cache the response body stream. If setting this option to true, then * the producers will not cache the response body stream but use the * response stream as-is (the stream can only be read once) as the * message body. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param disableStreamCache the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder disableStreamCache(boolean disableStreamCache) { doSetProperty("disableStreamCache", disableStreamCache); return this; } /** * Determines whether or not the raw input stream is cached or not. The * Camel consumer (camel-servlet, camel-jetty etc.) will by default * cache the input stream to support reading it multiple times to ensure * it Camel can retrieve all data from the stream. However you can set * this option to true when you for example need to access the raw * stream, such as streaming it directly to a file or other persistent * store. DefaultHttpBinding will copy the request input stream into a * stream cache and put it into message body if this option is false to * support reading the stream multiple times. If you use Servlet to * bridge/proxy an endpoint then consider enabling this option to * improve performance, in case you do not need to read the message * payload multiple times. The producer (camel-http) will by default * cache the response body stream. If setting this option to true, then * the producers will not cache the response body stream but use the * response stream as-is (the stream can only be read once) as the * message body. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param disableStreamCache the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder disableStreamCache(String disableStreamCache) { doSetProperty("disableStreamCache", disableStreamCache); return this; } /** * Whether to send to all (broadcast) or send to a single receiver. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param sendToAll the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder sendToAll(boolean sendToAll) { doSetProperty("sendToAll", sendToAll); return this; } /** * Whether to send to all (broadcast) or send to a single receiver. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param sendToAll the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder sendToAll(String sendToAll) { doSetProperty("sendToAll", sendToAll); return this; } /** * If enabled and an Exchange failed processing on the consumer side, * and if the caused Exception was send back serialized in the response * as a application/x-java-serialized-object content type. On the * producer side the exception will be deserialized and thrown as is, * instead of the HttpOperationFailedException. The caused exception is * required to be serialized. This is by default turned off. If you * enable this then be aware that Java will deserialize the incoming * data from the request to Java and that can be a potential security * risk. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param transferException the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder transferException(boolean transferException) { doSetProperty("transferException", transferException); return this; } /** * If enabled and an Exchange failed processing on the consumer side, * and if the caused Exception was send back serialized in the response * as a application/x-java-serialized-object content type. On the * producer side the exception will be deserialized and thrown as is, * instead of the HttpOperationFailedException. The caused exception is * required to be serialized. This is by default turned off. If you * enable this then be aware that Java will deserialize the incoming * data from the request to Java and that can be a potential security * risk. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param transferException the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder transferException(String transferException) { doSetProperty("transferException", transferException); return this; } /** * To enable streaming to send data as multiple text fragments. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param useStreaming the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder useStreaming(boolean useStreaming) { doSetProperty("useStreaming", useStreaming); return this; } /** * To enable streaming to send data as multiple text fragments. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param useStreaming the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder useStreaming(String useStreaming) { doSetProperty("useStreaming", useStreaming); return this; } /** * Configure the consumer to work in async mode. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer * * @param async the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder async(boolean async) { doSetProperty("async", async); return this; } /** * Configure the consumer to work in async mode. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer * * @param async the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder async(String async) { doSetProperty("async", async); return this; } /** * Used to only allow consuming if the HttpMethod matches, such as * GET/POST/PUT etc. Multiple methods can be specified separated by * comma. * * The option is a: <code>java.lang.String</code> type. * * Group: consumer * * @param httpMethodRestrict the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder httpMethodRestrict(String httpMethodRestrict) { doSetProperty("httpMethodRestrict", httpMethodRestrict); return this; } /** * If enabled and an Exchange failed processing on the consumer side the * exception's stack trace will be logged when the exception stack trace * is not sent in the response's body. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer * * @param logException the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder logException(boolean logException) { doSetProperty("logException", logException); return this; } /** * If enabled and an Exchange failed processing on the consumer side the * exception's stack trace will be logged when the exception stack trace * is not sent in the response's body. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer * * @param logException the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder logException(String logException) { doSetProperty("logException", logException); return this; } /** * Whether or not the consumer should try to find a target consumer by * matching the URI prefix if no exact match is found. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer * * @param matchOnUriPrefix the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder matchOnUriPrefix(boolean matchOnUriPrefix) { doSetProperty("matchOnUriPrefix", matchOnUriPrefix); return this; } /** * Whether or not the consumer should try to find a target consumer by * matching the URI prefix if no exact match is found. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer * * @param matchOnUriPrefix the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder matchOnUriPrefix(String matchOnUriPrefix) { doSetProperty("matchOnUriPrefix", matchOnUriPrefix); return this; } /** * If enabled and an Exchange failed processing on the consumer side the * response's body won't contain the exception's stack trace. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer * * @param muteException the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder muteException(boolean muteException) { doSetProperty("muteException", muteException); return this; } /** * If enabled and an Exchange failed processing on the consumer side the * response's body won't contain the exception's stack trace. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer * * @param muteException the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder muteException(String muteException) { doSetProperty("muteException", muteException); return this; } /** * To use a custom buffer size on the jakarta.servlet.ServletResponse. * * The option is a: <code>java.lang.Integer</code> type. * * Group: consumer * * @param responseBufferSize the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder responseBufferSize(Integer responseBufferSize) { doSetProperty("responseBufferSize", responseBufferSize); return this; } /** * To use a custom buffer size on the jakarta.servlet.ServletResponse. * * The option will be converted to a <code>java.lang.Integer</code> * type. * * Group: consumer * * @param responseBufferSize the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder responseBufferSize(String responseBufferSize) { doSetProperty("responseBufferSize", responseBufferSize); return this; } /** * Name of the servlet to use. * * The option is a: <code>java.lang.String</code> type. * * Default: CamelServlet * Group: consumer * * @param servletName the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointConsumerBuilder servletName(String servletName) { doSetProperty("servletName", servletName); return this; } } /** * Advanced builder for endpoint consumers for the Atmosphere Websocket component. */ public
AtmosphereWebsocketEndpointConsumerBuilder
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/TestReplicaMap.java
{ "start": 1283, "end": 4283 }
class ____ { private final ReplicaMap map = new ReplicaMap(); private final String bpid = "BP-TEST"; private final Block block = new Block(1234, 1234, 1234); @BeforeEach public void setup() { map.add(bpid, new FinalizedReplica(block, null, null)); } /** * Test for ReplicasMap.get(Block) and ReplicasMap.get(long) tests */ @Test public void testGet() { // Test 1: null argument throws invalid argument exception try { map.get(bpid, null); fail("Expected exception not thrown"); } catch (IllegalArgumentException expected) { } // Test 2: successful lookup based on block assertNotNull(map.get(bpid, block)); // Test 3: Lookup failure - generation stamp mismatch Block b = new Block(block); b.setGenerationStamp(0); assertNull(map.get(bpid, b)); // Test 4: Lookup failure - blockID mismatch b.setGenerationStamp(block.getGenerationStamp()); b.setBlockId(0); assertNull(map.get(bpid, b)); // Test 5: successful lookup based on block ID assertNotNull(map.get(bpid, block.getBlockId())); // Test 6: failed lookup for invalid block ID assertNull(map.get(bpid, 0)); } @Test public void testAdd() { // Test 1: null argument throws invalid argument exception try { map.add(bpid, null); fail("Expected exception not thrown"); } catch (IllegalArgumentException expected) { } } @Test public void testRemove() { // Test 1: null argument throws invalid argument exception try { map.remove(bpid, null); fail("Expected exception not thrown"); } catch (IllegalArgumentException expected) { } // Test 2: remove failure - generation stamp mismatch Block b = new Block(block); b.setGenerationStamp(0); assertNull(map.remove(bpid, b)); // Test 3: remove failure - blockID mismatch b.setGenerationStamp(block.getGenerationStamp()); b.setBlockId(0); assertNull(map.remove(bpid, b)); // Test 4: remove success assertNotNull(map.remove(bpid, block)); // Test 5: remove failure - invalid blockID assertNull(map.remove(bpid, 0)); // Test 6: remove success map.add(bpid, new FinalizedReplica(block, null, null)); assertNotNull(map.remove(bpid, block.getBlockId())); } @Test public void testMergeAll() { ReplicaMap temReplicaMap = new ReplicaMap(); Block tmpBlock = new Block(5678, 5678, 5678); temReplicaMap.add(bpid, new FinalizedReplica(tmpBlock, null, null)); map.mergeAll(temReplicaMap); assertNotNull(map.get(bpid, 1234)); assertNotNull(map.get(bpid, 5678)); } @Test public void testAddAll() { ReplicaMap temReplicaMap = new ReplicaMap(); Block tmpBlock = new Block(5678, 5678, 5678); temReplicaMap.add(bpid, new FinalizedReplica(tmpBlock, null, null)); map.addAll(temReplicaMap); assertNull(map.get(bpid, 1234)); assertNotNull(map.get(bpid, 5678)); } }
TestReplicaMap
java
apache__dubbo
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/tool/DubboMcpGenericCaller.java
{ "start": 1352, "end": 5975 }
class ____ { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboMcpGenericCaller.class); private final ApplicationConfig applicationConfig; private final Map<String, GenericService> serviceCache = new ConcurrentHashMap<>(); public DubboMcpGenericCaller(ApplicationModel applicationModel) { if (applicationModel == null) { logger.error( COMMON_UNEXPECTED_EXCEPTION, "", "", "ApplicationModel cannot be null for DubboMcpGenericCaller."); throw new IllegalArgumentException("ApplicationModel cannot be null."); } this.applicationConfig = applicationModel.getCurrentConfig(); if (this.applicationConfig == null) { String errMsg = "ApplicationConfig is null in the provided ApplicationModel. Application Name: " + (applicationModel.getApplicationName() != null ? applicationModel.getApplicationName() : "N/A"); logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", errMsg); throw new IllegalStateException(errMsg); } } public Object execute( String interfaceName, String methodName, List<String> orderedJavaParameterNames, Class<?>[] parameterJavaTypes, Map<String, Object> mcpProvidedParameters, String group, String version) { String cacheKey = interfaceName + ":" + (group == null ? "" : group) + ":" + (version == null ? "" : version); GenericService genericService = serviceCache.get(cacheKey); if (genericService == null) { ReferenceConfig<GenericService> reference = new ReferenceConfig<>(); reference.setApplication(this.applicationConfig); reference.setInterface(interfaceName); reference.setGeneric("true"); // Defaults to 'bean' or 'true' for POJO generalization. reference.setScope("local"); if (group != null && !group.isEmpty()) { reference.setGroup(group); } if (version != null && !version.isEmpty()) { reference.setVersion(version); } try { genericService = reference.get(); if (genericService != null) { serviceCache.put(cacheKey, genericService); } else { String errorMessage = "Failed to obtain GenericService instance for " + interfaceName + (group != null ? " group " + group : "") + (version != null ? " version " + version : ""); logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", errorMessage); throw new IllegalStateException(errorMessage); } } catch (Exception e) { String errorMessage = "Error obtaining GenericService for " + interfaceName + ": " + e.getMessage(); logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", errorMessage, e); throw new RuntimeException(errorMessage, e); } } String[] invokeParameterTypes = new String[parameterJavaTypes.length]; for (int i = 0; i < parameterJavaTypes.length; i++) { invokeParameterTypes[i] = parameterJavaTypes[i].getName(); } Object[] invokeArgs = new Object[orderedJavaParameterNames.size()]; for (int i = 0; i < orderedJavaParameterNames.size(); i++) { String paramName = orderedJavaParameterNames.get(i); if (mcpProvidedParameters.containsKey(paramName)) { invokeArgs[i] = mcpProvidedParameters.get(paramName); } else { invokeArgs[i] = null; logger.warn( COMMON_UNEXPECTED_EXCEPTION, "", "", "Parameter '" + paramName + "' not found in MCP provided parameters for method '" + methodName + "' of interface '" + interfaceName + "'. Will use null."); } } try { return genericService.$invoke(methodName, invokeParameterTypes, invokeArgs); } catch (Exception e) { String errorMessage = "GenericService $invoke failed for method '" + methodName + "' on interface '" + interfaceName + "': " + e.getMessage(); logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", errorMessage, e); throw new RuntimeException(errorMessage, e); } } }
DubboMcpGenericCaller
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/unproxyable/ProducerFailedToAddMissingNoargsConstructorTest.java
{ "start": 1166, "end": 1286 }
class ____ extends MyBase { public MyBean(String foo) { super(foo); } } static
MyBean
java
quarkusio__quarkus
extensions/smallrye-health/deployment/src/test/java/io/quarkus/smallrye/health/test/AsyncDispatchedThreadTest.java
{ "start": 2151, "end": 2667 }
class ____ implements AsyncHealthCheck { @Override public Uni<HealthCheckResponse> call() { return Uni.createFrom().item(HealthCheckResponse.named("my-liveness-check") .up() .withData("thread", Thread.currentThread().getName()) .withData("request", Arc.container().requestContext().isActive()) .build()); } } @ApplicationScoped @Readiness public static
LivenessHealthCheckCapturingThread
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java
{ "start": 6827, "end": 7688 }
class ____ { private final String httpBase; private final String httpsBase; private final URL localSchemaUrl; public DtdDescriptor(String identifierBase, String resourceName) { this.httpBase = "http://" + identifierBase; this.httpsBase = "https://" + identifierBase; this.localSchemaUrl = LocalSchemaLocator.resolveLocalSchemaUrl( resourceName ); } public String getIdentifierBase() { return httpBase; } public boolean matches(String publicId, String systemId) { if ( publicId != null ) { if ( publicId.startsWith( httpBase ) || publicId.startsWith( httpsBase ) ) { return true; } } if ( systemId != null ) { return systemId.startsWith( httpBase ) || systemId.startsWith( httpsBase ); } return false; } public URL getMappedLocalUrl() { return localSchemaUrl; } } }
DtdDescriptor
java
spring-projects__spring-security
oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverterAdapter.java
{ "start": 1122, "end": 1634 }
class ____ implements Converter<Jwt, Mono<AbstractAuthenticationToken>> { private final Converter<Jwt, AbstractAuthenticationToken> delegate; public ReactiveJwtAuthenticationConverterAdapter(Converter<Jwt, AbstractAuthenticationToken> delegate) { Assert.notNull(delegate, "delegate cannot be null"); this.delegate = delegate; } @Override public final Mono<AbstractAuthenticationToken> convert(Jwt jwt) { return Mono.just(jwt).map(this.delegate::convert); } }
ReactiveJwtAuthenticationConverterAdapter
java
apache__logging-log4j2
log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/resolver/CaseConverterResolver.java
{ "start": 5016, "end": 5331 }
class ____ implements EventResolver { private final TemplateResolver<LogEvent> inputResolver; private final Function<String, String> converter; private final ErrorHandlingStrategy errorHandlingStrategy; private final TemplateResolver<LogEvent> replacementResolver; private
CaseConverterResolver
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/tasks/CancellableTask.java
{ "start": 4669, "end": 5095 }
interface ____ { void onCancelled(); } private record CancellationListenerAdapter(CancellationListener cancellationListener) implements ActionListener<Void> { @Override public void onResponse(Void unused) { cancellationListener.onCancelled(); } @Override public void onFailure(Exception e) { assert false : e; } } }
CancellationListener
java
apache__camel
components/camel-micrometer-observability/src/test/java/org/apache/camel/micrometer/observability/AsyncWiretapTest.java
{ "start": 1719, "end": 7658 }
class ____ extends MicrometerObservabilityTracerPropagationTestSupport { @Test void testRouteMultipleRequests() throws InterruptedException, IOException { int j = 10; MockEndpoint mock = getMockEndpoint("mock:end"); mock.expectedMessageCount(j); mock.setAssertPeriod(5000); for (int i = 0; i < j; i++) { context.createProducerTemplate().sendBody("direct:start", "Hello!"); } mock.assertIsSatisfied(1000); Map<String, OtelTrace> traces = otelExtension.getTraces(); // Each trace should have a unique trace id. It is enough to assert that // the number of elements in the map is the same of the requests to prove // all traces have been generated uniquely. assertEquals(j, traces.size()); // Each trace should have the same structure for (OtelTrace trace : traces.values()) { checkTrace(trace, "Hello!"); } } private void checkTrace(OtelTrace trace, String expectedBody) { List<SpanData> spans = trace.getSpans(); assertEquals(7, spans.size()); SpanData testProducer = getSpan(spans, "direct://start", Op.EVENT_SENT); SpanData direct = getSpan(spans, "direct://start", Op.EVENT_RECEIVED); SpanData wiretapDirectTo = getSpan(spans, "direct://tap", Op.EVENT_SENT); SpanData wiretapDirectFrom = getSpan(spans, "direct://tap", Op.EVENT_RECEIVED); SpanData log = getSpan(spans, "log://info", Op.EVENT_SENT); SpanData wiretapLog = getSpan(spans, "log://tapped", Op.EVENT_SENT); SpanData wiretapMock = getSpan(spans, "mock://end", Op.EVENT_SENT); // Validate span completion assertTrue(testProducer.hasEnded()); assertTrue(direct.hasEnded()); assertTrue(wiretapDirectTo.hasEnded()); assertTrue(log.hasEnded()); assertTrue(wiretapDirectFrom.hasEnded()); assertTrue(wiretapLog.hasEnded()); assertTrue(wiretapMock.hasEnded()); // Validate same trace assertEquals(testProducer.getTraceId(), direct.getTraceId()); assertEquals(testProducer.getTraceId(), wiretapDirectTo.getTraceId()); assertEquals(testProducer.getTraceId(), log.getTraceId()); assertEquals(testProducer.getTraceId(), wiretapDirectFrom.getTraceId()); assertEquals(testProducer.getTraceId(), wiretapLog.getTraceId()); assertEquals(testProducer.getTraceId(), wiretapMock.getTraceId()); // Validate different Exchange ID assertNotEquals(testProducer.getAttributes().get(AttributeKey.stringKey("exchangeId")), wiretapDirectTo.getAttributes().get(AttributeKey.stringKey("exchangeId"))); assertEquals(testProducer.getAttributes().get(AttributeKey.stringKey("exchangeId")), direct.getAttributes().get(AttributeKey.stringKey("exchangeId"))); assertEquals(testProducer.getAttributes().get(AttributeKey.stringKey("exchangeId")), log.getAttributes().get(AttributeKey.stringKey("exchangeId"))); assertEquals(wiretapDirectTo.getAttributes().get(AttributeKey.stringKey("exchangeId")), wiretapDirectFrom.getAttributes().get(AttributeKey.stringKey("exchangeId"))); assertEquals(wiretapDirectTo.getAttributes().get(AttributeKey.stringKey("exchangeId")), wiretapLog.getAttributes().get(AttributeKey.stringKey("exchangeId"))); assertEquals(wiretapDirectTo.getAttributes().get(AttributeKey.stringKey("exchangeId")), wiretapMock.getAttributes().get(AttributeKey.stringKey("exchangeId"))); // Validate hierarchy assertEquals(SpanId.getInvalid(), testProducer.getParentSpanId()); assertEquals(testProducer.getSpanId(), direct.getParentSpanId()); assertEquals(direct.getSpanId(), wiretapDirectTo.getParentSpanId()); assertEquals(direct.getSpanId(), log.getParentSpanId()); assertEquals(wiretapDirectTo.getSpanId(), wiretapDirectFrom.getParentSpanId()); assertEquals(wiretapDirectFrom.getSpanId(), wiretapLog.getParentSpanId()); assertEquals(wiretapDirectFrom.getSpanId(), wiretapMock.getParentSpanId()); // Validate message logging assertEquals("message=A direct message", direct.getEvents().get(0).getName()); assertEquals("message=A tapped message", wiretapDirectFrom.getEvents().get(0).getName()); if (expectedBody == null) { assertEquals( "message=Exchange[ExchangePattern: InOut, BodyType: null, Body: [Body is null]]", log.getEvents().get(0).getName()); assertEquals( "message=Exchange[ExchangePattern: InOut, BodyType: null, Body: [Body is null]]", wiretapLog.getEvents().get(0).getName()); } else { assertEquals( "message=Exchange[ExchangePattern: InOnly, BodyType: String, Body: " + expectedBody + "]", log.getEvents().get(0).getName()); assertEquals( "message=Exchange[ExchangePattern: InOnly, BodyType: String, Body: " + expectedBody + "]", wiretapLog.getEvents().get(0).getName()); } } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .routeId("start") .wireTap("direct:tap") .log("A direct message") .to("log:info"); from("direct:tap") .delay(2000) .routeId("wiretapped") .log("A tapped message") .to("log:tapped") .to("mock:end"); } }; } }
AsyncWiretapTest
java
google__guice
extensions/servlet/src/com/google/inject/servlet/LinkedServletBindingImpl.java
{ "start": 872, "end": 1619 }
class ____ extends AbstractServletModuleBinding<Key<? extends HttpServlet>> implements LinkedServletBinding { LinkedServletBindingImpl( Map<String, String> initParams, Key<? extends HttpServlet> target, UriPatternMatcher patternMatcher) { super(initParams, target, patternMatcher); } @Override public Key<? extends HttpServlet> getLinkedKey() { return getTarget(); } @Override public String toString() { return MoreObjects.toStringHelper(LinkedServletBinding.class) .add("pattern", getPattern()) .add("initParams", getInitParams()) .add("uriPatternType", getUriPatternType()) .add("linkedServletKey", getLinkedKey()) .toString(); } }
LinkedServletBindingImpl
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/coordination/JoinReasonServiceTests.java
{ "start": 1101, "end": 9212 }
class ____ extends ESTestCase { public void testJoinReasonService() { final AtomicLong currentTimeMillis = new AtomicLong(randomLong()); final JoinReasonService joinReasonService = new JoinReasonService(currentTimeMillis::get); final DiscoveryNode master = randomDiscoveryNode(); final DiscoveryNode discoveryNode = randomDiscoveryNode(); final DiscoveryNodes withoutNode = DiscoveryNodes.builder() .add(master) .localNodeId(master.getId()) .masterNodeId(master.getId()) .build(); final DiscoveryNodes withNode = DiscoveryNodes.builder(withoutNode).add(discoveryNode).build(); assertThat(joinReasonService.getJoinReason(discoveryNode, CANDIDATE), matches("completing election")); assertThat(joinReasonService.getJoinReason(discoveryNode, LEADER), matches("joining")); joinReasonService.onClusterStateApplied(withoutNode); assertThat(joinReasonService.getJoinReason(discoveryNode, CANDIDATE), matches("completing election")); assertThat(joinReasonService.getJoinReason(discoveryNode, LEADER), matches("joining")); joinReasonService.onClusterStateApplied(withNode); assertThat(joinReasonService.getJoinReason(discoveryNode, CANDIDATE), matches("completing election")); assertThat(joinReasonService.getJoinReason(discoveryNode, LEADER), matches("rejoining")); joinReasonService.onClusterStateApplied(withoutNode); currentTimeMillis.addAndGet(1234L); assertThat( joinReasonService.getJoinReason(discoveryNode, LEADER), matchesNeedingGuidance("joining, removed [1.2s/1234ms] ago by [" + master.getName() + "]") ); joinReasonService.onNodeRemoved(discoveryNode, "test removal"); currentTimeMillis.addAndGet(4321L); assertThat( joinReasonService.getJoinReason(discoveryNode, LEADER), matchesNeedingGuidance("joining, removed [5.5s/5555ms] ago with reason [test removal]") ); joinReasonService.onClusterStateApplied(withNode); joinReasonService.onClusterStateApplied(withoutNode); assertThat( joinReasonService.getJoinReason(discoveryNode, LEADER), matchesNeedingGuidance("joining, removed [0ms] ago by [" + master.getName() + "], [2] total removals") ); joinReasonService.onNodeRemoved(discoveryNode, "second test removal"); assertThat( joinReasonService.getJoinReason(discoveryNode, LEADER), matchesNeedingGuidance("joining, removed [0ms] ago with reason [second test removal], [2] total removals") ); final DiscoveryNode rebootedNode = DiscoveryNodeUtils.builder(discoveryNode.getId()) .name(discoveryNode.getName()) .ephemeralId(UUIDs.randomBase64UUID(random())) .address(discoveryNode.getHostName(), discoveryNode.getHostAddress(), discoveryNode.getAddress()) .attributes(discoveryNode.getAttributes()) .roles(discoveryNode.getRoles()) .version(discoveryNode.getVersionInformation()) .build(); assertThat( joinReasonService.getJoinReason(rebootedNode, LEADER), matches("joining after restart, removed [0ms] ago with reason [second test removal]") ); final DiscoveryNodes withRebootedNode = DiscoveryNodes.builder(withoutNode).add(rebootedNode).build(); joinReasonService.onClusterStateApplied(withRebootedNode); joinReasonService.onClusterStateApplied(withoutNode); joinReasonService.onNodeRemoved(rebootedNode, "third test removal"); assertThat( joinReasonService.getJoinReason(rebootedNode, LEADER), matchesNeedingGuidance("joining, removed [0ms] ago with reason [third test removal]") ); joinReasonService.onClusterStateApplied(withRebootedNode); joinReasonService.onClusterStateApplied(withoutNode); joinReasonService.onNodeRemoved(rebootedNode, "fourth test removal"); assertThat( joinReasonService.getJoinReason(rebootedNode, LEADER), matchesNeedingGuidance("joining, removed [0ms] ago with reason [fourth test removal], [2] total removals") ); joinReasonService.onClusterStateApplied(withRebootedNode); joinReasonService.onClusterStateApplied(withNode); joinReasonService.onClusterStateApplied(withoutNode); assertThat( joinReasonService.getJoinReason(discoveryNode, LEADER), matchesNeedingGuidance("joining, removed [0ms] ago by [" + master.getName() + "]") ); assertThat( joinReasonService.getJoinReason(rebootedNode, LEADER), matches("joining after restart, removed [0ms] ago by [" + master.getName() + "]") ); } public void testCleanup() { final AtomicLong currentTimeMillis = new AtomicLong(randomLong()); final JoinReasonService joinReasonService = new JoinReasonService(currentTimeMillis::get); final DiscoveryNode masterNode = randomDiscoveryNode(); final DiscoveryNode targetNode = randomDiscoveryNode(); final DiscoveryNode[] discoveryNodes = new DiscoveryNode[between(2, 20)]; for (int i = 0; i < discoveryNodes.length; i++) { discoveryNodes[i] = randomDiscoveryNode(); } // we stop tracking the oldest absent node(s) when only 1/3 of the tracked nodes are present final int cleanupNodeCount = (discoveryNodes.length - 2) / 3; final DiscoveryNodes.Builder cleanupNodesBuilder = new DiscoveryNodes.Builder().add(masterNode) .localNodeId(masterNode.getId()) .masterNodeId(masterNode.getId()); for (int i = 0; i < cleanupNodeCount; i++) { cleanupNodesBuilder.add(discoveryNodes[i]); } final DiscoveryNodes cleanupNodes = cleanupNodesBuilder.build(); final DiscoveryNodes almostCleanupNodes = DiscoveryNodes.builder(cleanupNodes).add(discoveryNodes[cleanupNodeCount]).build(); final DiscoveryNodes.Builder allOtherNodesBuilder = DiscoveryNodes.builder(almostCleanupNodes); for (int i = cleanupNodeCount + 1; i < discoveryNodes.length; i++) { allOtherNodesBuilder.add(discoveryNodes[i]); } final DiscoveryNodes allOtherNodes = allOtherNodesBuilder.build(); final DiscoveryNodes allNodes = DiscoveryNodes.builder(allOtherNodes).add(targetNode).build(); // track all the nodes joinReasonService.onClusterStateApplied(allNodes); // remove the target node joinReasonService.onClusterStateApplied(allOtherNodes); joinReasonService.onNodeRemoved(targetNode, "test"); // advance time so that the target node is the oldest currentTimeMillis.incrementAndGet(); // remove almost enough other nodes and verify that we're still tracking the target node joinReasonService.onClusterStateApplied(almostCleanupNodes); assertThat( joinReasonService.getJoinReason(targetNode, LEADER), matchesNeedingGuidance("joining, removed [1ms] ago with reason [test]") ); // remove one more node to trigger the cleanup and forget about the target node joinReasonService.onClusterStateApplied(cleanupNodes); assertThat(joinReasonService.getJoinReason(targetNode, LEADER), matches("joining")); } private DiscoveryNode randomDiscoveryNode() { return DiscoveryNodeUtils.builder(UUIDs.randomBase64UUID(random())) .name(randomAlphaOfLength(10)) .ephemeralId(UUIDs.randomBase64UUID(random())) .build(); } private static Matcher<JoinReason> matches(String message) { return equalTo(new JoinReason(message, null)); } private static Matcher<JoinReason> matchesNeedingGuidance(String message) { return equalTo(new JoinReason(message, ReferenceDocs.UNSTABLE_CLUSTER_TROUBLESHOOTING)); } }
JoinReasonServiceTests
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/antlr/PainlessParser.java
{ "start": 177578, "end": 179335 }
class ____ extends ParserRuleContext { public TerminalNode ID() { return getToken(PainlessParser.ID, 0); } public DecltypeContext decltype() { return getRuleContext(DecltypeContext.class, 0); } public LamtypeContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_lamtype; } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if (visitor instanceof PainlessParserVisitor) return ((PainlessParserVisitor<? extends T>) visitor).visitLamtype(this); else return visitor.visitChildren(this); } } public final LamtypeContext lamtype() throws RecognitionException { LamtypeContext _localctx = new LamtypeContext(_ctx, getState()); enterRule(_localctx, 74, RULE_lamtype); try { enterOuterAlt(_localctx, 1); { setState(554); _errHandler.sync(this); switch (getInterpreter().adaptivePredict(_input, 58, _ctx)) { case 1: { setState(553); decltype(); } break; } setState(556); match(ID); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } @SuppressWarnings("CheckReturnValue") public static
LamtypeContext
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Ferry.java
{ "start": 228, "end": 380 }
class ____ extends Boat { private String sea; public String getSea() { return sea; } public void setSea(String string) { sea = string; } }
Ferry
java
playframework__playframework
core/play/src/main/java/play/core/cookie/encoding/HttpConstants.java
{ "start": 677, "end": 1013 }
class ____ { /** Horizontal space */ public static final byte SP = 32; /** Equals '=' */ public static final byte EQUALS = 61; /** Semicolon ';' */ public static final byte SEMICOLON = 59; /** Double quote '"' */ public static final byte DOUBLE_QUOTE = '"'; private HttpConstants() { // Unused } }
HttpConstants
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/rest/FromRestGetCorsCustomTest.java
{ "start": 1256, "end": 3363 }
class ____ extends ContextTestSupport { @Override protected Registry createCamelRegistry() throws Exception { Registry jndi = super.createCamelRegistry(); jndi.bind("dummy-rest", new DummyRestConsumerFactory()); return jndi; } @Test public void testCors() throws Exception { // the rest becomes routes and the input is a seda endpoint created by // the DummyRestConsumerFactory getMockEndpoint("mock:update").expectedMessageCount(1); Exchange out = template.request("seda:post-say-bye", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setBody("I was here"); } }); assertNotNull(out); assertEquals("myserver", out.getMessage().getHeader("Access-Control-Allow-Origin")); assertEquals(RestConfiguration.CORS_ACCESS_CONTROL_ALLOW_METHODS, out.getMessage().getHeader("Access-Control-Allow-Methods")); assertEquals(RestConfiguration.CORS_ACCESS_CONTROL_ALLOW_HEADERS, out.getMessage().getHeader("Access-Control-Allow-Headers")); assertEquals("180", out.getMessage().getHeader("Access-Control-Max-Age")); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { restConfiguration().host("localhost"); restConfiguration().enableCORS(true).corsHeaderProperty("Access-Control-Allow-Origin", "myserver"); restConfiguration().enableCORS(true).corsHeaderProperty("Access-Control-Max-Age", "180"); rest("/say/hello").get().to("direct:hello"); rest("/say/bye").get().consumes("application/json").to("direct:bye").post().to("mock:update"); from("direct:hello").transform().constant("Hello World"); from("direct:bye").transform().constant("Bye World"); } }; } }
FromRestGetCorsCustomTest
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/huggingface/rerank/HuggingFaceRerankModelTests.java
{ "start": 651, "end": 1542 }
class ____ extends ESTestCase { public void testThrowsURISyntaxException_ForInvalidUrl() { var thrownException = expectThrows(IllegalArgumentException.class, () -> createModel("^^", "secret", "model", 8, false)); assertThat(thrownException.getMessage(), containsString("unable to parse url [^^]")); } public static HuggingFaceRerankModel createModel( String url, String apiKey, String modelId, @Nullable Integer topN, @Nullable Boolean returnDocuments ) { return new HuggingFaceRerankModel( modelId, TaskType.RERANK, "service", new HuggingFaceRerankServiceSettings(url), new HuggingFaceRerankTaskSettings(topN, returnDocuments), new DefaultSecretSettings(new SecureString(apiKey.toCharArray())) ); } }
HuggingFaceRerankModelTests
java
google__dagger
hilt-compiler/main/java/dagger/hilt/android/processor/internal/androidentrypoint/ApplicationGenerator.java
{ "start": 4367, "end": 10024 }
class ____ not already define a customInject implementation. ImmutableSet<XMethodElement> customInjectMethods = Stream.concat( metadata.element().getDeclaredMethods().stream(), asStream(metadata.baseElement().getAllMethods())) .filter(method -> getSimpleName(method).contentEquals("customInject")) .filter(method -> method.getParameters().isEmpty()) .collect(toImmutableSet()); for (XMethodElement customInjectMethod : customInjectMethods) { ProcessorErrors.checkState( customInjectMethod.isAbstract() && customInjectMethod.isProtected(), customInjectMethod, "%s#%s, must have modifiers `abstract` and `protected` when using @CustomInject.", XElements.toStableString(customInjectMethod.getEnclosingElement()), XElements.toStableString(customInjectMethod)); } } return hasCustomInject; } // private final ApplicationComponentManager<ApplicationComponent> componentManager = // new ApplicationComponentManager(/* creatorType */); private FieldSpec componentManagerField() { ParameterSpec managerParam = metadata.componentManagerParam(); return FieldSpec.builder(managerParam.type, managerParam.name) .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .initializer("new $T($L)", AndroidClassNames.APPLICATION_COMPONENT_MANAGER, creatorType()) .build(); } // protected ApplicationComponentManager<ApplicationComponent> componentManager() { // return componentManager(); // } private MethodSpec componentManagerMethod() { return MethodSpec.methodBuilder("componentManager") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .returns(metadata.componentManagerParam().type) .addStatement("return $N", metadata.componentManagerParam()) .build(); } // new Supplier<ApplicationComponent>() { // @Override // public ApplicationComponent get() { // return DaggerApplicationComponent.builder() // .applicationContextModule(new ApplicationContextModule(Hilt_$APP.this)) // .build(); // } // } private TypeSpec creatorType() { return TypeSpec.anonymousClassBuilder("") .addSuperinterface(AndroidClassNames.COMPONENT_SUPPLIER) .addMethod( MethodSpec.methodBuilder("get") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(TypeName.OBJECT) .addCode(componentBuilder()) .build()) .build(); } // return DaggerApplicationComponent.builder() // .applicationContextModule(new ApplicationContextModule(Hilt_$APP.this)) // .build(); private CodeBlock componentBuilder() { ClassName component = componentNames.generatedComponent( metadata.elementClassName(), AndroidClassNames.SINGLETON_COMPONENT); return CodeBlock.builder() .addStatement( "return $T.builder()$Z" + ".applicationContextModule(new $T($T.this))$Z" + ".build()", Processors.prepend(Processors.getEnclosedClassName(component), "Dagger"), AndroidClassNames.APPLICATION_CONTEXT_MODULE, wrapperClassName) .build(); } // @CallSuper // @Override // public void onCreate() { // hiltInternalInject(); // super.onCreate(); // } private MethodSpec onCreateMethod() { return MethodSpec.methodBuilder("onCreate") .addAnnotation(AndroidClassNames.CALL_SUPER) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addStatement("hiltInternalInject()") .addStatement("super.onCreate()") .build(); } // public void hiltInternalInject() { // if (!injected) { // injected = true; // // This is a known unsafe cast but should be fine if the only use is // // $APP extends Hilt_$APP // generatedComponent().inject(($APP) this); // } // } private MethodSpec injectionMethod() { return MethodSpec.methodBuilder("hiltInternalInject") .addModifiers(Modifier.PROTECTED) .beginControlFlow("if (!injected)") .addStatement("injected = true") .addCode(injectCodeBlock()) .endControlFlow() .build(); } // private boolean injected = false; private static FieldSpec injectedField() { return FieldSpec.builder(TypeName.BOOLEAN, "injected") .addModifiers(Modifier.PRIVATE) .initializer("false") .build(); } // @Override // public final void customInject() { // hiltInternalInject(); // } private MethodSpec customInjectMethod() { return MethodSpec.methodBuilder("customInject") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addStatement("hiltInternalInject()") .build(); } // // This is a known unsafe cast but is safe in the only correct use case: // // $APP extends Hilt_$APP // generatedComponent().inject$APP(($APP) this); private CodeBlock injectCodeBlock() { return CodeBlock.builder() .add("// This is a known unsafe cast, but is safe in the only correct use case:\n") .add("// $T extends $T\n", metadata.elementClassName(), metadata.generatedClassName()) .addStatement( "(($T) generatedComponent()).$L($L)", metadata.injectorClassName(), metadata.injectMethodName(), Generators.unsafeCastThisTo(metadata.elementClassName())) .build(); } }
does
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableAddConstraint.java
{ "start": 770, "end": 2101 }
class ____ extends SQLObjectImpl implements SQLAlterTableItem { private SQLConstraint constraint; private boolean withNoCheck; private boolean noInherit; private boolean notValid; public SQLAlterTableAddConstraint() { } public SQLAlterTableAddConstraint(SQLConstraint constraint) { this.setConstraint(constraint); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, constraint); } visitor.endVisit(this); } public SQLConstraint getConstraint() { return constraint; } public void setConstraint(SQLConstraint constraint) { if (constraint != null) { constraint.setParent(this); } this.constraint = constraint; } public boolean isWithNoCheck() { return withNoCheck; } public void setWithNoCheck(boolean withNoCheck) { this.withNoCheck = withNoCheck; } public boolean isNoInherit() { return noInherit; } public void setNoInherit(boolean noInherit) { this.noInherit = noInherit; } public boolean isNotValid() { return notValid; } public void setNotValid(boolean notValid) { this.notValid = notValid; } }
SQLAlterTableAddConstraint
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/activities/DiagnosticsCollector.java
{ "start": 1147, "end": 1620 }
interface ____ { void collect(String diagnostics, String details); String getDiagnostics(); String getDetails(); void collectResourceDiagnostics(ResourceCalculator rc, Resource required, Resource available); void collectPlacementConstraintDiagnostics(PlacementConstraint pc, PlacementConstraint.TargetExpression.TargetType targetType); void collectPartitionDiagnostics( String requiredPartition, String nodePartition); }
DiagnosticsCollector
java
google__guice
core/src/com/google/inject/spi/InjectionPoint.java
{ "start": 21382, "end": 22133 }
class ____ { InjectableMember head; InjectableMember tail; void add(InjectableMember member) { if (head == null) { head = tail = member; } else { member.previous = tail; tail.next = member; tail = member; } } void remove(InjectableMember member) { if (member.previous != null) { member.previous.next = member.next; } if (member.next != null) { member.next.previous = member.previous; } if (head == member) { head = member.next; } if (tail == member) { tail = member.previous; } } boolean isEmpty() { return head == null; } } /** Position in type hierarchy. */
InjectableMembers
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/StopWatch.java
{ "start": 6596, "end": 6688 }
class ____ hold data about one task executed within the stop watch. */ public static
to
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/ClassesBaseTest.java
{ "start": 1492, "end": 1744 }
class ____ { public void publicMethod() {} protected void protectedMethod() {} @SuppressWarnings("unused") private void privateMethod() {} } @BeforeEach public void setUp() { classes = new Classes(); } public
MethodsClass
java
spring-projects__spring-boot
core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/DockerCliCommand.java
{ "start": 3663, "end": 3927 }
class ____ extends DockerCliCommand<List<DockerCliContextResponse>> { Context() { super(Type.DOCKER, DockerCliContextResponse.class, true, "context", "ls", "--format={{ json . }}"); } } /** * The {@code docker inspect} command. */ static final
Context
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RLiveObjectService.java
{ "start": 10657, "end": 10762 }
class ____ registered in the cache. * * All classed registered with the service is stored in a
is
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSParametersProvider.java
{ "start": 8186, "end": 8519 }
class ____ extends BooleanParam { /** * Parameter name. */ public static final String NAME = "noredirect"; /** * Constructor. */ public NoRedirectParam() { super(NAME, false); } } /** * Class for operation parameter. */ @InterfaceAudience.Private public static
NoRedirectParam