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/agroal/runtime/src/main/java/io/quarkus/agroal/runtime/DataSources.java | {
"start": 2416,
"end": 2696
} | class ____ not be used from applications or other extensions.
* For applications, use CDI to retrieve datasources instead.
* For extensions, use {@link AgroalDataSourceUtil} instead.
*/
@Deprecated(since = "3.16", forRemoval = true)
@Singleton
public | should |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/security/oauthbearer/JwtBearerJwtRetriever.java | {
"start": 5872,
"end": 8509
} | class ____ implements JwtRetriever {
private final Time time;
private HttpJwtRetriever delegate;
private AssertionJwtTemplate assertionJwtTemplate;
private AssertionCreator assertionCreator;
public JwtBearerJwtRetriever() {
this(Time.SYSTEM);
}
public JwtBearerJwtRetriever(Time time) {
this.time = time;
}
@Override
public void configure(Map<String, ?> configs, String saslMechanism, List<AppConfigurationEntry> jaasConfigEntries) {
ConfigurationUtils cu = new ConfigurationUtils(configs, saslMechanism);
String scope = cu.validateString(SASL_OAUTHBEARER_SCOPE, false);
if (cu.validateString(SASL_OAUTHBEARER_ASSERTION_FILE, false) != null) {
File assertionFile = cu.validateFile(SASL_OAUTHBEARER_ASSERTION_FILE);
assertionCreator = new FileAssertionCreator(assertionFile);
assertionJwtTemplate = new StaticAssertionJwtTemplate();
} else {
String algorithm = cu.validateString(SASL_OAUTHBEARER_ASSERTION_ALGORITHM);
File privateKeyFile = cu.validateFile(SASL_OAUTHBEARER_ASSERTION_PRIVATE_KEY_FILE);
Optional<String> passphrase = cu.containsKey(SASL_OAUTHBEARER_ASSERTION_PRIVATE_KEY_PASSPHRASE) ?
Optional.of(cu.validatePassword(SASL_OAUTHBEARER_ASSERTION_PRIVATE_KEY_PASSPHRASE)) :
Optional.empty();
assertionCreator = new DefaultAssertionCreator(algorithm, privateKeyFile, passphrase);
assertionJwtTemplate = layeredAssertionJwtTemplate(cu, time);
}
Supplier<String> assertionSupplier = () -> {
try {
return assertionCreator.create(assertionJwtTemplate);
} catch (Exception e) {
throw new JwtRetrieverException(e);
}
};
HttpRequestFormatter requestFormatter = new JwtBearerRequestFormatter(scope, assertionSupplier);
delegate = new HttpJwtRetriever(requestFormatter);
delegate.configure(configs, saslMechanism, jaasConfigEntries);
}
@Override
public String retrieve() throws JwtRetrieverException {
if (delegate == null)
throw new IllegalStateException("JWT retriever delegate is null; please call configure() first");
return delegate.retrieve();
}
@Override
public void close() throws IOException {
Utils.closeQuietly(assertionCreator, "JWT assertion creator");
Utils.closeQuietly(assertionJwtTemplate, "JWT assertion template");
Utils.closeQuietly(delegate, "JWT retriever delegate");
}
}
| JwtBearerJwtRetriever |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/operations/converters/SqlCreateOrAlterMaterializedTableConverter.java | {
"start": 2714,
"end": 13645
} | class ____
extends AbstractCreateMaterializedTableConverter<SqlCreateOrAlterMaterializedTable> {
@Override
public Operation convertSqlNode(
SqlCreateOrAlterMaterializedTable sqlCreateOrAlterMaterializedTable,
ConvertContext context) {
final ObjectIdentifier identifier =
this.getIdentifier(sqlCreateOrAlterMaterializedTable, context);
if (createOrAlterOperation(sqlCreateOrAlterMaterializedTable)) {
return handleCreateOrAlter(sqlCreateOrAlterMaterializedTable, context, identifier);
}
return handleCreate(sqlCreateOrAlterMaterializedTable, context, identifier);
}
private Operation handleCreateOrAlter(
final SqlCreateOrAlterMaterializedTable sqlCreateOrAlterMaterializedTable,
final ConvertContext context,
final ObjectIdentifier identifier) {
final Optional<ResolvedCatalogBaseTable<?>> resolvedBaseTable =
context.getCatalogManager().getCatalogBaseTable(identifier);
return resolvedBaseTable
.map(
oldBaseTable -> {
if (oldBaseTable.getTableKind() != TableKind.MATERIALIZED_TABLE) {
throw new ValidationException(
String.format(
"Table %s is not a materialized table. Only materialized table support create or alter operation.",
identifier.asSummaryString()));
}
return handleAlter(
sqlCreateOrAlterMaterializedTable,
(ResolvedCatalogMaterializedTable) oldBaseTable,
context,
identifier);
})
.orElseGet(
() -> handleCreate(sqlCreateOrAlterMaterializedTable, context, identifier));
}
private static boolean createOrAlterOperation(
final SqlCreateOrAlterMaterializedTable sqlCreateOrAlterMaterializedTable) {
return sqlCreateOrAlterMaterializedTable.getOperator()
== SqlCreateOrAlterMaterializedTable.CREATE_OR_ALTER_OPERATOR;
}
private Operation handleAlter(
final SqlCreateOrAlterMaterializedTable sqlCreateOrAlterMaterializedTable,
final ResolvedCatalogMaterializedTable oldMaterializedTable,
final ConvertContext context,
final ObjectIdentifier identifier) {
final CatalogMaterializedTable newTable =
buildNewCatalogMaterializedTableFromOldTable(
oldMaterializedTable, sqlCreateOrAlterMaterializedTable, context);
List<MaterializedTableChange> tableChanges =
buildTableChanges(sqlCreateOrAlterMaterializedTable, oldMaterializedTable, context);
return new AlterMaterializedTableAsQueryOperation(identifier, tableChanges, newTable);
}
private Operation handleCreate(
final SqlCreateOrAlterMaterializedTable sqlCreateOrAlterMaterializedTable,
final ConvertContext context,
final ObjectIdentifier identifier) {
final ResolvedCatalogMaterializedTable resolvedCatalogMaterializedTable =
this.getResolvedCatalogMaterializedTable(
sqlCreateOrAlterMaterializedTable, context);
return new CreateMaterializedTableOperation(identifier, resolvedCatalogMaterializedTable);
}
private List<MaterializedTableChange> buildTableChanges(
final SqlCreateOrAlterMaterializedTable sqlCreateOrAlterMaterializedTable,
final ResolvedCatalogMaterializedTable oldTable,
final ConvertContext context) {
List<MaterializedTableChange> changes = new ArrayList<>();
final MergeContext mergeContext =
this.getMergeContext(sqlCreateOrAlterMaterializedTable, context);
final ResolvedSchema oldSchema = oldTable.getResolvedSchema();
final List<Column> newColumns =
MaterializedTableUtils.validateAndExtractNewColumns(
oldSchema, mergeContext.getMergedQuerySchema());
newColumns.forEach(column -> changes.add(TableChange.add(column)));
changes.add(TableChange.modifyDefinitionQuery(mergeContext.getMergedExpandedQuery()));
return changes;
}
private CatalogMaterializedTable buildNewCatalogMaterializedTableFromOldTable(
final ResolvedCatalogMaterializedTable oldMaterializedTable,
final SqlCreateOrAlterMaterializedTable sqlCreateOrAlterMaterializedTable,
final ConvertContext context) {
final Schema.Builder schemaBuilder =
Schema.newBuilder().fromResolvedSchema(oldMaterializedTable.getResolvedSchema());
// Add new columns if this is an alter operation
final ResolvedSchema oldSchema = oldMaterializedTable.getResolvedSchema();
final MergeContext mergeContext =
this.getMergeContext(sqlCreateOrAlterMaterializedTable, context);
final List<Column> newColumns =
MaterializedTableUtils.validateAndExtractNewColumns(
oldSchema, mergeContext.getMergedQuerySchema());
newColumns.forEach(col -> schemaBuilder.column(col.getName(), col.getDataType()));
final String comment = sqlCreateOrAlterMaterializedTable.getComment();
final IntervalFreshness freshness =
this.getDerivedFreshness(sqlCreateOrAlterMaterializedTable);
final LogicalRefreshMode logicalRefreshMode =
this.getDerivedLogicalRefreshMode(sqlCreateOrAlterMaterializedTable);
final RefreshMode refreshMode = this.getDerivedRefreshMode(logicalRefreshMode);
CatalogMaterializedTable.Builder builder =
CatalogMaterializedTable.newBuilder()
.schema(schemaBuilder.build())
.comment(comment)
.distribution(mergeContext.getMergedTableDistribution().orElse(null))
.partitionKeys(mergeContext.getMergedPartitionKeys())
.options(mergeContext.getMergedTableOptions())
.originalQuery(mergeContext.getMergedOriginalQuery())
.expandedQuery(mergeContext.getMergedExpandedQuery())
.freshness(freshness)
.logicalRefreshMode(logicalRefreshMode)
.refreshMode(refreshMode)
.refreshStatus(RefreshStatus.INITIALIZING);
// Preserve refresh handler from old materialized table
oldMaterializedTable
.getRefreshHandlerDescription()
.ifPresent(builder::refreshHandlerDescription);
builder.serializedRefreshHandler(oldMaterializedTable.getSerializedRefreshHandler());
return builder.build();
}
@Override
protected MergeContext getMergeContext(
final SqlCreateOrAlterMaterializedTable sqlCreateMaterializedTable,
final ConvertContext context) {
return new MergeContext() {
private final MergeTableAsUtil mergeTableAsUtil = new MergeTableAsUtil(context);
// Cache original query. If we call getDerivedExpandedQuery() first, without storing the
// original query, it the SqlNode will be changed and the getAsQuery() will always
// return the expanded query.
private final String originalQuery =
SqlCreateOrAlterMaterializedTableConverter.this.getDerivedOriginalQuery(
sqlCreateMaterializedTable, context);
private final ResolvedSchema querySchema =
SqlCreateOrAlterMaterializedTableConverter.this.getQueryResolvedSchema(
sqlCreateMaterializedTable, context);
@Override
public Schema getMergedSchema() {
final Set<String> querySchemaColumnNames =
new HashSet<>(querySchema.getColumnNames());
final SqlNodeList sqlNodeList = sqlCreateMaterializedTable.getColumnList();
for (SqlNode column : sqlNodeList) {
if (!(column instanceof SqlRegularColumn)) {
continue;
}
SqlRegularColumn physicalColumn = (SqlRegularColumn) column;
if (!querySchemaColumnNames.contains(physicalColumn.getName().getSimple())) {
throw new ValidationException(
String.format(
"Invalid as physical column '%s' is defined in the DDL, but is not used in a query column.",
physicalColumn.getName().getSimple()));
}
}
if (sqlCreateMaterializedTable.isSchemaWithColumnsIdentifiersOnly()) {
// If only column identifiers are provided, then these are used to
// order the columns in the schema.
return mergeTableAsUtil.reorderSchema(sqlNodeList, querySchema);
} else {
return mergeTableAsUtil.mergeSchemas(
sqlNodeList,
sqlCreateMaterializedTable.getWatermark().orElse(null),
sqlCreateMaterializedTable.getFullConstraints(),
querySchema);
}
}
@Override
public Map<String, String> getMergedTableOptions() {
return sqlCreateMaterializedTable.getProperties();
}
@Override
public List<String> getMergedPartitionKeys() {
return sqlCreateMaterializedTable.getPartitionKeyList();
}
@Override
public Optional<TableDistribution> getMergedTableDistribution() {
return SqlCreateOrAlterMaterializedTableConverter.this.getDerivedTableDistribution(
sqlCreateMaterializedTable);
}
@Override
public String getMergedOriginalQuery() {
return this.originalQuery;
}
@Override
public String getMergedExpandedQuery() {
return SqlCreateOrAlterMaterializedTableConverter.this.getDerivedExpandedQuery(
sqlCreateMaterializedTable, context);
}
@Override
public ResolvedSchema getMergedQuerySchema() {
return this.querySchema;
}
};
}
}
| SqlCreateOrAlterMaterializedTableConverter |
java | apache__camel | components/camel-validator/src/generated/java/org/apache/camel/component/validator/ValidatorComponentConfigurer.java | {
"start": 736,
"end": 2841
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
ValidatorComponent target = (ValidatorComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "resourceresolverfactory":
case "resourceResolverFactory": target.setResourceResolverFactory(property(camelContext, org.apache.camel.component.validator.ValidatorResourceResolverFactory.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "resourceresolverfactory":
case "resourceResolverFactory": return org.apache.camel.component.validator.ValidatorResourceResolverFactory.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
ValidatorComponent target = (ValidatorComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "resourceresolverfactory":
case "resourceResolverFactory": return target.getResourceResolverFactory();
default: return null;
}
}
}
| ValidatorComponentConfigurer |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/metrics/stats/HistogramTest.java | {
"start": 1216,
"end": 9047
} | class ____ {
private static final double EPS = 0.0000001d;
@Test
public void testHistogram() {
BinScheme scheme = new ConstantBinScheme(10, -5, 5);
Histogram hist = new Histogram(scheme);
for (int i = -5; i < 5; i++)
hist.record(i);
for (int i = 0; i < 10; i++)
assertEquals(scheme.fromBin(i), hist.value(i / 10.0 + EPS), EPS);
}
@Test
public void testConstantBinScheme() {
ConstantBinScheme scheme = new ConstantBinScheme(5, -5, 5);
assertEquals(0, scheme.toBin(-5.01), "A value below the lower bound should map to the first bin");
assertEquals(4, scheme.toBin(5.01), "A value above the upper bound should map to the last bin");
assertEquals(0, scheme.toBin(-5.0001), "Check boundary of bucket 0");
assertEquals(0, scheme.toBin(-5.0000), "Check boundary of bucket 0");
assertEquals(0, scheme.toBin(-4.99999), "Check boundary of bucket 0");
assertEquals(0, scheme.toBin(-3.00001), "Check boundary of bucket 0");
assertEquals(1, scheme.toBin(-3), "Check boundary of bucket 1");
assertEquals(1, scheme.toBin(-1.00001), "Check boundary of bucket 1");
assertEquals(2, scheme.toBin(-1), "Check boundary of bucket 2");
assertEquals(2, scheme.toBin(0.99999), "Check boundary of bucket 2");
assertEquals(3, scheme.toBin(1), "Check boundary of bucket 3");
assertEquals(3, scheme.toBin(2.99999), "Check boundary of bucket 3");
assertEquals(4, scheme.toBin(3), "Check boundary of bucket 4");
assertEquals(4, scheme.toBin(4.9999), "Check boundary of bucket 4");
assertEquals(4, scheme.toBin(5.000), "Check boundary of bucket 4");
assertEquals(4, scheme.toBin(5.001), "Check boundary of bucket 4");
assertEquals(Float.NEGATIVE_INFINITY, scheme.fromBin(-1), 0.001d);
assertEquals(Float.POSITIVE_INFINITY, scheme.fromBin(5), 0.001d);
assertEquals(-5.0, scheme.fromBin(0), 0.001d);
assertEquals(-3.0, scheme.fromBin(1), 0.001d);
assertEquals(-1.0, scheme.fromBin(2), 0.001d);
assertEquals(1.0, scheme.fromBin(3), 0.001d);
assertEquals(3.0, scheme.fromBin(4), 0.001d);
checkBinningConsistency(scheme);
}
@Test
public void testConstantBinSchemeWithPositiveRange() {
ConstantBinScheme scheme = new ConstantBinScheme(5, 0, 5);
assertEquals(0, scheme.toBin(-1.0), "A value below the lower bound should map to the first bin");
assertEquals(4, scheme.toBin(5.01), "A value above the upper bound should map to the last bin");
assertEquals(0, scheme.toBin(-0.0001), "Check boundary of bucket 0");
assertEquals(0, scheme.toBin(0.0000), "Check boundary of bucket 0");
assertEquals(0, scheme.toBin(0.0001), "Check boundary of bucket 0");
assertEquals(0, scheme.toBin(0.9999), "Check boundary of bucket 0");
assertEquals(1, scheme.toBin(1.0000), "Check boundary of bucket 1");
assertEquals(1, scheme.toBin(1.0001), "Check boundary of bucket 1");
assertEquals(1, scheme.toBin(1.9999), "Check boundary of bucket 1");
assertEquals(2, scheme.toBin(2.0000), "Check boundary of bucket 2");
assertEquals(2, scheme.toBin(2.0001), "Check boundary of bucket 2");
assertEquals(2, scheme.toBin(2.9999), "Check boundary of bucket 2");
assertEquals(3, scheme.toBin(3.0000), "Check boundary of bucket 3");
assertEquals(3, scheme.toBin(3.0001), "Check boundary of bucket 3");
assertEquals(3, scheme.toBin(3.9999), "Check boundary of bucket 3");
assertEquals(4, scheme.toBin(4.0000), "Check boundary of bucket 4");
assertEquals(4, scheme.toBin(4.9999), "Check boundary of bucket 4");
assertEquals(4, scheme.toBin(5.0000), "Check boundary of bucket 4");
assertEquals(4, scheme.toBin(5.0001), "Check boundary of bucket 4");
assertEquals(Float.NEGATIVE_INFINITY, scheme.fromBin(-1), 0.001d);
assertEquals(Float.POSITIVE_INFINITY, scheme.fromBin(5), 0.001d);
assertEquals(0.0, scheme.fromBin(0), 0.001d);
assertEquals(1.0, scheme.fromBin(1), 0.001d);
assertEquals(2.0, scheme.fromBin(2), 0.001d);
assertEquals(3.0, scheme.fromBin(3), 0.001d);
assertEquals(4.0, scheme.fromBin(4), 0.001d);
checkBinningConsistency(scheme);
}
@Test
public void testLinearBinScheme() {
LinearBinScheme scheme = new LinearBinScheme(10, 10);
assertEquals(Float.NEGATIVE_INFINITY, scheme.fromBin(-1), 0.001d);
assertEquals(Float.POSITIVE_INFINITY, scheme.fromBin(11), 0.001d);
assertEquals(0.0, scheme.fromBin(0), 0.001d);
assertEquals(0.2222, scheme.fromBin(1), 0.001d);
assertEquals(0.6666, scheme.fromBin(2), 0.001d);
assertEquals(1.3333, scheme.fromBin(3), 0.001d);
assertEquals(2.2222, scheme.fromBin(4), 0.001d);
assertEquals(3.3333, scheme.fromBin(5), 0.001d);
assertEquals(4.6667, scheme.fromBin(6), 0.001d);
assertEquals(6.2222, scheme.fromBin(7), 0.001d);
assertEquals(8.0000, scheme.fromBin(8), 0.001d);
assertEquals(10.000, scheme.fromBin(9), 0.001d);
assertEquals(0, scheme.toBin(0.0000));
assertEquals(0, scheme.toBin(0.2221));
assertEquals(1, scheme.toBin(0.2223));
assertEquals(2, scheme.toBin(0.6667));
assertEquals(3, scheme.toBin(1.3334));
assertEquals(4, scheme.toBin(2.2223));
assertEquals(5, scheme.toBin(3.3334));
assertEquals(6, scheme.toBin(4.6667));
assertEquals(7, scheme.toBin(6.2223));
assertEquals(8, scheme.toBin(8.0000));
assertEquals(9, scheme.toBin(10.000));
assertEquals(9, scheme.toBin(10.001));
assertEquals(Float.POSITIVE_INFINITY, scheme.fromBin(10), 0.001d);
checkBinningConsistency(scheme);
}
private void checkBinningConsistency(BinScheme scheme) {
for (int bin = 0; bin < scheme.bins(); bin++) {
double fromBin = scheme.fromBin(bin);
int binAgain = scheme.toBin(fromBin + EPS);
assertEquals(bin, binAgain, "unbinning and rebinning the bin " + bin
+ " gave a different result ("
+ fromBin
+ " was placed in bin "
+ binAgain
+ " )");
}
}
public static void main(String[] args) {
Random random = new Random();
System.out.println("[-100, 100]:");
for (BinScheme scheme : Arrays.asList(new ConstantBinScheme(1000, -100, 100),
new ConstantBinScheme(100, -100, 100),
new ConstantBinScheme(10, -100, 100))) {
Histogram h = new Histogram(scheme);
for (int i = 0; i < 10000; i++)
h.record(200.0 * random.nextDouble() - 100.0);
for (double quantile = 0.0; quantile < 1.0; quantile += 0.05)
System.out.printf("%5.2f: %.1f, ", quantile, h.value(quantile));
System.out.println();
}
System.out.println("[0, 1000]");
for (BinScheme scheme : Arrays.asList(new LinearBinScheme(1000, 1000),
new LinearBinScheme(100, 1000),
new LinearBinScheme(10, 1000))) {
Histogram h = new Histogram(scheme);
for (int i = 0; i < 10000; i++)
h.record(1000.0 * random.nextDouble());
for (double quantile = 0.0; quantile < 1.0; quantile += 0.05)
System.out.printf("%5.2f: %.1f, ", quantile, h.value(quantile));
System.out.println();
}
}
}
| HistogramTest |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/support/AbstractContextConfigurationUtilsTests.java | {
"start": 6251,
"end": 6628
} | interface ____ {
@AliasFor(annotation = ContextConfiguration.class)
String[] locations() default "/foo.xml";
@AliasFor(annotation = ActiveProfiles.class)
String[] profiles() default "foo";
}
@ContextConfiguration("/bar.xml")
@ActiveProfiles(profiles = "bar")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @ | MetaLocationsFooConfigWithOverrides |
java | quarkusio__quarkus | extensions/hibernate-search-standalone-elasticsearch/runtime-dev/src/main/java/io/quarkus/hibernate/search/standalone/elasticsearch/runtime/dev/HibernateSearchStandaloneDevJsonRpcService.java | {
"start": 215,
"end": 1083
} | class ____ {
public HibernateSearchStandaloneDevInfo getInfo() {
return HibernateSearchStandaloneDevController.get().getInfo();
}
public int getNumberOfIndexedEntityTypes() {
return getInfo().getNumberOfIndexedEntities();
}
public Multi<String> reindex(List<String> entityTypeNames) {
SearchMapping mapping = HibernateSearchStandaloneDevController.get().searchMapping();
return Multi.createBy().concatenating().streams(
Multi.createFrom().item("started"),
Multi.createFrom()
.completionStage(() -> mapping.scope(Object.class, entityTypeNames).massIndexer().start()
.thenApply(ignored -> "success"))
.onFailure().recoverWithItem(Throwable::getMessage));
}
}
| HibernateSearchStandaloneDevJsonRpcService |
java | apache__commons-lang | src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java | {
"start": 1252,
"end": 21759
} | class ____ extends AbstractLangTest {
private static final int months = 7; // second final prime before 12
private static final int days = 23; // second final prime before 31 (and valid)
private static final int hours = 19; // second final prime before 24
private static final int minutes = 53; // second final prime before 60
private static final int seconds = 47; // third final prime before 60
private static final int millis = 991; // second final prime before 1000
private Date aDate;
private Calendar aCalendar;
@BeforeEach
public void setUp() {
aCalendar = Calendar.getInstance();
aCalendar.set(2005, months, days, hours, minutes, seconds);
aCalendar.set(Calendar.MILLISECOND, millis);
aDate = aCalendar.getTime();
}
@Test
void testDateFragmentInLargerUnitWithCalendar() {
assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.DATE));
}
@Test
void testDateFragmentInLargerUnitWithDate() {
assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.DATE));
}
@Test
void testDayOfYearFragmentInLargerUnitWithCalendar() {
assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.DAY_OF_YEAR));
}
@Test
void testDayOfYearFragmentInLargerUnitWithDate() {
assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.DAY_OF_YEAR));
}
@Test
void testDaysOfMonthWithCalendar() {
final long testResult = DateUtils.getFragmentInDays(aCalendar, Calendar.MONTH);
assertEquals(days, testResult);
}
@Test
void testDaysOfMonthWithDate() {
final long testResult = DateUtils.getFragmentInDays(aDate, Calendar.MONTH);
final Calendar cal = Calendar.getInstance();
cal.setTime(aDate);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), testResult);
}
@Test
void testDaysOfYearWithCalendar() {
final long testResult = DateUtils.getFragmentInDays(aCalendar, Calendar.YEAR);
assertEquals(aCalendar.get(Calendar.DAY_OF_YEAR), testResult);
}
@Test
void testDaysOfYearWithDate() {
final long testResult = DateUtils.getFragmentInDays(aDate, Calendar.YEAR);
final Calendar cal = Calendar.getInstance();
cal.setTime(aDate);
assertEquals(cal.get(Calendar.DAY_OF_YEAR), testResult);
}
@Test
void testHourOfDayFragmentInLargerUnitWithCalendar() {
assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.HOUR_OF_DAY));
assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.HOUR_OF_DAY));
}
@Test
void testHourOfDayFragmentInLargerUnitWithDate() {
assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.HOUR_OF_DAY));
assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.HOUR_OF_DAY));
}
@Test
void testHoursOfDayWithCalendar() {
long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.DATE);
final long expectedValue = hours;
assertEquals(expectedValue, testResult);
testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.DAY_OF_YEAR);
assertEquals(expectedValue, testResult);
}
@Test
void testHoursOfDayWithDate() {
long testResult = DateUtils.getFragmentInHours(aDate, Calendar.DATE);
final long expectedValue = hours;
assertEquals(expectedValue, testResult);
testResult = DateUtils.getFragmentInHours(aDate, Calendar.DAY_OF_YEAR);
assertEquals(expectedValue, testResult);
}
@Test
void testHoursOfMonthWithCalendar() {
final long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.MONTH);
assertEquals(hours + (days - 1) * DateUtils.MILLIS_PER_DAY / DateUtils.MILLIS_PER_HOUR, testResult);
}
@Test
void testHoursOfMonthWithDate() {
final long testResult = DateUtils.getFragmentInHours(aDate, Calendar.MONTH);
assertEquals(hours + (days - 1) * DateUtils.MILLIS_PER_DAY / DateUtils.MILLIS_PER_HOUR, testResult);
}
@Test
void testHoursOfYearWithCalendar() {
final long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.YEAR);
assertEquals(hours + (aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY / DateUtils.MILLIS_PER_HOUR, testResult);
}
@Test
void testHoursOfYearWithDate() {
final long testResult = DateUtils.getFragmentInHours(aDate, Calendar.YEAR);
final Calendar cal = Calendar.getInstance();
cal.setTime(aDate);
assertEquals(hours + (cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY / DateUtils.MILLIS_PER_HOUR, testResult);
}
// Calendar.SECOND as useful fragment
@Test
void testInvalidFragmentWithCalendar() {
assertIllegalArgumentException(() -> DateUtils.getFragmentInMilliseconds(aCalendar, 0));
assertIllegalArgumentException(() -> DateUtils.getFragmentInSeconds(aCalendar, 0));
assertIllegalArgumentException(() -> DateUtils.getFragmentInMinutes(aCalendar, 0));
assertIllegalArgumentException(() -> DateUtils.getFragmentInHours(aCalendar, 0));
assertIllegalArgumentException(() -> DateUtils.getFragmentInDays(aCalendar, 0));
}
@Test
void testInvalidFragmentWithDate() {
assertIllegalArgumentException(() -> DateUtils.getFragmentInMilliseconds(aDate, 0));
assertIllegalArgumentException(() -> DateUtils.getFragmentInSeconds(aDate, 0));
assertIllegalArgumentException(() -> DateUtils.getFragmentInMinutes(aDate, 0));
assertIllegalArgumentException(() -> DateUtils.getFragmentInHours(aDate, 0));
assertIllegalArgumentException(() -> DateUtils.getFragmentInDays(aDate, 0));
}
// Calendar.MINUTE as useful fragment
@Test
void testMillisecondFragmentInLargerUnitWithCalendar() {
assertEquals(0, DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MILLISECOND));
assertEquals(0, DateUtils.getFragmentInSeconds(aCalendar, Calendar.MILLISECOND));
assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.MILLISECOND));
assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.MILLISECOND));
assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.MILLISECOND));
}
@Test
void testMillisecondFragmentInLargerUnitWithDate() {
assertEquals(0, DateUtils.getFragmentInMilliseconds(aDate, Calendar.MILLISECOND));
assertEquals(0, DateUtils.getFragmentInSeconds(aDate, Calendar.MILLISECOND));
assertEquals(0, DateUtils.getFragmentInMinutes(aDate, Calendar.MILLISECOND));
assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.MILLISECOND));
assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.MILLISECOND));
}
@Test
void testMillisecondsOfDayWithCalendar() {
long testresult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.DATE);
final long expectedValue = millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR;
assertEquals(expectedValue, testresult);
testresult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.DAY_OF_YEAR);
assertEquals(expectedValue, testresult);
}
// Calendar.DATE and Calendar.DAY_OF_YEAR as useful fragment
@Test
void testMillisecondsOfDayWithDate() {
long testresult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.DATE);
final long expectedValue = millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR;
assertEquals(expectedValue, testresult);
testresult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.DAY_OF_YEAR);
assertEquals(expectedValue, testresult);
}
// Calendar.HOUR_OF_DAY as useful fragment
@Test
void testMillisecondsOfHourWithCalendar() {
final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.HOUR_OF_DAY);
assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE, testResult);
}
@Test
void testMillisecondsOfHourWithDate() {
final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.HOUR_OF_DAY);
assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE, testResult);
}
@Test
void testMillisecondsOfMinuteWithCalender() {
final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MINUTE);
assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND, testResult);
}
@Test
void testMillisecondsOfMinuteWithDate() {
final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MINUTE);
assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND, testResult);
}
@Test
void testMillisecondsOfMonthWithCalendar() {
final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MONTH);
assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR
+ (days - 1) * DateUtils.MILLIS_PER_DAY, testResult);
}
// Calendar.MONTH as useful fragment
@Test
void testMillisecondsOfMonthWithDate() {
final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MONTH);
assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR
+ (days - 1) * DateUtils.MILLIS_PER_DAY, testResult);
}
@Test
void testMillisecondsOfSecondWithCalendar() {
final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.SECOND);
assertEquals(millis, testResult);
assertEquals(aCalendar.get(Calendar.MILLISECOND), testResult);
}
@Test
void testMillisecondsOfSecondWithDate() {
final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.SECOND);
assertEquals(millis, testResult);
}
@Test
void testMillisecondsOfYearWithCalendar() {
final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.YEAR);
assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR
+ (aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY, testResult);
}
// Calendar.YEAR as useful fragment
@Test
void testMillisecondsOfYearWithDate() {
final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.YEAR);
final Calendar cal = Calendar.getInstance();
cal.setTime(aDate);
assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR
+ (cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY, testResult);
}
@Test
void testMinuteFragmentInLargerUnitWithCalendar() {
assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.MINUTE));
assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.MINUTE));
assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.MINUTE));
}
@Test
void testMinuteFragmentInLargerUnitWithDate() {
assertEquals(0, DateUtils.getFragmentInMinutes(aDate, Calendar.MINUTE));
assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.MINUTE));
assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.MINUTE));
}
@Test
void testMinutesOfDayWithCalendar() {
long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DATE);
final long expectedValue = minutes + hours * DateUtils.MILLIS_PER_HOUR / DateUtils.MILLIS_PER_MINUTE;
assertEquals(expectedValue, testResult);
testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DAY_OF_YEAR);
assertEquals(expectedValue, testResult);
}
@Test
void testMinutesOfDayWithDate() {
long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DATE);
final long expectedValue = minutes + hours * DateUtils.MILLIS_PER_HOUR / DateUtils.MILLIS_PER_MINUTE;
assertEquals(expectedValue, testResult);
testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DAY_OF_YEAR);
assertEquals(expectedValue, testResult);
}
@Test
void testMinutesOfHourWithCalendar() {
final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.HOUR_OF_DAY);
assertEquals(minutes, testResult);
}
@Test
void testMinutesOfHourWithDate() {
final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.HOUR_OF_DAY);
assertEquals(minutes, testResult);
}
@Test
void testMinutesOfMonthWithCalendar() {
final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.MONTH);
assertEquals(minutes + (hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY) / DateUtils.MILLIS_PER_MINUTE, testResult);
}
@Test
void testMinutesOfMonthWithDate() {
final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.MONTH);
assertEquals(minutes + (hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY) / DateUtils.MILLIS_PER_MINUTE, testResult);
}
@Test
void testMinutesOfYearWithCalendar() {
final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.YEAR);
assertEquals(minutes
+ (hours * DateUtils.MILLIS_PER_HOUR + (aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY) / DateUtils.MILLIS_PER_MINUTE,
testResult);
}
@Test
void testMinutesOfYearWithDate() {
final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.YEAR);
final Calendar cal = Calendar.getInstance();
cal.setTime(aDate);
assertEquals(
minutes + (hours * DateUtils.MILLIS_PER_HOUR + (cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY) / DateUtils.MILLIS_PER_MINUTE,
testResult);
}
@Test
void testMinutesOfYearWithWrongOffsetBugWithCalendar() {
final Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DAY_OF_YEAR, 1);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
final long testResult = DateUtils.getFragmentInMinutes(c, Calendar.YEAR);
assertEquals(0, testResult);
}
@Test
void testNullCalendar() {
assertNullPointerException(() -> DateUtils.getFragmentInMilliseconds((Calendar) null, Calendar.MILLISECOND));
assertNullPointerException(() -> DateUtils.getFragmentInSeconds((Calendar) null, Calendar.MILLISECOND));
assertNullPointerException(() -> DateUtils.getFragmentInMinutes((Calendar) null, Calendar.MILLISECOND));
assertNullPointerException(() -> DateUtils.getFragmentInHours((Calendar) null, Calendar.MILLISECOND));
assertNullPointerException(() -> DateUtils.getFragmentInDays((Calendar) null, Calendar.MILLISECOND));
}
@Test
void testNullDate() {
assertNullPointerException(() -> DateUtils.getFragmentInMilliseconds((Date) null, Calendar.MILLISECOND));
assertNullPointerException(() -> DateUtils.getFragmentInSeconds((Date) null, Calendar.MILLISECOND));
assertNullPointerException(() -> DateUtils.getFragmentInMinutes((Date) null, Calendar.MILLISECOND));
assertNullPointerException(() -> DateUtils.getFragmentInHours((Date) null, Calendar.MILLISECOND));
assertNullPointerException(() -> DateUtils.getFragmentInDays((Date) null, Calendar.MILLISECOND));
}
@Test
void testSecondFragmentInLargerUnitWithCalendar() {
assertEquals(0, DateUtils.getFragmentInSeconds(aCalendar, Calendar.SECOND));
assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.SECOND));
assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.SECOND));
assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.SECOND));
}
@Test
void testSecondFragmentInLargerUnitWithDate() {
assertEquals(0, DateUtils.getFragmentInSeconds(aDate, Calendar.SECOND));
assertEquals(0, DateUtils.getFragmentInMinutes(aDate, Calendar.SECOND));
assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.SECOND));
assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.SECOND));
}
@Test
void testSecondsOfDayWithCalendar() {
long testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DATE);
final long expectedValue = seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR) / DateUtils.MILLIS_PER_SECOND;
assertEquals(expectedValue, testresult);
testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DAY_OF_YEAR);
assertEquals(expectedValue, testresult);
}
@Test
void testSecondsOfDayWithDate() {
long testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DATE);
final long expectedValue = seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR) / DateUtils.MILLIS_PER_SECOND;
assertEquals(expectedValue, testresult);
testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DAY_OF_YEAR);
assertEquals(expectedValue, testresult);
}
@Test
void testSecondsofHourWithCalendar() {
final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.HOUR_OF_DAY);
assertEquals(seconds + minutes * DateUtils.MILLIS_PER_MINUTE / DateUtils.MILLIS_PER_SECOND, testResult);
}
@Test
void testSecondsofHourWithDate() {
final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.HOUR_OF_DAY);
assertEquals(seconds + minutes * DateUtils.MILLIS_PER_MINUTE / DateUtils.MILLIS_PER_SECOND, testResult);
}
@Test
void testSecondsofMinuteWithCalendar() {
final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MINUTE);
assertEquals(seconds, testResult);
assertEquals(aCalendar.get(Calendar.SECOND), testResult);
}
@Test
void testSecondsofMinuteWithDate() {
final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MINUTE);
assertEquals(seconds, testResult);
}
@Test
void testSecondsOfMonthWithCalendar() {
final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MONTH);
assertEquals(seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY)
/ DateUtils.MILLIS_PER_SECOND, testResult);
}
@Test
void testSecondsOfMonthWithDate() {
final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MONTH);
assertEquals(seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY)
/ DateUtils.MILLIS_PER_SECOND, testResult);
}
@Test
void testSecondsOfYearWithCalendar() {
final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.YEAR);
assertEquals(seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR
+ (aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY) / DateUtils.MILLIS_PER_SECOND, testResult);
}
@Test
void testSecondsOfYearWithDate() {
final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.YEAR);
final Calendar cal = Calendar.getInstance();
cal.setTime(aDate);
assertEquals(seconds
+ (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR + (cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY)
/ DateUtils.MILLIS_PER_SECOND,
testResult);
}
}
| DateUtilsFragmentTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/Rounding.java | {
"start": 24216,
"end": 26878
} | class ____ extends PreparedRounding {
@Override
public double roundingSize(long utcMillis, DateTimeUnit timeUnit) {
if (unit.isMillisBased) {
if (timeUnit.isMillisBased) {
return (double) unit.ratio / timeUnit.ratio;
} else {
throw new IllegalArgumentException(
"Cannot use month-based rate unit ["
+ timeUnit.shortName
+ "] with non-month based calendar interval histogram ["
+ unit.shortName
+ "] only week, day, hour, minute and second are supported for this histogram"
);
}
} else {
if (timeUnit.isMillisBased) {
return (double) (nextRoundingValue(utcMillis) - utcMillis) / timeUnit.ratio;
} else {
return (double) unit.ratio / timeUnit.ratio;
}
}
}
@Override
public double roundingSize(DateTimeUnit timeUnit) {
if (unit.isMillisBased) {
if (timeUnit.isMillisBased) {
return (double) unit.ratio / timeUnit.ratio;
} else {
throw new IllegalArgumentException(
"Cannot use month-based rate unit ["
+ timeUnit.shortName
+ "] with non-month based calendar interval histogram ["
+ unit.shortName
+ "] only week, day, hour, minute and second are supported for this histogram"
);
}
} else {
if (timeUnit.isMillisBased) {
throw new IllegalArgumentException(
"Cannot use non month-based rate unit ["
+ timeUnit.shortName
+ "] with calendar interval histogram ["
+ unit.shortName
+ "] only month, quarter and year are supported for this histogram"
);
} else {
return (double) unit.ratio / timeUnit.ratio;
}
}
}
@Override
public abstract String toString();
}
private | TimeUnitPreparedRounding |
java | apache__camel | components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/ChainedCxfConfigurer.java | {
"start": 1007,
"end": 2146
} | class ____ implements CxfConfigurer {
private CxfConfigurer parent;
private CxfConfigurer child;
private ChainedCxfConfigurer() {
}
public static ChainedCxfConfigurer create(CxfConfigurer parent, CxfConfigurer child) {
ChainedCxfConfigurer result = new ChainedCxfConfigurer();
result.parent = parent;
result.child = child;
return result;
}
public ChainedCxfConfigurer addChild(CxfConfigurer cxfConfigurer) {
ChainedCxfConfigurer result = new ChainedCxfConfigurer();
result.parent = this;
result.child = cxfConfigurer;
return result;
}
@Override
public void configure(AbstractWSDLBasedEndpointFactory factoryBean) {
parent.configure(factoryBean);
child.configure(factoryBean);
}
@Override
public void configureClient(Client client) {
parent.configureClient(client);
child.configureClient(client);
}
@Override
public void configureServer(Server server) {
parent.configureServer(server);
child.configureServer(server);
}
public static | ChainedCxfConfigurer |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathProcessor.java | {
"start": 1043,
"end": 1166
} | class ____ extends FunctionalEnumBinaryProcessor<Number, Number, Number, BinaryMathOperation> {
public | BinaryMathProcessor |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/mapper/FieldArrayContext.java | {
"start": 5685,
"end": 6194
} | class ____ {
int currentOffset;
// Need to use TreeMap here, so that we maintain the order in which each value (with offset) stored inserted,
// (which is in the same order the document gets parsed) so we store offsets in right order. This is the same
// order in what the values get stored in SortedSetDocValues.
final Map<Comparable<?>, List<Integer>> valueToOffsets = new TreeMap<>();
final List<Integer> nullValueOffsets = new ArrayList<>(2);
}
}
| Offsets |
java | spring-projects__spring-boot | module/spring-boot-hibernate/src/test/java/org/springframework/boot/hibernate/autoconfigure/HibernateJpaAutoConfigurationTests.java | {
"start": 7198,
"end": 43397
} | class ____ {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withPropertyValues("spring.datasource.generate-unique-name=true",
"spring.jta.log-dir=" + new File(new BuildOutput(getClass()).getRootLocation(), "transaction-logs"))
.withUserConfiguration(TestConfiguration.class)
.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class,
TransactionManagerCustomizationAutoConfiguration.class, DataSourceInitializationAutoConfiguration.class,
HibernateJpaAutoConfiguration.class));
@Test
void notConfiguredIfDataSourceIsNotAvailable() {
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(HibernateJpaAutoConfiguration.class))
.run(assertJpaIsNotAutoConfigured());
}
@Test
void notConfiguredIfNoSingleDataSourceCandidateIsAvailable() {
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(HibernateJpaAutoConfiguration.class))
.withUserConfiguration(TestTwoDataSourcesConfiguration.class)
.run(assertJpaIsNotAutoConfigured());
}
protected ContextConsumer<AssertableApplicationContext> assertJpaIsNotAutoConfigured() {
return (context) -> {
assertThat(context).hasNotFailed();
assertThat(context).hasSingleBean(JpaProperties.class);
assertThat(context).doesNotHaveBean(TransactionManager.class);
assertThat(context).doesNotHaveBean(EntityManagerFactory.class);
};
}
@Test
void configuredWithAutoConfiguredDataSource() {
this.contextRunner.run((context) -> {
assertThat(context).hasSingleBean(DataSource.class);
assertThat(context).hasSingleBean(JpaTransactionManager.class);
assertThat(context).hasSingleBean(EntityManagerFactory.class);
assertThat(context).hasSingleBean(PersistenceManagedTypes.class);
});
}
@Test
void configuredWithSingleCandidateDataSource() {
this.contextRunner.withUserConfiguration(TestTwoDataSourcesAndPrimaryConfiguration.class).run((context) -> {
assertThat(context).getBeans(DataSource.class).hasSize(2);
assertThat(context).hasSingleBean(JpaTransactionManager.class);
assertThat(context).hasSingleBean(EntityManagerFactory.class);
assertThat(context).hasSingleBean(PersistenceManagedTypes.class);
});
}
@Test
void jpaTransactionManagerTakesPrecedenceOverSimpleDataSourceOne() {
this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class))
.run((context) -> {
assertThat(context).hasSingleBean(DataSource.class);
assertThat(context).hasSingleBean(JpaTransactionManager.class);
assertThat(context).getBean("transactionManager").isInstanceOf(JpaTransactionManager.class);
});
}
@Test
void openEntityManagerInViewInterceptorIsCreated() {
new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true")
.withUserConfiguration(TestConfiguration.class)
.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class,
TransactionAutoConfiguration.class, HibernateJpaAutoConfiguration.class))
.run((context) -> assertThat(context).hasSingleBean(OpenEntityManagerInViewInterceptor.class));
}
@Test
void openEntityManagerInViewInterceptorIsNotRegisteredWhenFilterPresent() {
new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true")
.withUserConfiguration(TestFilterConfiguration.class)
.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class,
TransactionAutoConfiguration.class, HibernateJpaAutoConfiguration.class))
.run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class));
}
@Test
void openEntityManagerInViewInterceptorIsNotRegisteredWhenFilterRegistrationPresent() {
new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true")
.withUserConfiguration(TestFilterRegistrationConfiguration.class)
.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class,
TransactionAutoConfiguration.class, HibernateJpaAutoConfiguration.class))
.run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class));
}
@Test
void openEntityManagerInViewInterceptorAutoConfigurationBacksOffWhenManuallyRegistered() {
new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true")
.withUserConfiguration(TestInterceptorManualConfiguration.class)
.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class,
TransactionAutoConfiguration.class, HibernateJpaAutoConfiguration.class))
.run((context) -> assertThat(context).getBean(OpenEntityManagerInViewInterceptor.class)
.isExactlyInstanceOf(
TestInterceptorManualConfiguration.ManualOpenEntityManagerInViewInterceptor.class));
}
@Test
void openEntityManagerInViewInterceptorIsNotRegisteredWhenExplicitlyOff() {
new WebApplicationContextRunner()
.withPropertyValues("spring.datasource.generate-unique-name=true", "spring.jpa.open-in-view=false")
.withUserConfiguration(TestConfiguration.class)
.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class,
TransactionAutoConfiguration.class, HibernateJpaAutoConfiguration.class))
.run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class));
}
@Test
void customJpaProperties() {
this.contextRunner
.withPropertyValues("spring.jpa.properties.a:b", "spring.jpa.properties.a.b:c", "spring.jpa.properties.c:d")
.run((context) -> {
LocalContainerEntityManagerFactoryBean bean = context
.getBean(LocalContainerEntityManagerFactoryBean.class);
Map<String, Object> map = bean.getJpaPropertyMap();
assertThat(map).containsEntry("a", "b");
assertThat(map).containsEntry("c", "d");
assertThat(map).containsEntry("a.b", "c");
});
}
@Test
@WithMetaInfPersistenceXmlResource
void usesManuallyDefinedLocalContainerEntityManagerFactoryBeanUsingBuilder() {
this.contextRunner.withPropertyValues("spring.jpa.properties.a=b")
.withUserConfiguration(TestConfigurationWithEntityManagerFactoryBuilder.class)
.run((context) -> {
LocalContainerEntityManagerFactoryBean factoryBean = context
.getBean(LocalContainerEntityManagerFactoryBean.class);
Map<String, Object> map = factoryBean.getJpaPropertyMap();
assertThat(map).containsEntry("configured", "manually").containsEntry("a", "b");
});
}
@Test
@WithMetaInfPersistenceXmlResource
void usesManuallyDefinedLocalContainerEntityManagerFactoryBeanIfAvailable() {
this.contextRunner.withUserConfiguration(TestConfigurationWithLocalContainerEntityManagerFactoryBean.class)
.run((context) -> {
LocalContainerEntityManagerFactoryBean factoryBean = context
.getBean(LocalContainerEntityManagerFactoryBean.class);
Map<String, Object> map = factoryBean.getJpaPropertyMap();
assertThat(map).containsEntry("configured", "manually");
});
}
@Test
@WithMetaInfPersistenceXmlResource
void usesManuallyDefinedEntityManagerFactoryIfAvailable() {
this.contextRunner.withUserConfiguration(TestConfigurationWithLocalContainerEntityManagerFactoryBean.class)
.run((context) -> {
EntityManagerFactory factoryBean = context.getBean(EntityManagerFactory.class);
Map<String, Object> map = factoryBean.getProperties();
assertThat(map).containsEntry("configured", "manually");
});
}
@Test
void usesManuallyDefinedTransactionManagerBeanIfAvailable() {
this.contextRunner.withUserConfiguration(TestConfigurationWithTransactionManager.class).run((context) -> {
assertThat(context).hasSingleBean(JpaTransactionManager.class);
JpaTransactionManager txManager = context.getBean(JpaTransactionManager.class);
assertThat(txManager).isInstanceOf(CustomJpaTransactionManager.class);
});
}
@Test
void defaultPersistenceManagedTypes() {
this.contextRunner.run((context) -> {
assertThat(context).hasSingleBean(PersistenceManagedTypes.class);
EntityManager entityManager = context.getBean(EntityManagerFactory.class).createEntityManager();
assertThat(getManagedJavaTypes(entityManager)).contains(City.class).doesNotContain(Country.class);
});
}
@Test
void customPersistenceManagedTypes() {
this.contextRunner
.withBean(PersistenceManagedTypes.class, () -> PersistenceManagedTypes.of(Country.class.getName()))
.run((context) -> {
assertThat(context).hasSingleBean(PersistenceManagedTypes.class);
EntityManager entityManager = context.getBean(EntityManagerFactory.class).createEntityManager();
assertThat(getManagedJavaTypes(entityManager)).contains(Country.class).doesNotContain(City.class);
});
}
@Test
void customPersistenceUnitManager() {
this.contextRunner.withUserConfiguration(TestConfigurationWithCustomPersistenceUnitManager.class)
.run((context) -> {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = context
.getBean(LocalContainerEntityManagerFactoryBean.class);
assertThat(entityManagerFactoryBean).hasFieldOrPropertyWithValue("persistenceUnitManager",
context.getBean(PersistenceUnitManager.class));
});
}
@Test
void customPersistenceUnitPostProcessors() {
this.contextRunner.withUserConfiguration(TestConfigurationWithCustomPersistenceUnitPostProcessors.class)
.run((context) -> {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = context
.getBean(LocalContainerEntityManagerFactoryBean.class);
PersistenceUnitInfo persistenceUnitInfo = entityManagerFactoryBean.getPersistenceUnitInfo();
assertThat(persistenceUnitInfo).isNotNull();
assertThat(persistenceUnitInfo.getManagedClassNames())
.contains("customized.attribute.converter.class.name");
});
}
@Test
void customManagedClassNameFilter() {
this.contextRunner.withBean(ManagedClassNameFilter.class, () -> (s) -> !s.endsWith("City"))
.withUserConfiguration(AutoConfigurePackageForCountry.class)
.run((context) -> {
EntityManager entityManager = context.getBean(EntityManagerFactory.class).createEntityManager();
assertThat(getManagedJavaTypes(entityManager)).contains(Country.class).doesNotContain(City.class);
});
}
@Test
void testDmlScriptWithMissingDdl() {
this.contextRunner.withPropertyValues("spring.sql.init.data-locations:classpath:/city.sql",
// Missing:
"spring.sql.init.schema-locations:classpath:/ddl.sql")
.run((context) -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure()).hasMessageContaining("ddl.sql");
});
}
@Test
void testDmlScript() {
// This can't succeed because the data SQL is executed immediately after the
// schema and Hibernate hasn't initialized yet at that point
this.contextRunner.withPropertyValues("spring.sql.init.data-locations:/city.sql").run((context) -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class);
});
}
@Test
@WithResource(name = "city.sql",
content = "INSERT INTO CITY (ID, NAME, STATE, COUNTRY, MAP) values (2000, 'Washington', 'DC', 'US', 'Google')")
void testDmlScriptRunsEarly() {
this.contextRunner.withUserConfiguration(TestInitializedJpaConfiguration.class)
.withClassLoader(new HideDataScriptClassLoader())
.withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.properties.hibernate.format_sql=true",
"spring.jpa.properties.hibernate.highlight_sql=true", "spring.jpa.hibernate.ddl-auto:create-drop",
"spring.sql.init.data-locations:/city.sql", "spring.jpa.defer-datasource-initialization=true")
.run((context) -> assertThat(context.getBean(TestInitializedJpaConfiguration.class).called).isTrue());
}
@Test
@WithResource(name = "db/city/V1__init.sql", content = """
CREATE SEQUENCE city_seq INCREMENT BY 50;
CREATE TABLE CITY (
id BIGINT GENERATED BY DEFAULT AS IDENTITY,
name VARCHAR(30),
state VARCHAR(30),
country VARCHAR(30),
map VARCHAR(30)
);
""")
void testFlywaySwitchOffDdlAuto() {
this.contextRunner.withPropertyValues("spring.sql.init.mode:never", "spring.flyway.locations:classpath:db/city")
.withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class))
.run((context) -> assertThat(context).hasNotFailed());
}
@Test
@WithResource(name = "db/city/V1__init.sql", content = """
CREATE SEQUENCE city_seq INCREMENT BY 50;
CREATE TABLE CITY (
id BIGINT GENERATED BY DEFAULT AS IDENTITY,
name VARCHAR(30),
state VARCHAR(30),
country VARCHAR(30),
map VARCHAR(30)
);
""")
void testFlywayPlusValidation() {
this.contextRunner
.withPropertyValues("spring.sql.init.mode:never", "spring.flyway.locations:classpath:db/city",
"spring.jpa.hibernate.ddl-auto:validate")
.withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class))
.run((context) -> assertThat(context).hasNotFailed());
}
@Test
@WithResource(name = "db/changelog/db.changelog-city.yaml", content = """
databaseChangeLog:
- changeSet:
id: 1
author: dsyer
changes:
- createSequence:
sequenceName: city_seq
incrementBy: 50
- createTable:
tableName: city
columns:
- column:
name: id
type: bigint
autoIncrement: true
constraints:
primaryKey: true
nullable: false
- column:
name: name
type: varchar(50)
constraints:
nullable: false
- column:
name: state
type: varchar(50)
constraints:
nullable: false
- column:
name: country
type: varchar(50)
constraints:
nullable: false
- column:
name: map
type: varchar(50)
constraints:
nullable: true
""")
void testLiquibasePlusValidation() {
this.contextRunner
.withPropertyValues("spring.liquibase.change-log:classpath:db/changelog/db.changelog-city.yaml",
"spring.jpa.hibernate.ddl-auto:validate")
.withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class))
.run((context) -> assertThat(context).hasNotFailed());
}
@Test
void hibernateDialectIsNotSetByDefault() {
this.contextRunner.run(assertJpaVendorAdapter(
(adapter) -> assertThat(adapter.getJpaPropertyMap()).doesNotContainKeys("hibernate.dialect")));
}
@Test
void shouldConfigureHibernateJpaDialectWithSqlExceptionTranslatorIfPresent() {
SQLStateSQLExceptionTranslator sqlExceptionTranslator = new SQLStateSQLExceptionTranslator();
this.contextRunner.withBean(SQLStateSQLExceptionTranslator.class, () -> sqlExceptionTranslator)
.run(assertJpaVendorAdapter(
(adapter) -> assertThat(adapter.getJpaDialect()).extracting("exceptionTranslator")
.hasFieldOrPropertyWithValue("jdbcExceptionTranslator", sqlExceptionTranslator)));
}
@Test
void shouldNotConfigureHibernateJpaDialectWithSqlExceptionTranslatorIfNotUnique() {
SQLStateSQLExceptionTranslator sqlExceptionTranslator1 = new SQLStateSQLExceptionTranslator();
SQLStateSQLExceptionTranslator sqlExceptionTranslator2 = new SQLStateSQLExceptionTranslator();
this.contextRunner
.withBean("sqlExceptionTranslator1", SQLExceptionTranslator.class, () -> sqlExceptionTranslator1)
.withBean("sqlExceptionTranslator2", SQLExceptionTranslator.class, () -> sqlExceptionTranslator2)
.run(assertJpaVendorAdapter(
(adapter) -> assertThat(adapter.getJpaDialect()).extracting("exceptionTranslator")
.hasFieldOrPropertyWithValue("jdbcExceptionTranslator", null)));
}
@Test
void hibernateDialectIsSetWhenDatabaseIsSet() {
this.contextRunner.withPropertyValues("spring.jpa.database=H2")
.run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap())
.contains(entry("hibernate.dialect", H2Dialect.class.getName()))));
}
@Test
void hibernateDialectIsSetWhenDatabasePlatformIsSet() {
String databasePlatform = TestH2Dialect.class.getName();
this.contextRunner.withPropertyValues("spring.jpa.database-platform=" + databasePlatform)
.run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap())
.contains(entry("hibernate.dialect", databasePlatform))));
}
private ContextConsumer<AssertableApplicationContext> assertJpaVendorAdapter(
Consumer<HibernateJpaVendorAdapter> adapter) {
return (context) -> {
assertThat(context).hasSingleBean(JpaVendorAdapter.class);
assertThat(context).hasSingleBean(HibernateJpaVendorAdapter.class);
adapter.accept(context.getBean(HibernateJpaVendorAdapter.class));
};
}
@Test
void jtaDefaultPlatform() {
this.contextRunner.withUserConfiguration(JtaTransactionManagerConfiguration.class)
.run(assertJtaPlatform(SpringJtaPlatform.class));
}
@Test
void jtaCustomPlatform() {
this.contextRunner
.withPropertyValues(
"spring.jpa.properties.hibernate.transaction.jta.platform:" + TestJtaPlatform.class.getName())
.withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class))
.run(assertJtaPlatform(TestJtaPlatform.class));
}
@Test
void jtaNotUsedByTheApplication() {
this.contextRunner.run(assertJtaPlatform(NoJtaPlatform.class));
}
private ContextConsumer<AssertableApplicationContext> assertJtaPlatform(Class<? extends JtaPlatform> expectedType) {
return (context) -> {
SessionFactoryImpl sessionFactory = context.getBean(LocalContainerEntityManagerFactoryBean.class)
.getNativeEntityManagerFactory()
.unwrap(SessionFactoryImpl.class);
assertThat(sessionFactory.getServiceRegistry().getService(JtaPlatform.class)).isInstanceOf(expectedType);
};
}
@Test
void jtaCustomTransactionManagerUsingProperties() {
this.contextRunner
.withPropertyValues("spring.transaction.default-timeout:30",
"spring.transaction.rollback-on-commit-failure:true")
.run((context) -> {
JpaTransactionManager transactionManager = context.getBean(JpaTransactionManager.class);
assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30);
assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue();
});
}
@Test
void autoConfigurationBacksOffWithSeveralDataSources() {
this.contextRunner
.withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class,
XADataSourceAutoConfiguration.class, JtaAutoConfiguration.class))
.withUserConfiguration(TestTwoDataSourcesConfiguration.class)
.run((context) -> {
assertThat(context).hasNotFailed();
assertThat(context).doesNotHaveBean(EntityManagerFactory.class);
});
}
@Test
void providerDisablesAutoCommitIsConfigured() {
this.contextRunner
.withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(),
"spring.datasource.hikari.auto-commit:false")
.run((context) -> {
Map<String, Object> jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class)
.getJpaPropertyMap();
assertThat(jpaProperties).contains(entry("hibernate.connection.provider_disables_autocommit", "true"));
});
}
@Test
void providerDisablesAutoCommitIsNotConfiguredIfAutoCommitIsEnabled() {
this.contextRunner
.withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(),
"spring.datasource.hikari.auto-commit:true")
.run((context) -> {
Map<String, Object> jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class)
.getJpaPropertyMap();
assertThat(jpaProperties).doesNotContainKeys("hibernate.connection.provider_disables_autocommit");
});
}
@Test
void providerDisablesAutoCommitIsNotConfiguredIfPropertyIsSet() {
this.contextRunner
.withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(),
"spring.datasource.hikari.auto-commit:false",
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false")
.run((context) -> {
Map<String, Object> jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class)
.getJpaPropertyMap();
assertThat(jpaProperties).contains(entry("hibernate.connection.provider_disables_autocommit", "false"));
});
}
@Test
void providerDisablesAutoCommitIsNotConfiguredWithJta() {
this.contextRunner.withUserConfiguration(JtaTransactionManagerConfiguration.class)
.withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(),
"spring.datasource.hikari.auto-commit:false")
.run((context) -> {
Map<String, Object> jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class)
.getJpaPropertyMap();
assertThat(jpaProperties).doesNotContainKeys("hibernate.connection.provider_disables_autocommit");
});
}
@Test
@WithResource(name = "META-INF/mappings/non-annotated.xml",
content = """
<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm https://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/orm_2_1.xsd"
version="2.1">
<entity class="org.springframework.boot.jpa.autoconfigure.hibernate.mapping.NonAnnotatedEntity">
<table name="NON_ANNOTATED"/>
<attributes>
<id name="id">
<column name="id"/>
<generated-value strategy="IDENTITY"/>
</id>
<basic name="item">
<column name="item"/>
</basic>
</attributes>
</entity>
</entity-mappings>
""")
@WithResource(name = "non-annotated-data.sql",
content = "INSERT INTO NON_ANNOTATED (id, item) values (2000, 'Test');")
void customResourceMapping() {
this.contextRunner.withClassLoader(new HideDataScriptClassLoader())
.withPropertyValues("spring.sql.init.data-locations:classpath:non-annotated-data.sql",
"spring.jpa.mapping-resources=META-INF/mappings/non-annotated.xml",
"spring.jpa.defer-datasource-initialization=true")
.run((context) -> {
EntityManager em = context.getBean(EntityManagerFactory.class).createEntityManager();
NonAnnotatedEntity found = em.find(NonAnnotatedEntity.class, 2000L);
assertThat(found).isNotNull();
assertThat(found.getItem()).isEqualTo("Test");
});
}
@Test
void physicalNamingStrategyCanBeUsed() {
this.contextRunner.withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class).run((context) -> {
Map<String, Object> hibernateProperties = getVendorProperties(context);
assertThat(hibernateProperties)
.contains(entry("hibernate.physical_naming_strategy", context.getBean("testPhysicalNamingStrategy")));
assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy");
});
}
@Test
void implicitNamingStrategyCanBeUsed() {
this.contextRunner.withUserConfiguration(TestImplicitNamingStrategyConfiguration.class).run((context) -> {
Map<String, Object> hibernateProperties = getVendorProperties(context);
assertThat(hibernateProperties)
.contains(entry("hibernate.implicit_naming_strategy", context.getBean("testImplicitNamingStrategy")));
assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy");
});
}
@Test
void namingStrategyInstancesTakePrecedenceOverNamingStrategyProperties() {
this.contextRunner
.withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class,
TestImplicitNamingStrategyConfiguration.class)
.withPropertyValues("spring.jpa.hibernate.naming.physical-strategy:com.example.Physical",
"spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit")
.run((context) -> {
Map<String, Object> hibernateProperties = getVendorProperties(context);
assertThat(hibernateProperties).contains(
entry("hibernate.physical_naming_strategy", context.getBean("testPhysicalNamingStrategy")),
entry("hibernate.implicit_naming_strategy", context.getBean("testImplicitNamingStrategy")));
assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy");
});
}
@Test
void hibernatePropertiesCustomizerTakesPrecedenceOverStrategyInstancesAndNamingStrategyProperties() {
this.contextRunner
.withUserConfiguration(TestHibernatePropertiesCustomizerConfiguration.class,
TestPhysicalNamingStrategyConfiguration.class, TestImplicitNamingStrategyConfiguration.class)
.withPropertyValues("spring.jpa.hibernate.naming.physical-strategy:com.example.Physical",
"spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit")
.run((context) -> {
Map<String, Object> hibernateProperties = getVendorProperties(context);
TestHibernatePropertiesCustomizerConfiguration configuration = context
.getBean(TestHibernatePropertiesCustomizerConfiguration.class);
assertThat(hibernateProperties).contains(
entry("hibernate.physical_naming_strategy", configuration.physicalNamingStrategy),
entry("hibernate.implicit_naming_strategy", configuration.implicitNamingStrategy));
assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy");
});
}
@Test
@WithResource(name = "city.sql",
content = "INSERT INTO CITY (ID, NAME, STATE, COUNTRY, MAP) values (2000, 'Washington', 'DC', 'US', 'Google')")
void eventListenerCanBeRegisteredAsBeans() {
this.contextRunner.withUserConfiguration(TestInitializedJpaConfiguration.class)
.withClassLoader(new HideDataScriptClassLoader())
.withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.hibernate.ddl-auto:create-drop",
"spring.sql.init.data-locations:classpath:/city.sql",
"spring.jpa.defer-datasource-initialization=true")
.run((context) -> {
// See CityListener
assertThat(context).hasSingleBean(City.class);
assertThat(context.getBean(City.class).getName()).isEqualTo("Washington");
});
}
@Test
void hibernatePropertiesCustomizerCanDisableBeanContainer() {
this.contextRunner.withUserConfiguration(DisableBeanContainerConfiguration.class)
.run((context) -> assertThat(context).doesNotHaveBean(City.class));
}
@Test
void vendorPropertiesWithEmbeddedDatabaseAndNoDdlProperty() {
this.contextRunner.run(vendorProperties((vendorProperties) -> {
assertThat(vendorProperties).doesNotContainKeys(SchemaToolingSettings.JAKARTA_HBM2DDL_DATABASE_ACTION);
assertThat(vendorProperties).containsEntry(SchemaToolingSettings.HBM2DDL_AUTO, "create-drop");
}));
}
@Test
void vendorPropertiesWhenDdlAutoPropertyIsSet() {
this.contextRunner.withPropertyValues("spring.jpa.hibernate.ddl-auto=update")
.run(vendorProperties((vendorProperties) -> {
assertThat(vendorProperties).doesNotContainKeys(SchemaToolingSettings.JAKARTA_HBM2DDL_DATABASE_ACTION);
assertThat(vendorProperties).containsEntry(SchemaToolingSettings.HBM2DDL_AUTO, "update");
}));
}
@Test
void vendorPropertiesWhenDdlAutoPropertyAndHibernatePropertiesAreSet() {
this.contextRunner
.withPropertyValues("spring.jpa.hibernate.ddl-auto=update",
"spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop")
.run(vendorProperties((vendorProperties) -> {
assertThat(vendorProperties).doesNotContainKeys(SchemaToolingSettings.JAKARTA_HBM2DDL_DATABASE_ACTION);
assertThat(vendorProperties).containsEntry(SchemaToolingSettings.HBM2DDL_AUTO, "create-drop");
}));
}
@Test
void vendorPropertiesWhenDdlAutoPropertyIsSetToNone() {
this.contextRunner.withPropertyValues("spring.jpa.hibernate.ddl-auto=none")
.run(vendorProperties((vendorProperties) -> assertThat(vendorProperties).doesNotContainKeys(
SchemaToolingSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, SchemaToolingSettings.HBM2DDL_AUTO)));
}
@Test
void vendorPropertiesWhenJpaDdlActionIsSet() {
this.contextRunner
.withPropertyValues("spring.jpa.properties.jakarta.persistence.schema-generation.database.action=create")
.run(vendorProperties((vendorProperties) -> {
assertThat(vendorProperties).containsEntry(SchemaToolingSettings.JAKARTA_HBM2DDL_DATABASE_ACTION,
"create");
assertThat(vendorProperties).doesNotContainKeys(SchemaToolingSettings.HBM2DDL_AUTO);
}));
}
@Test
void vendorPropertiesWhenBothDdlAutoPropertiesAreSet() {
this.contextRunner
.withPropertyValues("spring.jpa.properties.jakarta.persistence.schema-generation.database.action=create",
"spring.jpa.hibernate.ddl-auto=create-only")
.run(vendorProperties((vendorProperties) -> {
assertThat(vendorProperties).containsEntry(SchemaToolingSettings.JAKARTA_HBM2DDL_DATABASE_ACTION,
"create");
assertThat(vendorProperties).containsEntry(SchemaToolingSettings.HBM2DDL_AUTO, "create-only");
}));
}
private ContextConsumer<AssertableApplicationContext> vendorProperties(
Consumer<Map<String, Object>> vendorProperties) {
return (context) -> vendorProperties.accept(getVendorProperties(context));
}
private static Map<String, Object> getVendorProperties(ConfigurableApplicationContext context) {
return context.getBean(HibernateJpaConfiguration.class).getVendorProperties(context.getBean(DataSource.class));
}
@Test
void withSyncBootstrappingAnApplicationListenerThatUsesJpaDoesNotTriggerABeanCurrentlyInCreationException() {
this.contextRunner.withUserConfiguration(JpaUsingApplicationListenerConfiguration.class).run((context) -> {
assertThat(context).hasNotFailed();
EventCapturingApplicationListener listener = context.getBean(EventCapturingApplicationListener.class);
assertThat(listener.events).hasSize(1);
assertThat(listener.events).hasOnlyElementsOfType(ContextRefreshedEvent.class);
});
}
@Test
void withAsyncBootstrappingAnApplicationListenerThatUsesJpaDoesNotTriggerABeanCurrentlyInCreationException() {
this.contextRunner
.withUserConfiguration(AsyncBootstrappingConfiguration.class,
JpaUsingApplicationListenerConfiguration.class)
.run((context) -> {
assertThat(context).hasNotFailed();
EventCapturingApplicationListener listener = context.getBean(EventCapturingApplicationListener.class);
assertThat(listener.events).hasSize(1);
assertThat(listener.events).hasOnlyElementsOfType(ContextRefreshedEvent.class);
// createEntityManager requires Hibernate bootstrapping to be complete
assertThatNoException()
.isThrownBy(() -> context.getBean(EntityManagerFactory.class).createEntityManager());
});
}
@Test
@WithMetaInfPersistenceXmlResource
void whenLocalContainerEntityManagerFactoryBeanHasNoJpaVendorAdapterAutoConfigurationSucceeds() {
this.contextRunner
.withUserConfiguration(
TestConfigurationWithLocalContainerEntityManagerFactoryBeanWithNoJpaVendorAdapter.class)
.run((context) -> {
EntityManagerFactory factoryBean = context.getBean(EntityManagerFactory.class);
Map<String, Object> map = factoryBean.getProperties();
assertThat(map).containsEntry("configured", "manually");
});
}
@Test
void registersHintsForJtaClasses() {
RuntimeHints hints = new RuntimeHints();
new HibernateRuntimeHints().registerHints(hints, getClass().getClassLoader());
for (String noJtaPlatformClass : Arrays.asList(
"org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform",
"org.hibernate.service.jta.platform.internal.NoJtaPlatform")) {
assertThat(RuntimeHintsPredicates.reflection()
.onType(TypeReference.of(noJtaPlatformClass))
.withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(hints);
}
}
@Test
void registersHintsForNamingClasses() {
RuntimeHints hints = new RuntimeHints();
new HibernateRuntimeHints().registerHints(hints, getClass().getClassLoader());
for (Class<?> noJtaPlatformClass : Arrays.asList(SpringImplicitNamingStrategy.class,
PhysicalNamingStrategySnakeCaseImpl.class)) {
assertThat(RuntimeHintsPredicates.reflection()
.onType(noJtaPlatformClass)
.withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(hints);
}
}
@Test
@Disabled("gh-40177")
void whenSpringJpaGenerateDdlIsNotSetThenTableIsNotCreated() {
// spring.jpa.generated-ddl defaults to false but this test still fails because
// we're using an embedded database which means that HibernateProperties defaults
// hibernate.hbm2ddl.auto to create-drop, replacing the
// hibernate.hbm2ddl.auto=none that comes from generate-ddl being false.
this.contextRunner.run((context) -> assertThat(tablesFrom(context)).doesNotContain("CITY"));
}
@Test
void whenSpringJpaGenerateDdlIsTrueThenTableIsCreated() {
this.contextRunner.withPropertyValues("spring.jpa.generate-ddl=true")
.run((context) -> assertThat(tablesFrom(context)).contains("CITY"));
}
@Test
@Disabled("gh-40177")
void whenSpringJpaGenerateDdlIsFalseThenTableIsNotCreated() {
// This test fails because we're using an embedded database which means that
// HibernateProperties defaults hibernate.hbm2ddl.auto to create-drop, replacing
// the hibernate.hbm2ddl.auto=none that comes from setting generate-ddl to false.
this.contextRunner.withPropertyValues("spring.jpa.generate-ddl=false")
.run((context) -> assertThat(tablesFrom(context)).doesNotContain("CITY"));
}
@Test
void whenHbm2DdlAutoIsNoneThenTableIsNotCreated() {
this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.hbm2ddl.auto=none")
.run((context) -> assertThat(tablesFrom(context)).doesNotContain("CITY"));
}
@Test
void whenSpringJpaHibernateDdlAutoIsNoneThenTableIsNotCreated() {
this.contextRunner.withPropertyValues("spring.jpa.hibernate.ddl-auto=none")
.run((context) -> assertThat(tablesFrom(context)).doesNotContain("CITY"));
}
@Test
@Disabled("gh-40177")
void whenSpringJpaGenerateDdlIsTrueAndSpringJpaHibernateDdlAutoIsNoneThenTableIsNotCreated() {
// This test fails because when ddl-auto is set to none, we remove
// hibernate.hbm2ddl.auto from Hibernate properties. This then allows
// spring.jpa.generate-ddl to set it to create-drop
this.contextRunner.withPropertyValues("spring.jpa.generate-ddl=true", "spring.jpa.hibernate.ddl-auto=none")
.run((context) -> assertThat(tablesFrom(context)).doesNotContain("CITY"));
}
@Test
void whenSpringJpaGenerateDdlIsTrueAndSpringJpaHibernateDdlAutoIsDropThenTableIsNotCreated() {
this.contextRunner.withPropertyValues("spring.jpa.generate-ddl=true", "spring.jpa.hibernate.ddl-auto=drop")
.run((context) -> assertThat(tablesFrom(context)).doesNotContain("CITY"));
}
@Test
void whenSpringJpaGenerateDdlIsTrueAndJakartaSchemaGenerationIsNoneThenTableIsNotCreated() {
this.contextRunner
.withPropertyValues("spring.jpa.generate-ddl=true",
"spring.jpa.properties.jakarta.persistence.schema-generation.database.action=none")
.run((context) -> assertThat(tablesFrom(context)).doesNotContain("CITY"));
}
@Test
void whenSpringJpaGenerateDdlIsTrueSpringJpaHibernateDdlAutoIsCreateAndJakartaSchemaGenerationIsNoneThenTableIsNotCreated() {
this.contextRunner
.withPropertyValues("spring.jpa.generate-ddl=true", "spring.jpa.hibernate.ddl-auto=create",
"spring.jpa.properties.jakarta.persistence.schema-generation.database.action=none")
.run((context) -> assertThat(tablesFrom(context)).doesNotContain("CITY"));
}
private List<String> tablesFrom(AssertableApplicationContext context) {
DataSource dataSource = context.getBean(DataSource.class);
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
List<String> tables = jdbc.query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES",
(results, row) -> results.getString(1));
return tables;
}
private Class<?>[] getManagedJavaTypes(EntityManager entityManager) {
Set<ManagedType<?>> managedTypes = entityManager.getMetamodel().getManagedTypes();
return managedTypes.stream().map(ManagedType::getJavaType).toArray(Class<?>[]::new);
}
@Configuration(proxyBeanMethods = false)
protected static | HibernateJpaAutoConfigurationTests |
java | elastic__elasticsearch | x-pack/plugin/rollup/src/main/java/org/elasticsearch/xpack/rollup/job/RollupIndexer.java | {
"start": 3273,
"end": 16440
} | class ____ extends AsyncTwoPhaseIndexer<Map<String, Object>, RollupIndexerJobStats> {
static final String AGGREGATION_NAME = RollupField.NAME;
private final RollupJob job;
private final CompositeAggregationBuilder compositeBuilder;
private long maxBoundary;
/**
* Ctr
* @param threadPool ThreadPool to use to fire the first request of a background job.
* @param job The rollup job
* @param initialState Initial state for the indexer
* @param initialPosition The last indexed bucket of the task
*/
RollupIndexer(ThreadPool threadPool, RollupJob job, AtomicReference<IndexerState> initialState, Map<String, Object> initialPosition) {
this(threadPool, job, initialState, initialPosition, new RollupIndexerJobStats());
}
/**
* Ctr
* @param threadPool ThreadPool to use to fire the first request of a background job.
* @param job The rollup job
* @param initialState Initial state for the indexer
* @param initialPosition The last indexed bucket of the task
* @param jobStats jobstats instance for collecting stats
*/
RollupIndexer(
ThreadPool threadPool,
RollupJob job,
AtomicReference<IndexerState> initialState,
Map<String, Object> initialPosition,
RollupIndexerJobStats jobStats
) {
super(threadPool, initialState, initialPosition, jobStats);
this.job = job;
this.compositeBuilder = createCompositeBuilder(job.getConfig());
}
@Override
protected String getJobId() {
return job.getConfig().getId();
}
@Override
protected void onStart(long now, ActionListener<Boolean> listener) {
try {
// this is needed to exclude buckets that can still receive new documents
DateHistogramGroupConfig dateHisto = job.getConfig().getGroupConfig().getDateHistogram();
// if the job has a delay we filter all documents that appear before it
long delay = dateHisto.getDelay() != null ? TimeValue.parseTimeValue(dateHisto.getDelay().toString(), "").millis() : 0;
maxBoundary = dateHisto.createRounding().round(now - delay);
listener.onResponse(true);
} catch (Exception e) {
listener.onFailure(e);
}
}
protected SearchRequest buildSearchRequest() {
final Map<String, Object> position = getPosition();
SearchSourceBuilder searchSource = new SearchSourceBuilder().size(0)
.trackTotalHits(false)
// make sure we always compute complete buckets that appears before the configured delay
.query(createBoundaryQuery(position))
.aggregation(compositeBuilder.aggregateAfter(position));
return new SearchRequest(job.getConfig().indices()).allowPartialSearchResults(false).source(searchSource);
}
@Override
protected IterationResult<Map<String, Object>> doProcess(SearchResponse searchResponse) {
final CompositeAggregation response = searchResponse.getAggregations().get(AGGREGATION_NAME);
if (response.getBuckets().isEmpty()) {
// do not reset the position as we want to continue from where we stopped
return new IterationResult<>(Stream.empty(), getPosition(), true);
}
return new IterationResult<>(
IndexerUtils.processBuckets(
response,
job.getConfig().getRollupIndex(),
getStats(),
job.getConfig().getGroupConfig(),
job.getConfig().getId()
),
response.afterKey(),
response.getBuckets().isEmpty()
);
}
/**
* Creates a skeleton {@link CompositeAggregationBuilder} from the provided job config.
* @param config The config for the job.
* @return The composite aggregation that creates the rollup buckets
*/
private static CompositeAggregationBuilder createCompositeBuilder(RollupJobConfig config) {
final GroupConfig groupConfig = config.getGroupConfig();
List<CompositeValuesSourceBuilder<?>> builders = createValueSourceBuilders(groupConfig);
CompositeAggregationBuilder composite = new CompositeAggregationBuilder(AGGREGATION_NAME, builders);
List<AggregationBuilder> aggregations = createAggregationBuilders(config.getMetricsConfig());
aggregations.forEach(composite::subAggregation);
final Map<String, Object> metadata = createMetadata(groupConfig);
if (metadata.isEmpty() == false) {
composite.setMetadata(metadata);
}
composite.size(config.getPageSize());
return composite;
}
/**
* Creates the range query that limits the search to documents that appear before the maximum allowed time
* (see {@link #maxBoundary}
* and on or after the last processed time.
* @param position The current position of the pagination
* @return The range query to execute
*/
private QueryBuilder createBoundaryQuery(Map<String, Object> position) {
assert maxBoundary < Long.MAX_VALUE;
DateHistogramGroupConfig dateHisto = job.getConfig().getGroupConfig().getDateHistogram();
String fieldName = dateHisto.getField();
String rollupFieldName = fieldName + "." + DateHistogramAggregationBuilder.NAME;
long lowerBound = 0L;
if (position != null) {
Number value = (Number) position.get(rollupFieldName);
lowerBound = value.longValue();
}
assert lowerBound <= maxBoundary;
final RangeQueryBuilder query = new RangeQueryBuilder(fieldName).gte(lowerBound).lt(maxBoundary).format("epoch_millis");
return query;
}
static Map<String, Object> createMetadata(final GroupConfig groupConfig) {
final Map<String, Object> metadata = new HashMap<>();
if (groupConfig != null) {
// Add all the metadata in order: date_histo -> histo
final DateHistogramGroupConfig dateHistogram = groupConfig.getDateHistogram();
metadata.put(RollupField.formatMetaField(RollupField.INTERVAL), dateHistogram.getInterval().toString());
final HistogramGroupConfig histogram = groupConfig.getHistogram();
if (histogram != null) {
metadata.put(RollupField.formatMetaField(RollupField.INTERVAL), histogram.getInterval());
}
}
return metadata;
}
public static List<CompositeValuesSourceBuilder<?>> createValueSourceBuilders(final GroupConfig groupConfig) {
final List<CompositeValuesSourceBuilder<?>> builders = new ArrayList<>();
// Add all the agg builders to our request in order: date_histo -> histo -> terms
if (groupConfig != null) {
final DateHistogramGroupConfig dateHistogram = groupConfig.getDateHistogram();
builders.addAll(createValueSourceBuilders(dateHistogram));
final HistogramGroupConfig histogram = groupConfig.getHistogram();
builders.addAll(createValueSourceBuilders(histogram));
final TermsGroupConfig terms = groupConfig.getTerms();
builders.addAll(createValueSourceBuilders(terms));
}
return Collections.unmodifiableList(builders);
}
public static List<CompositeValuesSourceBuilder<?>> createValueSourceBuilders(final DateHistogramGroupConfig dateHistogram) {
final String dateHistogramField = dateHistogram.getField();
final String dateHistogramName = RollupField.formatIndexerAggName(dateHistogramField, DateHistogramAggregationBuilder.NAME);
final DateHistogramValuesSourceBuilder dateHistogramBuilder = new DateHistogramValuesSourceBuilder(dateHistogramName);
if (dateHistogram instanceof DateHistogramGroupConfig.FixedInterval) {
dateHistogramBuilder.fixedInterval(dateHistogram.getInterval());
} else if (dateHistogram instanceof DateHistogramGroupConfig.CalendarInterval) {
dateHistogramBuilder.calendarInterval(dateHistogram.getInterval());
} else {
throw new IllegalStateException("[date_histogram] must use either [fixed_interval] or [calendar_interval]");
}
dateHistogramBuilder.field(dateHistogramField);
dateHistogramBuilder.timeZone(ZoneId.of(dateHistogram.getTimeZone()));
return Collections.singletonList(dateHistogramBuilder);
}
public static List<CompositeValuesSourceBuilder<?>> createValueSourceBuilders(final HistogramGroupConfig histogram) {
final List<CompositeValuesSourceBuilder<?>> builders = new ArrayList<>();
if (histogram != null) {
for (String field : histogram.getFields()) {
final String histogramName = RollupField.formatIndexerAggName(field, HistogramAggregationBuilder.NAME);
final HistogramValuesSourceBuilder histogramBuilder = new HistogramValuesSourceBuilder(histogramName);
histogramBuilder.interval(histogram.getInterval());
histogramBuilder.field(field);
histogramBuilder.missingBucket(true);
builders.add(histogramBuilder);
}
}
return Collections.unmodifiableList(builders);
}
public static List<CompositeValuesSourceBuilder<?>> createValueSourceBuilders(final TermsGroupConfig terms) {
final List<CompositeValuesSourceBuilder<?>> builders = new ArrayList<>();
if (terms != null) {
for (String field : terms.getFields()) {
final String termsName = RollupField.formatIndexerAggName(field, TermsAggregationBuilder.NAME);
final TermsValuesSourceBuilder termsBuilder = new TermsValuesSourceBuilder(termsName);
termsBuilder.field(field);
termsBuilder.missingBucket(true);
builders.add(termsBuilder);
}
}
return Collections.unmodifiableList(builders);
}
/**
* This returns a set of aggregation builders which represent the configured
* set of metrics. Used to iterate over historical data.
*/
static List<AggregationBuilder> createAggregationBuilders(final List<MetricConfig> metricsConfigs) {
final List<AggregationBuilder> builders = new ArrayList<>();
if (metricsConfigs != null) {
for (MetricConfig metricConfig : metricsConfigs) {
final List<String> metrics = metricConfig.getMetrics();
if (metrics.isEmpty() == false) {
final String field = metricConfig.getField();
for (String metric : metrics) {
ValuesSourceAggregationBuilder.LeafOnly<? extends AggregationBuilder> newBuilder;
if (metric.equals(MetricConfig.MIN.getPreferredName())) {
newBuilder = new MinAggregationBuilder(formatFieldName(field, MinAggregationBuilder.NAME, RollupField.VALUE));
} else if (metric.equals(MetricConfig.MAX.getPreferredName())) {
newBuilder = new MaxAggregationBuilder(formatFieldName(field, MaxAggregationBuilder.NAME, RollupField.VALUE));
} else if (metric.equals(MetricConfig.AVG.getPreferredName())) {
// Avgs are sum + count
newBuilder = new SumAggregationBuilder(formatFieldName(field, AvgAggregationBuilder.NAME, RollupField.VALUE));
ValuesSourceAggregationBuilder.LeafOnly<ValueCountAggregationBuilder> countBuilder =
new ValueCountAggregationBuilder(
formatFieldName(field, AvgAggregationBuilder.NAME, RollupField.COUNT_FIELD)
);
countBuilder.field(field);
builders.add(countBuilder);
} else if (metric.equals(MetricConfig.SUM.getPreferredName())) {
newBuilder = new SumAggregationBuilder(formatFieldName(field, SumAggregationBuilder.NAME, RollupField.VALUE));
} else if (metric.equals(MetricConfig.VALUE_COUNT.getPreferredName())) {
// TODO allow non-numeric value_counts.
// I removed the hard coding of NUMERIC as part of cleaning up targetValueType, but I don't think that resolves
// the above to do note -- Tozzi 2019-12-06
newBuilder = new ValueCountAggregationBuilder(
formatFieldName(field, ValueCountAggregationBuilder.NAME, RollupField.VALUE)
);
} else {
throw new IllegalArgumentException("Unsupported metric type [" + metric + "]");
}
newBuilder.field(field);
builders.add(newBuilder);
}
}
}
}
return Collections.unmodifiableList(builders);
}
}
| RollupIndexer |
java | apache__flink | flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/sink/writer/AsyncSinkWriterStateSerializerTest.java | {
"start": 1308,
"end": 1895
} | class ____ {
@Test
void testSerializeAndDeSerialize() throws IOException {
AsyncSinkWriterStateSerializerImpl stateSerializer =
new AsyncSinkWriterStateSerializerImpl();
BufferedRequestState<String> state =
getTestState((element, context) -> element, String::length);
BufferedRequestState<String> deserializedState =
stateSerializer.deserialize(0, stateSerializer.serialize(state));
assertThatBufferStatesAreEqual(state, deserializedState);
}
private static | AsyncSinkWriterStateSerializerTest |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/parent_childs/Child.java | {
"start": 709,
"end": 1462
} | class ____ {
private Integer id;
private String name;
private String surName;
private Integer age;
public Child() {
}
public Child(Integer id, String name, String surName, Integer age) {
this.id = id;
this.name = name;
this.surName = surName;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
| Child |
java | spring-projects__spring-boot | smoke-test/spring-boot-smoke-test-websocket-jetty/src/main/java/smoketest/websocket/jetty/client/SimpleGreetingService.java | {
"start": 676,
"end": 807
} | class ____ implements GreetingService {
@Override
public String getGreeting() {
return "Hello world!";
}
}
| SimpleGreetingService |
java | apache__flink | flink-formats/flink-avro-confluent-registry/src/test/java/org/apache/flink/formats/avro/registry/confluent/debezium/DebeziumAvroSerDeSchemaTest.java | {
"start": 9559,
"end": 10029
} | class ____
implements DeserializationSchema.InitializationContext,
SerializationSchema.InitializationContext {
@Override
public MetricGroup getMetricGroup() {
return new UnregisteredMetricsGroup();
}
@Override
public UserCodeClassLoader getUserCodeClassLoader() {
return SimpleUserCodeClassLoader.create(getClass().getClassLoader());
}
}
}
| MockInitializationContext |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotsUtilization.java | {
"start": 997,
"end": 2375
} | class ____ {
private final int total;
private final int reserved;
SlotsUtilization(int total, int reserved) {
Preconditions.checkArgument(
total >= reserved, "The total value must be >= reserved value.");
Preconditions.checkArgument(reserved >= 0, "The reserved number must not be negative.");
this.total = total;
this.reserved = reserved;
}
SlotsUtilization incReserved(int inc) {
Preconditions.checkArgument(inc > 0, "The increment number must be greater than zero.");
Preconditions.checkArgument(
reserved + inc <= total,
"The increment result must be equal to or less than the total value.");
return new SlotsUtilization(total, reserved + inc);
}
double getUtilization() {
if (total == 0 && reserved == 0) {
return 1.0;
}
return ((double) reserved) / total;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SlotsUtilization that = (SlotsUtilization) o;
return total == that.total && reserved == that.reserved;
}
@Override
public int hashCode() {
return Objects.hash(total, reserved);
}
}
| SlotsUtilization |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/errors/IllegalSaslStateException.java | {
"start": 1050,
"end": 1369
} | class ____ extends AuthenticationException {
private static final long serialVersionUID = 1L;
public IllegalSaslStateException(String message) {
super(message);
}
public IllegalSaslStateException(String message, Throwable cause) {
super(message, cause);
}
}
| IllegalSaslStateException |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableSwitchIfEmptyTest.java | {
"start": 991,
"end": 3621
} | class ____ extends RxJavaTest {
@Test
public void switchWhenNotEmpty() throws Exception {
final AtomicBoolean subscribed = new AtomicBoolean(false);
final Observable<Integer> o = Observable.just(4)
.switchIfEmpty(Observable.just(2)
.doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(Disposable d) {
subscribed.set(true);
}
}));
assertEquals(4, o.blockingSingle().intValue());
assertFalse(subscribed.get());
}
@Test
public void switchWhenEmpty() throws Exception {
final Observable<Integer> o = Observable.<Integer>empty()
.switchIfEmpty(Observable.fromIterable(Arrays.asList(42)));
assertEquals(42, o.blockingSingle().intValue());
}
@Test
public void switchTriggerUnsubscribe() throws Exception {
final Disposable d = Disposable.empty();
Observable<Long> withProducer = Observable.unsafeCreate(new ObservableSource<Long>() {
@Override
public void subscribe(final Observer<? super Long> observer) {
observer.onSubscribe(d);
observer.onNext(42L);
}
});
Observable.<Long>empty()
.switchIfEmpty(withProducer)
.lift(new ObservableOperator<Long, Long>() {
@Override
public Observer<? super Long> apply(final Observer<? super Long> child) {
return new DefaultObserver<Long>() {
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Long aLong) {
cancel();
}
};
}
}).subscribe();
assertTrue(d.isDisposed());
// FIXME no longer assertable
// assertTrue(sub.isUnsubscribed());
}
@Test
public void switchShouldTriggerUnsubscribe() {
final Disposable d = Disposable.empty();
Observable.unsafeCreate(new ObservableSource<Long>() {
@Override
public void subscribe(final Observer<? super Long> observer) {
observer.onSubscribe(d);
observer.onComplete();
}
}).switchIfEmpty(Observable.<Long>never()).subscribe();
assertTrue(d.isDisposed());
}
}
| ObservableSwitchIfEmptyTest |
java | quarkusio__quarkus | extensions/liquibase/liquibase/deployment/src/test/java/io/quarkus/liquibase/test/LiquibaseExtensionConfigNamedDataSourceWithoutDefaultTest.java | {
"start": 514,
"end": 1624
} | class ____ {
@Inject
LiquibaseExtensionConfigFixture fixture;
@Inject
@LiquibaseDataSource("users")
LiquibaseFactory liquibaseUsers;
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClass(LiquibaseExtensionConfigFixture.class)
.addAsResource("db/xml/changeLog.xml")
.addAsResource("db/xml/create-tables.xml")
.addAsResource("db/xml/create-views.xml")
.addAsResource("db/xml/test/test.xml")
.addAsResource("config-for-named-datasource-without-default.properties", "application.properties"));
@Test
@DisplayName("Reads liquibase configuration for datasource named 'users' without default datasource correctly")
public void testLiquibaseConfigNamedUsersInjection() {
fixture.assertAllConfigurationSettings(liquibaseUsers.getConfiguration(), "users");
assertFalse(fixture.migrateAtStart(""));
}
}
| LiquibaseExtensionConfigNamedDataSourceWithoutDefaultTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/collectioninitializer/UserAuthorization.java | {
"start": 287,
"end": 909
} | class ____ {
@Id
private Long id;
@ManyToOne(optional = false)
private User user;
@ManyToOne(optional = false)
private CostCenter costCenter;
@Override
public String toString() {
return "UserAuthorization{" +
"id='" + getId() + '\'' +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public CostCenter getCostCenter() {
return costCenter;
}
public void setCostCenter(CostCenter costCenter) {
this.costCenter = costCenter;
}
}
| UserAuthorization |
java | playframework__playframework | core/play/src/main/java/play/libs/Files.java | {
"start": 391,
"end": 510
} | class ____ {
/** This creates temporary files when Play needs to keep overflow data on the filesystem. */
public | Files |
java | junit-team__junit5 | junit-vintage-engine/src/testFixtures/java/org/junit/platform/runner/JUnitPlatform.java | {
"start": 574,
"end": 672
} | class ____ the one from the discontinued
* {@code junit-platform-runner} module.
*/
public | mimicking |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/datastreams/lifecycle/GetDataStreamLifecycleActionTests.java | {
"start": 1357,
"end": 8404
} | class ____ extends ESTestCase {
@SuppressWarnings("unchecked")
public void testDefaultLifecycleResponseToXContent() throws Exception {
boolean isInternalDataStream = randomBoolean();
GetDataStreamLifecycleAction.Response.DataStreamLifecycle dataStreamLifecycle = createDataStreamLifecycle(
DataStreamLifecycle.DEFAULT_DATA_LIFECYCLE,
isInternalDataStream
);
GetDataStreamLifecycleAction.Response response = new GetDataStreamLifecycleAction.Response(List.of(dataStreamLifecycle));
try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) {
builder.humanReadable(true);
response.toXContentChunked(ToXContent.EMPTY_PARAMS).forEachRemaining(xcontent -> {
try {
xcontent.toXContent(builder, EMPTY_PARAMS);
} catch (IOException e) {
logger.error(e.getMessage(), e);
fail(e.getMessage());
}
});
Map<String, Object> resultMap = XContentHelper.convertToMap(BytesReference.bytes(builder), false, builder.contentType()).v2();
assertThat(resultMap.get("global_retention"), equalTo(Map.of()));
assertThat(resultMap.containsKey("data_streams"), equalTo(true));
List<Map<String, Object>> dataStreams = (List<Map<String, Object>>) resultMap.get("data_streams");
Map<String, Object> firstDataStream = dataStreams.get(0);
assertThat(firstDataStream.containsKey("lifecycle"), equalTo(true));
Map<String, Object> lifecycleResult = (Map<String, Object>) firstDataStream.get("lifecycle");
assertThat(lifecycleResult.get("enabled"), equalTo(true));
assertThat(lifecycleResult.get("data_retention"), nullValue());
assertThat(lifecycleResult.get("effective_retention"), nullValue());
assertThat(lifecycleResult.get("retention_determined_by"), nullValue());
}
}
@SuppressWarnings("unchecked")
public void testGlobalRetentionToXContent() {
TimeValue globalDefaultRetention = TimeValue.timeValueDays(10);
TimeValue globalMaxRetention = TimeValue.timeValueDays(50);
DataStreamGlobalRetention globalRetention = new DataStreamGlobalRetention(globalDefaultRetention, globalMaxRetention);
GetDataStreamLifecycleAction.Response response = new GetDataStreamLifecycleAction.Response(List.of(), null, globalRetention);
try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) {
builder.humanReadable(true);
response.toXContentChunked(ToXContent.EMPTY_PARAMS).forEachRemaining(xcontent -> {
try {
xcontent.toXContent(builder, EMPTY_PARAMS);
} catch (IOException e) {
logger.error(e.getMessage(), e);
fail(e.getMessage());
}
});
Map<String, Object> resultMap = XContentHelper.convertToMap(BytesReference.bytes(builder), false, builder.contentType()).v2();
assertThat(resultMap.containsKey("global_retention"), equalTo(true));
Map<String, String> globalRetentionMap = (Map<String, String>) resultMap.get("global_retention");
assertThat(globalRetentionMap.get("max_retention"), equalTo(globalMaxRetention.getStringRep()));
assertThat(globalRetentionMap.get("default_retention"), equalTo(globalDefaultRetention.getStringRep()));
assertThat(resultMap.containsKey("data_streams"), equalTo(true));
} catch (Exception e) {
fail(e);
}
}
@SuppressWarnings("unchecked")
public void testDataStreamLifecycleToXContent() throws Exception {
TimeValue configuredRetention = TimeValue.timeValueDays(100);
TimeValue globalDefaultRetention = TimeValue.timeValueDays(10);
TimeValue globalMaxRetention = TimeValue.timeValueDays(50);
DataStreamGlobalRetention globalRetention = new DataStreamGlobalRetention(globalDefaultRetention, globalMaxRetention);
DataStreamLifecycle lifecycle = DataStreamLifecycle.createDataLifecycle(true, configuredRetention, null, null);
{
boolean isInternalDataStream = true;
GetDataStreamLifecycleAction.Response.DataStreamLifecycle explainIndexDataStreamLifecycle = createDataStreamLifecycle(
lifecycle,
isInternalDataStream
);
Map<String, Object> resultMap = getXContentMap(explainIndexDataStreamLifecycle, globalRetention);
Map<String, Object> lifecycleResult = (Map<String, Object>) resultMap.get("lifecycle");
assertThat(lifecycleResult.get("data_retention"), equalTo(configuredRetention.getStringRep()));
assertThat(lifecycleResult.get("effective_retention"), equalTo(configuredRetention.getStringRep()));
assertThat(lifecycleResult.get("retention_determined_by"), equalTo("data_stream_configuration"));
}
{
boolean isInternalDataStream = false;
GetDataStreamLifecycleAction.Response.DataStreamLifecycle explainIndexDataStreamLifecycle = createDataStreamLifecycle(
lifecycle,
isInternalDataStream
);
Map<String, Object> resultMap = getXContentMap(explainIndexDataStreamLifecycle, globalRetention);
Map<String, Object> lifecycleResult = (Map<String, Object>) resultMap.get("lifecycle");
assertThat(lifecycleResult.get("data_retention"), equalTo(configuredRetention.getStringRep()));
assertThat(lifecycleResult.get("effective_retention"), equalTo(globalMaxRetention.getStringRep()));
assertThat(lifecycleResult.get("retention_determined_by"), equalTo("max_global_retention"));
}
}
private GetDataStreamLifecycleAction.Response.DataStreamLifecycle createDataStreamLifecycle(
DataStreamLifecycle lifecycle,
boolean isInternalDataStream
) {
return new GetDataStreamLifecycleAction.Response.DataStreamLifecycle(randomAlphaOfLength(50), lifecycle, isInternalDataStream);
}
/*
* Calls toXContent on the given dataStreamLifecycle, and converts the response to a Map
*/
private Map<String, Object> getXContentMap(
GetDataStreamLifecycleAction.Response.DataStreamLifecycle dataStreamLifecycle,
DataStreamGlobalRetention globalRetention
) throws IOException {
try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) {
RolloverConfiguration rolloverConfiguration = null;
dataStreamLifecycle.toXContent(builder, ToXContent.EMPTY_PARAMS, rolloverConfiguration, globalRetention);
String serialized = Strings.toString(builder);
return XContentHelper.convertToMap(XContentType.JSON.xContent(), serialized, randomBoolean());
}
}
}
| GetDataStreamLifecycleActionTests |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/support/incrementer/SybaseMaxValueIncrementer.java | {
"start": 2319,
"end": 3178
} | class ____ extends AbstractIdentityColumnMaxValueIncrementer {
/**
* Default constructor for bean property style usage.
* @see #setDataSource
* @see #setIncrementerName
* @see #setColumnName
*/
public SybaseMaxValueIncrementer() {
}
/**
* Convenience constructor.
* @param dataSource the DataSource to use
* @param incrementerName the name of the sequence/table to use
* @param columnName the name of the column in the sequence table to use
*/
public SybaseMaxValueIncrementer(DataSource dataSource, String incrementerName, String columnName) {
super(dataSource, incrementerName, columnName);
}
@Override
protected String getIncrementStatement() {
return "insert into " + getIncrementerName() + " values()";
}
@Override
protected String getIdentityStatement() {
return "select @@identity";
}
}
| SybaseMaxValueIncrementer |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/TopBytesRefAggregatorFunction.java | {
"start": 998,
"end": 6178
} | class ____ implements AggregatorFunction {
private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of(
new IntermediateStateDesc("top", ElementType.BYTES_REF) );
private final DriverContext driverContext;
private final TopBytesRefAggregator.SingleState state;
private final List<Integer> channels;
private final int limit;
private final boolean ascending;
public TopBytesRefAggregatorFunction(DriverContext driverContext, List<Integer> channels,
TopBytesRefAggregator.SingleState state, int limit, boolean ascending) {
this.driverContext = driverContext;
this.channels = channels;
this.state = state;
this.limit = limit;
this.ascending = ascending;
}
public static TopBytesRefAggregatorFunction create(DriverContext driverContext,
List<Integer> channels, int limit, boolean ascending) {
return new TopBytesRefAggregatorFunction(driverContext, channels, TopBytesRefAggregator.initSingle(driverContext.bigArrays(), limit, ascending), limit, ascending);
}
public static List<IntermediateStateDesc> intermediateStateDesc() {
return INTERMEDIATE_STATE_DESC;
}
@Override
public int intermediateBlockCount() {
return INTERMEDIATE_STATE_DESC.size();
}
@Override
public void addRawInput(Page page, BooleanVector mask) {
if (mask.allFalse()) {
// Entire page masked away
} else if (mask.allTrue()) {
addRawInputNotMasked(page);
} else {
addRawInputMasked(page, mask);
}
}
private void addRawInputMasked(Page page, BooleanVector mask) {
BytesRefBlock vBlock = page.getBlock(channels.get(0));
BytesRefVector vVector = vBlock.asVector();
if (vVector == null) {
addRawBlock(vBlock, mask);
return;
}
addRawVector(vVector, mask);
}
private void addRawInputNotMasked(Page page) {
BytesRefBlock vBlock = page.getBlock(channels.get(0));
BytesRefVector vVector = vBlock.asVector();
if (vVector == null) {
addRawBlock(vBlock);
return;
}
addRawVector(vVector);
}
private void addRawVector(BytesRefVector vVector) {
BytesRef vScratch = new BytesRef();
for (int valuesPosition = 0; valuesPosition < vVector.getPositionCount(); valuesPosition++) {
BytesRef vValue = vVector.getBytesRef(valuesPosition, vScratch);
TopBytesRefAggregator.combine(state, vValue);
}
}
private void addRawVector(BytesRefVector vVector, BooleanVector mask) {
BytesRef vScratch = new BytesRef();
for (int valuesPosition = 0; valuesPosition < vVector.getPositionCount(); valuesPosition++) {
if (mask.getBoolean(valuesPosition) == false) {
continue;
}
BytesRef vValue = vVector.getBytesRef(valuesPosition, vScratch);
TopBytesRefAggregator.combine(state, vValue);
}
}
private void addRawBlock(BytesRefBlock vBlock) {
BytesRef vScratch = new BytesRef();
for (int p = 0; p < vBlock.getPositionCount(); p++) {
int vValueCount = vBlock.getValueCount(p);
if (vValueCount == 0) {
continue;
}
int vStart = vBlock.getFirstValueIndex(p);
int vEnd = vStart + vValueCount;
for (int vOffset = vStart; vOffset < vEnd; vOffset++) {
BytesRef vValue = vBlock.getBytesRef(vOffset, vScratch);
TopBytesRefAggregator.combine(state, vValue);
}
}
}
private void addRawBlock(BytesRefBlock vBlock, BooleanVector mask) {
BytesRef vScratch = new BytesRef();
for (int p = 0; p < vBlock.getPositionCount(); p++) {
if (mask.getBoolean(p) == false) {
continue;
}
int vValueCount = vBlock.getValueCount(p);
if (vValueCount == 0) {
continue;
}
int vStart = vBlock.getFirstValueIndex(p);
int vEnd = vStart + vValueCount;
for (int vOffset = vStart; vOffset < vEnd; vOffset++) {
BytesRef vValue = vBlock.getBytesRef(vOffset, vScratch);
TopBytesRefAggregator.combine(state, vValue);
}
}
}
@Override
public void addIntermediateInput(Page page) {
assert channels.size() == intermediateBlockCount();
assert page.getBlockCount() >= channels.get(0) + intermediateStateDesc().size();
Block topUncast = page.getBlock(channels.get(0));
if (topUncast.areAllValuesNull()) {
return;
}
BytesRefBlock top = (BytesRefBlock) topUncast;
assert top.getPositionCount() == 1;
BytesRef topScratch = new BytesRef();
TopBytesRefAggregator.combineIntermediate(state, top);
}
@Override
public void evaluateIntermediate(Block[] blocks, int offset, DriverContext driverContext) {
state.toIntermediate(blocks, offset, driverContext);
}
@Override
public void evaluateFinal(Block[] blocks, int offset, DriverContext driverContext) {
blocks[offset] = TopBytesRefAggregator.evaluateFinal(state, driverContext);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append("[");
sb.append("channels=").append(channels);
sb.append("]");
return sb.toString();
}
@Override
public void close() {
state.close();
}
}
| TopBytesRefAggregatorFunction |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/detached/initialization/DetachedNestedInitializationDelayedFetchTest.java | {
"start": 5922,
"end": 6061
} | class ____ {
@Id
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
private EntityB b;
}
@Entity(name = "EntityB")
static | EntityA |
java | quarkusio__quarkus | extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/signatures/SubscriberSignatureTest.java | {
"start": 6293,
"end": 6627
} | class ____ extends Spy {
@Channel("C")
Emitter<Integer> emitter;
public Emitter<Integer> emitter() {
return emitter;
}
@Incoming("C")
public void consume(Integer i) {
items.add(i);
}
}
@ApplicationScoped
public static | BeanUsingConsumerMethod |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/sequence/HANASequenceSupport.java | {
"start": 248,
"end": 537
} | class ____ extends NextvalSequenceSupport {
public static final SequenceSupport INSTANCE = new HANASequenceSupport();
@Override
public String getFromDual() {
return " from sys.dummy";
}
@Override
public boolean sometimesNeedsStartingValue() {
return true;
}
}
| HANASequenceSupport |
java | redisson__redisson | redisson/src/main/java/org/redisson/reactive/RedissonListMultimapCacheReactive.java | {
"start": 848,
"end": 1426
} | class ____<K, V> {
private final RListMultimap<K, V> instance;
private final CommandReactiveExecutor commandExecutor;
public RedissonListMultimapCacheReactive(RListMultimap<K, V> instance, CommandReactiveExecutor commandExecutor) {
this.instance = instance;
this.commandExecutor = commandExecutor;
}
public RListReactive<V> get(K key) {
RList<V> list = instance.get(key);
return ReactiveProxyBuilder.create(commandExecutor, list, new RedissonListReactive<>(list), RListReactive.class);
}
}
| RedissonListMultimapCacheReactive |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/data/ConstantFloatVector.java | {
"start": 742,
"end": 4283
} | class ____ extends AbstractVector implements FloatVector {
static final long RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(ConstantFloatVector.class);
private final float value;
ConstantFloatVector(float value, int positionCount, BlockFactory blockFactory) {
super(positionCount, blockFactory);
this.value = value;
}
@Override
public float getFloat(int position) {
return value;
}
@Override
public FloatBlock asBlock() {
return new FloatVectorBlock(this);
}
@Override
public FloatVector filter(int... positions) {
return blockFactory().newConstantFloatVector(value, positions.length);
}
@Override
public FloatBlock keepMask(BooleanVector mask) {
if (getPositionCount() == 0) {
incRef();
return new FloatVectorBlock(this);
}
if (mask.isConstant()) {
if (mask.getBoolean(0)) {
incRef();
return new FloatVectorBlock(this);
}
return (FloatBlock) blockFactory().newConstantNullBlock(getPositionCount());
}
try (FloatBlock.Builder builder = blockFactory().newFloatBlockBuilder(getPositionCount())) {
// TODO if X-ArrayBlock used BooleanVector for it's null mask then we could shuffle references here.
for (int p = 0; p < getPositionCount(); p++) {
if (mask.getBoolean(p)) {
builder.appendFloat(value);
} else {
builder.appendNull();
}
}
return builder.build();
}
}
@Override
public ReleasableIterator<FloatBlock> lookup(IntBlock positions, ByteSizeValue targetBlockSize) {
if (positions.getPositionCount() == 0) {
return ReleasableIterator.empty();
}
IntVector positionsVector = positions.asVector();
if (positionsVector == null) {
return new FloatLookup(asBlock(), positions, targetBlockSize);
}
int min = positionsVector.min();
if (min < 0) {
throw new IllegalArgumentException("invalid position [" + min + "]");
}
if (min > getPositionCount()) {
return ReleasableIterator.single((FloatBlock) positions.blockFactory().newConstantNullBlock(positions.getPositionCount()));
}
if (positionsVector.max() < getPositionCount()) {
return ReleasableIterator.single(positions.blockFactory().newConstantFloatBlockWith(value, positions.getPositionCount()));
}
return new FloatLookup(asBlock(), positions, targetBlockSize);
}
@Override
public ElementType elementType() {
return ElementType.FLOAT;
}
@Override
public boolean isConstant() {
return true;
}
@Override
public FloatVector deepCopy(BlockFactory blockFactory) {
return blockFactory.newConstantFloatVector(value, getPositionCount());
}
@Override
public long ramBytesUsed() {
return RAM_BYTES_USED;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof FloatVector that) {
return FloatVector.equals(this, that);
}
return false;
}
@Override
public int hashCode() {
return FloatVector.hash(this);
}
public String toString() {
return getClass().getSimpleName() + "[positions=" + getPositionCount() + ", value=" + value + ']';
}
}
| ConstantFloatVector |
java | quarkusio__quarkus | extensions/tls-registry/cli/src/main/java/io/quarkus/tls/cli/DotEnvHelper.java | {
"start": 246,
"end": 1335
} | class ____ {
private DotEnvHelper() {
// Avoid direct instantiation
}
public static List<String> readDotEnvFile() throws IOException {
if (!DOT_ENV_FILE.exists()) {
return new ArrayList<>();
}
return new ArrayList<>(Files.readAllLines(DOT_ENV_FILE.toPath()));
}
public static void addOrReplaceProperty(List<String> content, String key, String value) {
var line = hasLine(content, key);
if (line != -1) {
content.set(line, key + "=" + value);
} else {
content.add(key + "=" + value);
}
}
private static int hasLine(List<String> content, String key) {
for (int i = 0; i < content.size(); i++) {
if (content.get(i).startsWith(key + "=") || content.get(i).startsWith(key + " =")) {
return i;
}
}
return -1;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void deleteQuietly(File file) {
if (file.isFile()) {
file.delete();
}
}
}
| DotEnvHelper |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/huggingface/completion/HuggingFaceChatCompletionModelTests.java | {
"start": 740,
"end": 4611
} | class ____ extends ESTestCase {
public void testThrowsURISyntaxException_ForInvalidUrl() {
var thrownException = expectThrows(IllegalArgumentException.class, () -> createCompletionModel("^^", "secret", "id"));
assertThat(thrownException.getMessage(), containsString("unable to parse url [^^]"));
}
public static HuggingFaceChatCompletionModel createCompletionModel(String url, String apiKey, String modelId) {
return new HuggingFaceChatCompletionModel(
"id",
TaskType.COMPLETION,
"service",
new HuggingFaceChatCompletionServiceSettings(modelId, url, null),
new DefaultSecretSettings(new SecureString(apiKey.toCharArray()))
);
}
public static HuggingFaceChatCompletionModel createChatCompletionModel(String url, String apiKey, String modelId) {
return new HuggingFaceChatCompletionModel(
"id",
TaskType.CHAT_COMPLETION,
"service",
new HuggingFaceChatCompletionServiceSettings(modelId, url, null),
new DefaultSecretSettings(new SecureString(apiKey.toCharArray()))
);
}
public void testOverrideWith_UnifiedCompletionRequest_OverridesExistingModelId() {
var model = createCompletionModel("url", "api_key", "model_name");
var request = new UnifiedCompletionRequest(
List.of(new UnifiedCompletionRequest.Message(new UnifiedCompletionRequest.ContentString("hello"), "role", null, null)),
"different_model",
null,
null,
null,
null,
null,
null
);
var overriddenModel = HuggingFaceChatCompletionModel.of(model, request);
assertThat(overriddenModel.getServiceSettings().modelId(), is("different_model"));
}
public void testOverrideWith_UnifiedCompletionRequest_OverridesNullModelId() {
var model = createCompletionModel("url", "api_key", null);
var request = new UnifiedCompletionRequest(
List.of(new UnifiedCompletionRequest.Message(new UnifiedCompletionRequest.ContentString("hello"), "role", null, null)),
"different_model",
null,
null,
null,
null,
null,
null
);
var overriddenModel = HuggingFaceChatCompletionModel.of(model, request);
assertThat(overriddenModel.getServiceSettings().modelId(), is("different_model"));
}
public void testOverrideWith_UnifiedCompletionRequest_KeepsNullIfNoModelIdProvided() {
var model = createCompletionModel("url", "api_key", null);
var request = new UnifiedCompletionRequest(
List.of(new UnifiedCompletionRequest.Message(new UnifiedCompletionRequest.ContentString("hello"), "role", null, null)),
null,
null,
null,
null,
null,
null,
null
);
var overriddenModel = HuggingFaceChatCompletionModel.of(model, request);
assertNull(overriddenModel.getServiceSettings().modelId());
}
public void testOverrideWith_UnifiedCompletionRequest_UsesModelFields_WhenRequestDoesNotOverride() {
var model = createCompletionModel("url", "api_key", "model_name");
var request = new UnifiedCompletionRequest(
List.of(new UnifiedCompletionRequest.Message(new UnifiedCompletionRequest.ContentString("hello"), "role", null, null)),
null, // not overriding model
null,
null,
null,
null,
null,
null
);
var overriddenModel = HuggingFaceChatCompletionModel.of(model, request);
assertThat(overriddenModel.getServiceSettings().modelId(), is("model_name"));
}
}
| HuggingFaceChatCompletionModelTests |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/RMultimapCacheReactive.java | {
"start": 728,
"end": 865
} | interface ____ {@link RMultimapCache} object.
*
* @author Nikita Koksharov
*
* @param <K> key type
* @param <V> value type
*/
public | of |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/injection/guice/internal/AbstractBindingBuilder.java | {
"start": 990,
"end": 2936
} | class ____<T> {
public static final String IMPLEMENTATION_ALREADY_SET = "Implementation is set more than once.";
public static final String SINGLE_INSTANCE_AND_SCOPE = "Setting the scope is not permitted when binding to a single instance.";
public static final String SCOPE_ALREADY_SET = "Scope is set more than once.";
public static final String BINDING_TO_NULL = "Binding to null instances is not allowed. "
+ "Use toProvider(Providers.of(null)) if this is your intended behaviour.";
protected final List<Element> elements;
protected final int position;
protected final Binder binder;
private BindingImpl<T> binding;
public AbstractBindingBuilder(Binder binder, List<Element> elements, Object source, Key<T> key) {
this.binder = binder;
this.elements = elements;
this.position = elements.size();
this.binding = new UntargettedBindingImpl<>(source, key, Scoping.UNSCOPED);
elements.add(position, this.binding);
}
protected BindingImpl<T> getBinding() {
return binding;
}
protected BindingImpl<T> setBinding(BindingImpl<T> binding) {
this.binding = binding;
elements.set(position, binding);
return binding;
}
public void asEagerSingleton() {
checkNotScoped();
setBinding(getBinding().withEagerSingletonScoping());
}
protected void checkNotTargetted() {
if ((binding instanceof UntargettedBindingImpl) == false) {
binder.addError(IMPLEMENTATION_ALREADY_SET);
}
}
protected void checkNotScoped() {
// Scoping isn't allowed when we have only one instance.
if (binding instanceof InstanceBinding) {
binder.addError(SINGLE_INSTANCE_AND_SCOPE);
return;
}
if (binding.getScoping() != Scoping.UNSCOPED) {
binder.addError(SCOPE_ALREADY_SET);
}
}
}
| AbstractBindingBuilder |
java | spring-projects__spring-boot | module/spring-boot-mail/src/main/java/org/springframework/boot/mail/autoconfigure/MailSenderPropertiesConfiguration.java | {
"start": 1766,
"end": 3511
} | class ____ {
@Bean
@ConditionalOnMissingBean(JavaMailSender.class)
JavaMailSenderImpl mailSender(MailProperties properties, ObjectProvider<SslBundles> sslBundles) {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
applyProperties(properties, sender, sslBundles.getIfAvailable());
return sender;
}
private void applyProperties(MailProperties properties, JavaMailSenderImpl sender,
@Nullable SslBundles sslBundles) {
sender.setHost(properties.getHost());
if (properties.getPort() != null) {
sender.setPort(properties.getPort());
}
sender.setUsername(properties.getUsername());
sender.setPassword(properties.getPassword());
sender.setProtocol(properties.getProtocol());
if (properties.getDefaultEncoding() != null) {
sender.setDefaultEncoding(properties.getDefaultEncoding().name());
}
Properties javaMailProperties = asProperties(properties.getProperties());
String protocol = properties.getProtocol();
protocol = (!StringUtils.hasLength(protocol)) ? "smtp" : protocol;
Ssl ssl = properties.getSsl();
if (ssl.isEnabled()) {
javaMailProperties.setProperty("mail." + protocol + ".ssl.enable", "true");
}
if (ssl.getBundle() != null) {
Assert.state(sslBundles != null, "'sslBundles' must not be null");
SslBundle sslBundle = sslBundles.getBundle(ssl.getBundle());
javaMailProperties.put("mail." + protocol + ".ssl.socketFactory",
sslBundle.createSslContext().getSocketFactory());
}
if (!javaMailProperties.isEmpty()) {
sender.setJavaMailProperties(javaMailProperties);
}
}
private Properties asProperties(Map<String, String> source) {
Properties properties = new Properties();
properties.putAll(source);
return properties;
}
}
| MailSenderPropertiesConfiguration |
java | apache__camel | components/camel-infinispan/camel-infinispan/src/test/java/org/apache/camel/component/infinispan/remote/cluster/AbstractInfinispanRemoteClusteredIT.java | {
"start": 6518,
"end": 7436
} | class ____ {
public RouteBuilder getRouteBuilder(RunnerEnv runnerEnv) {
return new RouteBuilder() {
@Override
public void configure() {
this.getContext().addRoutePolicyFactory(ClusteredRoutePolicyFactory.forNamespace(viewName));
fromF("timer:%s?delay=1000&period=1000&repeatCount=%d", runnerEnv.id, runnerEnv.events)
.routeId("route-" + runnerEnv.id)
.log("From id=${routeId} counter=${header.CamelTimerCounter}")
.process(e -> runnerEnv.latch.countDown());
}
};
}
@Timeout(value = 1, unit = TimeUnit.MINUTES)
@Test
public void test() throws Exception {
runTest(this::getRouteBuilder);
}
}
@Nested
| InfinispanRemoteClusteredRoutePolicyFactoryTestNested |
java | elastic__elasticsearch | x-pack/plugin/otel-data/src/test/java/org/elasticsearch/xpack/oteldata/otlp/datapoint/TargetIndexTests.java | {
"start": 620,
"end": 6725
} | class ____ extends ESTestCase {
public void testEvaluateWithExplicitIndex() {
List<KeyValue> attributes = List.of(
createStringAttribute("elasticsearch.index", "custom-index"),
createStringAttribute("data_stream.dataset", "should-be-ignored"),
createStringAttribute("data_stream.namespace", "should-be-ignored")
);
TargetIndex index = TargetIndex.evaluate("metrics", attributes, null, List.of(), List.of());
assertThat(index.index(), equalTo("custom-index"));
assertThat(index.isDataStream(), is(false));
assertThat(index.type(), nullValue());
assertThat(index.dataset(), nullValue());
assertThat(index.namespace(), nullValue());
}
public void testEvaluateWithDataStreamAttributes() {
List<KeyValue> attributes = List.of(
createStringAttribute("data_stream.dataset", "custom-dataset"),
createStringAttribute("data_stream.namespace", "custom-namespace")
);
TargetIndex index = TargetIndex.evaluate("metrics", attributes, null, List.of(), List.of());
// DataStream.sanitizeDataset replaces hyphens with underscores
assertThat(index.index(), equalTo("metrics-custom_dataset.otel-custom-namespace"));
assertThat(index.isDataStream(), is(true));
assertThat(index.type(), equalTo("metrics"));
assertThat(index.dataset(), equalTo("custom_dataset.otel"));
assertThat(index.namespace(), equalTo("custom-namespace"));
}
public void testEvaluateWithScopeAttributes() {
List<KeyValue> scopeAttributes = List.of(
createStringAttribute("data_stream.dataset", "scope-dataset"),
createStringAttribute("data_stream.namespace", "scope-namespace")
);
TargetIndex index = TargetIndex.evaluate("metrics", List.of(), null, scopeAttributes, List.of());
// DataStream.sanitizeDataset replaces hyphens with underscores
assertThat(index.index(), equalTo("metrics-scope_dataset.otel-scope-namespace"));
assertThat(index.isDataStream(), is(true));
assertThat(index.type(), equalTo("metrics"));
assertThat(index.dataset(), equalTo("scope_dataset.otel"));
assertThat(index.namespace(), equalTo("scope-namespace"));
}
public void testEvaluateWithResourceAttributes() {
List<KeyValue> resourceAttributes = List.of(
createStringAttribute("data_stream.dataset", "resource-dataset"),
createStringAttribute("data_stream.namespace", "resource-namespace")
);
TargetIndex index = TargetIndex.evaluate("metrics", List.of(), null, List.of(), resourceAttributes);
// DataStream.sanitizeDataset replaces hyphens with underscores
assertThat(index.index(), equalTo("metrics-resource_dataset.otel-resource-namespace"));
assertThat(index.isDataStream(), is(true));
assertThat(index.type(), equalTo("metrics"));
assertThat(index.dataset(), equalTo("resource_dataset.otel"));
assertThat(index.namespace(), equalTo("resource-namespace"));
}
public void testAttributePrecedence() {
// The order of precedence should be: attributes > scopeAttributes > resourceAttributes
List<KeyValue> attributes = List.of(createStringAttribute("data_stream.dataset", "attr-dataset"));
List<KeyValue> scopeAttributes = List.of(
createStringAttribute("data_stream.dataset", "scope-dataset"),
createStringAttribute("data_stream.namespace", "scope-namespace")
);
List<KeyValue> resourceAttributes = List.of(
createStringAttribute("data_stream.dataset", "resource-dataset"),
createStringAttribute("data_stream.namespace", "resource-namespace")
);
TargetIndex index = TargetIndex.evaluate("metrics", attributes, null, scopeAttributes, resourceAttributes);
// DataStream.sanitizeDataset replaces hyphens with underscores
assertThat(index.index(), equalTo("metrics-attr_dataset.otel-scope-namespace"));
assertThat(index.isDataStream(), is(true));
assertThat(index.type(), equalTo("metrics"));
assertThat(index.dataset(), equalTo("attr_dataset.otel"));
assertThat(index.namespace(), equalTo("scope-namespace"));
}
public void testEvaluateWithReceiverInScopeName() {
TargetIndex index = TargetIndex.evaluate("metrics", List.of(), "hostmetrics-receiver", List.of(), List.of());
assertThat(index.index(), equalTo("metrics-hostmetrics_receiver.otel-default"));
assertThat(index.isDataStream(), is(true));
assertThat(index.type(), equalTo("metrics"));
assertThat(index.dataset(), equalTo("hostmetrics_receiver.otel"));
assertThat(index.namespace(), equalTo("default"));
}
public void testEvaluateWithDefaultValues() {
TargetIndex index = TargetIndex.evaluate("metrics", List.of(), null, List.of(), List.of());
assertThat(index.index(), equalTo("metrics-generic.otel-default"));
assertThat(index.isDataStream(), is(true));
assertThat(index.type(), equalTo("metrics"));
assertThat(index.dataset(), equalTo("generic.otel"));
assertThat(index.namespace(), equalTo("default"));
}
public void testDataStreamSanitization() {
List<KeyValue> attributes = List.of(
createStringAttribute("data_stream.dataset", "Some-Dataset"),
createStringAttribute("data_stream.namespace", "Some*Namespace")
);
TargetIndex index = TargetIndex.evaluate("metrics", attributes, null, List.of(), List.of());
// DataStream.sanitizeDataset and DataStream.sanitizeNamespace should be applied
assertThat(index.dataset(), equalTo("some_dataset.otel"));
assertThat(index.namespace(), equalTo("some_namespace"));
}
private KeyValue createStringAttribute(String key, String value) {
return KeyValue.newBuilder().setKey(key).setValue(AnyValue.newBuilder().setStringValue(value).build()).build();
}
}
| TargetIndexTests |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/instance/ArcContainerSelectTest.java | {
"start": 1127,
"end": 2175
} | class ____ {
@RegisterExtension
public ArcTestContainer container = new ArcTestContainer(Alpha.class, Washcloth.class);
@SuppressWarnings("serial")
@Test
public void testSelect() {
assertTrue(Arc.container().select(BeanManager.class).isResolvable());
InjectableInstance<Supplier<String>> instance = Arc.container().select(new TypeLiteral<Supplier<String>>() {
});
Set<String> strings = new HashSet<>();
for (InstanceHandle<Supplier<String>> handle : instance.handles()) {
strings.add(handle.get().get());
handle.close();
}
assertEquals(2, strings.size());
assertTrue(strings.contains("alpha"));
assertTrue(strings.contains("washcloth"));
assertTrue(Washcloth.INIT.get());
assertTrue(Washcloth.DESTROYED.get());
assertThatThrownBy(() -> Arc.container().select(Alpha.class, new TestLiteral()))
.isInstanceOf(IllegalArgumentException.class);
}
@Singleton
static | ArcContainerSelectTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/RebalanceOnlyWhenActiveAllocationDecider.java | {
"start": 763,
"end": 1625
} | class ____ extends AllocationDecider {
public static final String NAME = "rebalance_only_when_active";
static final Decision YES_ALL_REPLICAS_ACTIVE = Decision.single(
Decision.Type.YES,
NAME,
"rebalancing is allowed as all copies of this shard are active"
);
static final Decision NO_SOME_REPLICAS_INACTIVE = Decision.single(
Decision.Type.NO,
NAME,
"rebalancing is not allowed until all copies of this shard are active"
);
@Override
public Decision canRebalance(ShardRouting shardRouting, RoutingAllocation allocation) {
return allocation.routingNodes().allShardsActive(shardRouting.shardId(), allocation.metadata().projectFor(shardRouting.index()))
? YES_ALL_REPLICAS_ACTIVE
: NO_SOME_REPLICAS_INACTIVE;
}
}
| RebalanceOnlyWhenActiveAllocationDecider |
java | redisson__redisson | redisson/src/main/java/org/redisson/client/protocol/decoder/StringListReplayDecoder.java | {
"start": 929,
"end": 1352
} | class ____ implements MultiDecoder<List<String>> {
@Override
public Decoder<Object> getDecoder(Codec codec, int paramNum, State state, long size) {
return StringCodec.INSTANCE.getValueDecoder();
}
@Override
public List<String> decode(List<Object> parts, State state) {
return Arrays.asList(Arrays.copyOf(parts.toArray(), parts.size(), String[].class));
}
}
| StringListReplayDecoder |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM2.java | {
"start": 2396,
"end": 2665
} | class ____ {
private List<Integer> list = new ArrayList<Integer>();
public List<Integer> getList() {
return list;
}
public void setList(List<Integer> list) {
this.list = list;
}
}
public static | V1 |
java | quarkusio__quarkus | extensions/vertx/deployment/src/test/java/io/quarkus/vertx/deployment/MessageConsumerMethodTest.java | {
"start": 1035,
"end": 8255
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot(root -> root.addClasses(SimpleBean.class, Transformer.class))
.overrideConfigKey("foo", "foo-config");
@Inject
SimpleBean simpleBean;
@Inject
EventBus eventBus;
@Test
public void testSend() throws InterruptedException {
BlockingQueue<Object> synchronizer = new LinkedBlockingQueue<>();
eventBus.request("foo", "hello", ar -> {
if (ar.succeeded()) {
try {
synchronizer.put(ar.result().body());
} catch (InterruptedException e) {
fail(e);
}
} else {
fail(ar.cause());
}
});
assertEquals("HELLO", synchronizer.poll(2, TimeUnit.SECONDS));
}
@Test
public void testSendGenericType() throws InterruptedException {
BlockingQueue<Object> synchronizer = new LinkedBlockingQueue<>();
eventBus.request("foos", List.of(1, 2), ar -> {
if (ar.succeeded()) {
try {
synchronizer.put(ar.result().body());
} catch (InterruptedException e) {
fail(e);
}
} else {
fail(ar.cause());
}
});
assertEquals(3, synchronizer.poll(2, TimeUnit.SECONDS));
}
@Test
public void testSendAsync() throws InterruptedException {
BlockingQueue<Object> synchronizer = new LinkedBlockingQueue<>();
eventBus.request("foo-async", "hello", ar -> {
if (ar.succeeded()) {
try {
synchronizer.put(ar.result().body());
} catch (InterruptedException e) {
fail(e);
}
} else {
fail(ar.cause());
}
});
assertEquals("olleh", synchronizer.poll(2, TimeUnit.SECONDS));
}
@Test
public void testSendAsyncUni() throws InterruptedException {
BlockingQueue<Object> synchronizer = new LinkedBlockingQueue<>();
eventBus.request("foo-async-uni", "hello-uni", ar -> {
if (ar.succeeded()) {
try {
synchronizer.put(ar.result().body());
} catch (InterruptedException e) {
fail(e);
}
} else {
fail(ar.cause());
}
});
assertEquals("inu-olleh", synchronizer.poll(2, TimeUnit.SECONDS));
}
@Test
public void testSendDefaultAddress() throws InterruptedException {
BlockingQueue<Object> synchronizer = new LinkedBlockingQueue<>();
eventBus.request("io.quarkus.vertx.deployment.MessageConsumerMethodTest$SimpleBean", "Hello", ar -> {
if (ar.succeeded()) {
try {
synchronizer.put(ar.result().body());
} catch (InterruptedException e) {
fail(e);
}
} else {
fail(ar.cause());
}
});
assertEquals("hello", synchronizer.poll(2, TimeUnit.SECONDS));
}
@Test
public void testRequestContext() throws InterruptedException {
BlockingQueue<Object> synchronizer = new LinkedBlockingQueue<>();
eventBus.request("request", "Martin", ar -> {
if (ar.succeeded()) {
try {
synchronizer.put(ar.result().body());
} catch (InterruptedException e) {
fail(e);
}
} else {
fail(ar.cause());
}
});
assertEquals("MArtin", synchronizer.poll(2, TimeUnit.SECONDS));
}
@Test
public void testBlockingRequestContext() throws InterruptedException {
BlockingQueue<Object> synchronizer = new LinkedBlockingQueue<>();
eventBus.request("blocking-request", "Lu", ar -> {
if (ar.succeeded()) {
try {
synchronizer.put(ar.result().body());
} catch (InterruptedException e) {
fail(e);
}
} else {
fail(ar.cause());
}
});
assertEquals("Lu", synchronizer.poll(2, TimeUnit.SECONDS));
}
@Test
public void testPublish() throws InterruptedException {
SimpleBean.MESSAGES.clear();
SimpleBean.latch = new CountDownLatch(2);
eventBus.publish("pub", "Hello");
SimpleBean.latch.await(2, TimeUnit.SECONDS);
assertTrue(SimpleBean.MESSAGES.contains("hello"));
assertTrue(SimpleBean.MESSAGES.contains("HELLO"));
}
@Test
public void testBlockingConsumer() throws InterruptedException {
SimpleBean.MESSAGES.clear();
SimpleBean.latch = new CountDownLatch(1);
eventBus.publish("blocking", "Hello");
SimpleBean.latch.await(2, TimeUnit.SECONDS);
assertEquals(1, SimpleBean.MESSAGES.size());
String message = SimpleBean.MESSAGES.get(0);
assertTrue(message.contains("hello::true"));
}
@Test
public void testPublishMutiny() throws InterruptedException {
SimpleBean.MESSAGES.clear();
SimpleBean.latch = new CountDownLatch(1);
eventBus.publish("pub-mutiny", "Hello");
SimpleBean.latch.await(2, TimeUnit.SECONDS);
assertTrue(SimpleBean.MESSAGES.contains("HELLO"));
}
@Test
public void testBlockingConsumerUsingSmallRyeBlocking() throws InterruptedException {
SimpleBean.MESSAGES.clear();
SimpleBean.latch = new CountDownLatch(1);
eventBus.publish("worker", "Hello");
SimpleBean.latch.await(2, TimeUnit.SECONDS);
assertEquals(1, SimpleBean.MESSAGES.size());
String message = SimpleBean.MESSAGES.get(0);
assertTrue(message.contains("hello::true"));
}
@Test
public void testConfiguredAddress() throws InterruptedException {
BlockingQueue<Object> synchronizer = new LinkedBlockingQueue<>();
eventBus.request("foo-config", "hello", ar -> {
if (ar.succeeded()) {
try {
synchronizer.put(ar.result().body());
} catch (InterruptedException e) {
fail(e);
}
} else {
fail(ar.cause());
}
});
assertEquals("HELLO!", synchronizer.poll(2, TimeUnit.SECONDS));
}
@Test
public void testConfiguredAddressDefault() throws InterruptedException {
BlockingQueue<Object> synchronizer = new LinkedBlockingQueue<>();
eventBus.request("foo-config-default", "hello", ar -> {
if (ar.succeeded()) {
try {
synchronizer.put(ar.result().body());
} catch (InterruptedException e) {
fail(e);
}
} else {
fail(ar.cause());
}
});
assertEquals("hello!", synchronizer.poll(2, TimeUnit.SECONDS));
}
static | MessageConsumerMethodTest |
java | spring-projects__spring-boot | module/spring-boot-ldap/src/test/java/org/springframework/boot/ldap/autoconfigure/LdapPropertiesTests.java | {
"start": 976,
"end": 1648
} | class ____ {
@Test
void ldapTemplatePropertiesUseConsistentLdapTemplateDefaultValues() {
Template templateProperties = new LdapProperties().getTemplate();
LdapTemplate ldapTemplate = new LdapTemplate();
assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignorePartialResultException",
templateProperties.isIgnorePartialResultException());
assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignoreNameNotFoundException",
templateProperties.isIgnoreNameNotFoundException());
assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignoreSizeLimitExceededException",
templateProperties.isIgnoreSizeLimitExceededException());
}
}
| LdapPropertiesTests |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/cluster/CamelClusterMember.java | {
"start": 881,
"end": 1103
} | interface ____ extends HasId {
/**
* @return true if this member is the master.
*/
boolean isLeader();
/**
* @return true if this member is local.
*/
boolean isLocal();
}
| CamelClusterMember |
java | google__error-prone | core/src/test/java/com/google/errorprone/ErrorProneCompilerIntegrationTest.java | {
"start": 28633,
"end": 28991
} | class ____ extends BugChecker implements MethodInvocationTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
requireNonNull(ASTHelpers.getSymbol(tree));
return NO_MATCH;
}
}
@BugPattern(summary = "Duplicates CPSChecker", severity = ERROR)
public static | GetSymbolChecker |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/CannotMockFinalClassTest.java | {
"start": 3639,
"end": 3881
} | class ____ {}
@Mock FinalClass impossible;
public void method() {
FinalClass local = Mockito.mock(FinalClass.class);
}
}\
""")
.doTest();
}
}
| FinalClass |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/sqlprovider/ProviderMethodResolutionTest.java | {
"start": 8948,
"end": 9307
} | class ____ implements ProviderMethodResolver {
public static String update() {
return "UPDATE foo SET name = #{name} WHERE id = #{id}";
}
public static StringBuilder update(ProviderContext context) {
return new StringBuilder("UPDATE foo SET name = #{name} WHERE id = #{id}");
}
}
}
| MethodResolverBasedSqlProvider |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/collection/spi/PersistentList.java | {
"start": 910,
"end": 11496
} | class ____<E> extends AbstractPersistentCollection<E> implements List<E> {
protected List<E> list;
/**
* Constructs a PersistentList. This form needed for SOAP libraries, etc
*/
public PersistentList() {
}
/**
* Constructs a PersistentList.
*
* @param session The session
*/
public PersistentList(SharedSessionContractImplementor session) {
super( session );
}
/**
* Constructs a PersistentList.
*
* @param session The session
* @param list The raw list
*/
public PersistentList(SharedSessionContractImplementor session, List<E> list) {
super( session );
this.list = list;
setInitialized();
setDirectlyAccessible( true );
}
protected List<E> getRawList() {
return list;
}
@Override
public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
final ArrayList<Object> clonedList = new ArrayList<>( list.size() );
for ( Object element : list ) {
final Object deepCopy = persister.getElementType().deepCopy( element, persister.getFactory() );
clonedList.add( deepCopy );
}
return clonedList;
}
@Override
public Collection<E> getOrphans(Serializable snapshot, String entityName) throws HibernateException {
return getOrphans( (List<E>) snapshot, list, entityName, getSession() );
}
@Override
@SuppressWarnings("unchecked")
public void initializeEmptyCollection(CollectionPersister persister) {
assert list == null;
//noinspection unchecked
list = (List<E>) persister.getCollectionSemantics().instantiateRaw( 0, persister );
endRead();
}
@Override
public boolean equalsSnapshot(CollectionPersister persister) throws HibernateException {
final Type elementType = persister.getElementType();
final List<?> sn = (List<?>) getSnapshot();
if ( sn.size() != this.list.size() ) {
return false;
}
final Iterator<?> itr = list.iterator();
final Iterator<?> snapshotItr = sn.iterator();
while ( itr.hasNext() ) {
if ( elementType.isDirty( itr.next(), snapshotItr.next(), getSession() ) ) {
return false;
}
}
return true;
}
@Override
public boolean isSnapshotEmpty(Serializable snapshot) {
return ( (Collection<?>) snapshot ).isEmpty();
}
@Override
@SuppressWarnings("unchecked")
public void initializeFromCache(CollectionPersister persister, Object disassembled, Object owner)
throws HibernateException {
final Serializable[] array = (Serializable[]) disassembled;
final int size = array.length;
assert list == null;
list = (List<E>) persister.getCollectionSemantics().instantiateRaw( size, persister );
for ( Serializable arrayElement : array ) {
list.add( (E) persister.getElementType().assemble( arrayElement, getSession(), owner ) );
}
}
@Override
public void injectLoadedState(PluralAttributeMapping attributeMapping, List<?> loadingStateList) {
assert isInitializing();
assert list == null;
final var collectionDescriptor = attributeMapping.getCollectionDescriptor();
final var collectionSemantics = collectionDescriptor.getCollectionSemantics();
//noinspection unchecked
list = (List<E>) collectionSemantics.instantiateRaw( loadingStateList.size(), collectionDescriptor );
//noinspection unchecked
list.addAll( (List<E>) loadingStateList );
}
@Override
public boolean isWrapper(Object collection) {
return list==collection;
}
@Override
public int size() {
return readSize() ? getCachedSize() : list.size();
}
@Override
public boolean isEmpty() {
return readSize() ? getCachedSize()==0 : list.isEmpty();
}
@Override
public boolean contains(Object object) {
final Boolean exists = readElementExistence( object );
return exists == null
? list.contains( object )
: exists;
}
@Override
public Iterator<E> iterator() {
read();
return new IteratorProxy<>( list.iterator() );
}
@Override
public Object[] toArray() {
read();
return list.toArray();
}
@Override
public <A> A[] toArray(A[] array) {
read();
return list.toArray( array );
}
@Override
public boolean add(E object) {
if ( !isOperationQueueEnabled() ) {
write();
return list.add( object );
}
else {
queueOperation( new SimpleAdd( object ) );
return true;
}
}
@Override
public boolean remove(Object value) {
final Boolean exists = isPutQueueEnabled() ? readElementExistence( value ) : null;
if ( exists == null ) {
initialize( true );
if ( list.remove( value ) ) {
elementRemoved = true;
dirty();
return true;
}
else {
return false;
}
}
else if ( exists ) {
elementRemoved = true;
queueOperation( new SimpleRemove( (E) value ) );
return true;
}
else {
return false;
}
}
@Override
public boolean containsAll(Collection<?> coll) {
read();
return list.containsAll( coll );
}
@Override
public boolean addAll(Collection<? extends E> values) {
if ( values.isEmpty() ) {
return false;
}
if ( !isOperationQueueEnabled() ) {
write();
return list.addAll( values );
}
else {
for ( E value : values ) {
queueOperation( new SimpleAdd( value ) );
}
return !values.isEmpty();
}
}
@Override
public boolean addAll(int index, Collection<? extends E> coll) {
if ( coll.size() > 0 ) {
write();
return list.addAll( index, coll );
}
else {
return false;
}
}
@Override
public boolean removeAll(Collection<?> coll) {
if ( coll.size() > 0 ) {
initialize( true );
if ( list.removeAll( coll ) ) {
elementRemoved = true;
dirty();
return true;
}
else {
return false;
}
}
else {
return false;
}
}
@Override
public boolean retainAll(Collection<?> coll) {
initialize( true );
if ( list.retainAll( coll ) ) {
dirty();
return true;
}
else {
return false;
}
}
@Override
public void clear() {
if ( isClearQueueEnabled() ) {
queueOperation( new Clear() );
}
else {
initialize( true );
if ( ! list.isEmpty() ) {
list.clear();
dirty();
}
}
}
@Override
public E get(int index) {
if ( index < 0 ) {
throw new ArrayIndexOutOfBoundsException( "negative index" );
}
final Object result = readElementByIndex( index );
return result == UNKNOWN ? list.get( index ) : (E) result;
}
@Override
public E set(int index, E value) {
if (index<0) {
throw new ArrayIndexOutOfBoundsException("negative index");
}
final Object old = isPutQueueEnabled() ? readElementByIndex( index ) : UNKNOWN;
if ( old==UNKNOWN ) {
write();
return list.set( index, value );
}
else {
queueOperation( new Set( index, value, (E) old ) );
return (E) old;
}
}
@Override
public E remove(int index) {
if ( index < 0 ) {
throw new ArrayIndexOutOfBoundsException( "negative index" );
}
final Object old = isPutQueueEnabled() ? readElementByIndex( index ) : UNKNOWN;
elementRemoved = true;
if ( old == UNKNOWN ) {
write();
dirty();
return list.remove( index );
}
else {
queueOperation( new Remove( index, (E) old ) );
return (E) old;
}
}
@Override
public void add(int index, E value) {
if ( index < 0 ) {
throw new ArrayIndexOutOfBoundsException( "negative index" );
}
write();
list.add( index, value );
}
@Override
public int indexOf(Object value) {
read();
return list.indexOf( value );
}
@Override
public int lastIndexOf(Object value) {
read();
return list.lastIndexOf( value );
}
@Override
public ListIterator<E> listIterator() {
read();
return new ListIteratorProxy( list.listIterator() );
}
@Override
public ListIterator<E> listIterator(int index) {
read();
return new ListIteratorProxy( list.listIterator( index ) );
}
@Override
public List<E> subList(int from, int to) {
read();
return new ListProxy( list.subList( from, to ) );
}
@Override
public boolean empty() {
return list.isEmpty();
}
@Override
public String toString() {
read();
return list.toString();
}
@Override
public Iterator<E> entries(CollectionPersister persister) {
return list.iterator();
}
@Override
public Object disassemble(CollectionPersister persister) throws HibernateException {
final int length = list.size();
final Serializable[] result = new Serializable[length];
for ( int i=0; i<length; i++ ) {
result[i] = persister.getElementType().disassemble( list.get( i ), getSession(), null );
}
return result;
}
@Override
public Iterator<?> getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException {
final List<Object> deletes = new ArrayList<>();
final List<?> sn = (List<?>) getSnapshot();
int end;
final int snSize = sn.size();
if ( snSize > list.size() ) {
for ( int i = list.size(); i < snSize; i++ ) {
deletes.add( indexIsFormula ? sn.get( i ) : i );
}
end = list.size();
}
else {
end = snSize;
}
for ( int i=0; i<end; i++ ) {
final Object item = list.get( i );
final Object snapshotItem = sn.get( i );
if ( item == null && snapshotItem != null ) {
deletes.add( indexIsFormula ? snapshotItem : i );
}
}
return deletes.iterator();
}
@Override
public boolean hasDeletes(CollectionPersister persister) {
final List<?> sn = (List<?>) getSnapshot();
int snSize = sn.size();
if ( snSize > list.size() ) {
return true;
}
for ( int i=0; i<snSize; i++ ) {
if ( list.get( i ) == null && sn.get( i ) != null ) {
return true;
}
}
return false;
}
@Override
public boolean needsInserting(Object entry, int i, Type elemType) throws HibernateException {
final List<?> sn = (List<?>) getSnapshot();
return list.get( i ) != null && ( i >= sn.size() || sn.get( i ) == null );
}
@Override
public boolean needsUpdating(Object entry, int i, Type elemType) throws HibernateException {
final List<?> sn = (List<?>) getSnapshot();
return i < sn.size()
&& sn.get( i ) != null
&& list.get( i ) != null
&& elemType.isDirty( list.get( i ), sn.get( i ), getSession() );
}
@Override
public Object getIndex(Object entry, int i, CollectionPersister persister) {
return i;
}
@Override
public Object getElement(Object entry) {
return entry;
}
@Override
public Object getSnapshotElement(Object entry, int i) {
final List<?> sn = (List<?>) getSnapshot();
return sn.get( i );
}
@Override
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
public boolean equals(Object other) {
read();
return list.equals( other );
}
@Override
public int hashCode() {
read();
return list.hashCode();
}
@Override
public boolean entryExists(Object entry, int i) {
return entry!=null;
}
final | PersistentList |
java | netty__netty | example/src/main/java/io/netty/example/echo/EchoClientHandler.java | {
"start": 1018,
"end": 1947
} | class ____ extends ChannelInboundHandlerAdapter {
private final ByteBuf firstMessage;
/**
* Creates a client-side handler.
*/
public EchoClientHandler() {
firstMessage = Unpooled.buffer(EchoClient.SIZE);
for (int i = 0; i < firstMessage.capacity(); i ++) {
firstMessage.writeByte((byte) i);
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(firstMessage);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ctx.write(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}
| EchoClientHandler |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/FetchWithRootGraphTest.java | {
"start": 2100,
"end": 2588
} | class ____ {
@Id
private Long id;
private String text;
public SimpleEntity() {
}
public SimpleEntity(Long id, String text) {
this.id = id;
this.text = text;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
@Entity(name = "EntityWithReference")
@Table(name = "EntityWithReference")
static | SimpleEntity |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhance/version/SimpleEntity.java | {
"start": 619,
"end": 1612
} | class ____ implements ManagedEntity {
@Id
private Integer id;
private String name;
@Override
public Object $$_hibernate_getEntityInstance() {
return null;
}
@Override
public EntityEntry $$_hibernate_getEntityEntry() {
return null;
}
@Override
public void $$_hibernate_setEntityEntry(EntityEntry entityEntry) {
}
@Override
public ManagedEntity $$_hibernate_getPreviousManagedEntity() {
return null;
}
@Override
public void $$_hibernate_setPreviousManagedEntity(ManagedEntity previous) {
}
@Override
public ManagedEntity $$_hibernate_getNextManagedEntity() {
return null;
}
@Override
public void $$_hibernate_setNextManagedEntity(ManagedEntity next) {
}
@Override
public void $$_hibernate_setUseTracker(boolean useTracker) {
}
@Override
public boolean $$_hibernate_useTracker() {
return false;
}
@Override
public int $$_hibernate_getInstanceId() {
return 0;
}
@Override
public void $$_hibernate_setInstanceId(int id) {
}
}
| SimpleEntity |
java | netty__netty | codec-dns/src/test/java/io/netty/handler/codec/dns/NativeImageHandlerMetadataTest.java | {
"start": 772,
"end": 960
} | class ____ {
@Test
public void collectAndCompareMetadata() {
ChannelHandlerMetadataUtil.generateMetadata("io.netty.handler.codec.dns");
}
}
| NativeImageHandlerMetadataTest |
java | google__guice | core/src/com/google/inject/TypeLiteral.java | {
"start": 1477,
"end": 1809
} | class ____ enables retrieval of
* the type information even at runtime.
*
* <p>For example, to create a type literal for {@code List<String>}, you can create an empty
* anonymous inner class:
*
* <p>{@code TypeLiteral<List<String>> list = new TypeLiteral<List<String>>() {};}
*
* <p>Along with modeling generic types, this | which |
java | google__guava | android/guava/src/com/google/common/cache/LocalCache.java | {
"start": 47388,
"end": 48010
} | class ____<K, V> extends WeakValueReference<K, V> {
final int weight;
WeightedWeakValueReference(
ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry, int weight) {
super(queue, referent, entry);
this.weight = weight;
}
@Override
public int getWeight() {
return weight;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new WeightedWeakValueReference<>(queue, value, entry, weight);
}
}
/** References a soft value. */
static final | WeightedWeakValueReference |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/cluster/settings/ClusterSettingsUpdateWithFaultyMasterIT.java | {
"start": 1360,
"end": 3561
} | class ____ extends ESIntegTestCase {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return List.of(BlockingClusterSettingTestPlugin.class, MockTransportService.TestPlugin.class);
}
public void testClusterSettingsUpdateNotAcknowledged() throws Exception {
final var nodes = internalCluster().startMasterOnlyNodes(3);
final String masterNode = internalCluster().getMasterName();
final String blockedNode = randomValueOtherThan(masterNode, () -> randomFrom(nodes));
assertThat(blockedNode, not(equalTo(internalCluster().getMasterName())));
ensureStableCluster(3);
NetworkDisruption networkDisruption = new NetworkDisruption(
new NetworkDisruption.TwoPartitions(
Set.of(blockedNode),
nodes.stream().filter(n -> n.equals(blockedNode) == false).collect(Collectors.toSet())
),
NetworkDisruption.DISCONNECT
);
internalCluster().setDisruptionScheme(networkDisruption);
logger.info("--> updating cluster settings");
var future = client(masterNode).admin()
.cluster()
.prepareUpdateSettings(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT)
.setPersistentSettings(Settings.builder().put(BlockingClusterSettingTestPlugin.TEST_BLOCKING_SETTING.getKey(), true).build())
.setMasterNodeTimeout(TimeValue.timeValueMillis(100L))
.execute();
logger.info("--> waiting for cluster state update to be blocked");
safeAwait(BlockingClusterSettingTestPlugin.blockLatch);
logger.info("--> isolating master eligible node [{}] from other nodes", blockedNode);
networkDisruption.startDisrupting();
logger.info("--> unblocking cluster state update");
BlockingClusterSettingTestPlugin.releaseLatch.countDown();
assertThat("--> cluster settings update should not be acknowledged", future.get().isAcknowledged(), equalTo(false));
logger.info("--> stop network disruption");
networkDisruption.stopDisrupting();
ensureStableCluster(3);
}
public static | ClusterSettingsUpdateWithFaultyMasterIT |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/discovery/DiscoveryTests.java | {
"start": 20264,
"end": 20398
} | class ____ {
@Test
private static int test() {
return fail("should not be called");
}
}
static | InvalidTestMethodTestCase |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/DoNotMockCheckerTest.java | {
"start": 9350,
"end": 10054
} | class ____ {
// BUG: Diagnostic contains:
@Mock MetaDoNotMockObject metaAnnotatedDoNotMockObject;
// BUG: Diagnostic contains:
@Mock MetaDoNotMockInterface metaDoNotMockInterface;
@Mock MockableObject mockableObject;
@Mock DoubleMetaAnnotatedDoNotMock doubleMetaAnnotatedDoNotMock; // mockable
}
""")
.doTest();
}
@Test
public void matchesMockitoDotMock_autoValue() {
testHelper
.addSourceLines(
"lib/Lib.java",
"""
package lib;
import org.mockito.Mockito;
import lib.AutoValueObjects.*;
public | Lib |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/aot/generate/GeneratedClasses.java | {
"start": 3110,
"end": 3314
} | class ____ the specified {@code featureName}
* targeting the specified {@code component}. If this method has previously
* been called with the given {@code featureName}/{@code target} the
* existing | for |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/FutureTransformAsyncTest.java | {
"start": 13112,
"end": 13708
} | class ____ {
private Executor executor;
ListenableFuture<String> foo(String s) {
return immediateFuture(s);
}
ListenableFuture<String> test() {
ListenableFuture<String> future = transform(foo("x"), value -> "value: " + value, executor);
return future;
}
}
""")
.doTest();
}
@Test
public void transformAsync_immediateVoidFuture() {
refactoringHelper
.addInputLines(
"in/Test.java",
"""
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.Executor;
| Test |
java | spring-projects__spring-framework | spring-oxm/src/main/java/org/springframework/oxm/Marshaller.java | {
"start": 1235,
"end": 1366
} | interface ____ {
/**
* Indicate whether this marshaller can marshal instances of the supplied type.
* @param clazz the | Marshaller |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/short_/ShortAssert_isStrictlyBetween_Shorts_Test.java | {
"start": 908,
"end": 1286
} | class ____ extends ShortAssertBaseTest {
@Override
protected ShortAssert invoke_api_method() {
return assertions.isStrictlyBetween((short) 6, (short) 8);
}
@Override
protected void verify_internal_effects() {
verify(shorts).assertIsStrictlyBetween(getInfo(assertions), getActual(assertions), (short) 6, (short) 8);
}
}
| ShortAssert_isStrictlyBetween_Shorts_Test |
java | alibaba__nacos | config/src/main/java/com/alibaba/nacos/config/server/model/ConfigInfoTagWrapper.java | {
"start": 770,
"end": 1349
} | class ____ extends ConfigInfo4Tag {
private static final long serialVersionUID = 4511997359365712505L;
private long lastModified;
public ConfigInfoTagWrapper() {
}
public long getLastModified() {
return lastModified;
}
public void setLastModified(long lastModified) {
this.lastModified = lastModified;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
} | ConfigInfoTagWrapper |
java | spring-projects__spring-boot | module/spring-boot-data-commons/src/test/java/org/springframework/boot/data/autoconfigure/metrics/DataRepositoryMetricsAutoConfigurationTests.java | {
"start": 8348,
"end": 8435
} | interface ____ extends Repository<Example, Long> {
long count();
}
| ExampleRepository |
java | quarkusio__quarkus | independent-projects/tools/message-writer/src/main/java/io/quarkus/devtools/messagewriter/MessageWriter.java | {
"start": 80,
"end": 1124
} | interface ____ {
static MessageWriter info() {
return new DefaultMessageWriter();
}
static MessageWriter info(PrintStream out) {
return new DefaultMessageWriter(out);
}
static MessageWriter debug() {
return new DefaultMessageWriter(true);
}
static MessageWriter debug(PrintStream out) {
return new DefaultMessageWriter(out, true);
}
default void info(String format, Object... args) {
info(String.format(format, args));
}
void info(String msg);
default void error(String format, Object... args) {
error(String.format(format, args));
}
void error(String msg);
boolean isDebugEnabled();
default void debug(String format, Object... args) {
if (!isDebugEnabled()) {
return;
}
debug(String.format(format, args));
}
void debug(String msg);
default void warn(String format, Object... args) {
warn(String.format(format, args));
}
void warn(String msg);
}
| MessageWriter |
java | quarkusio__quarkus | integration-tests/oidc-wiremock/src/test/java/io/quarkus/it/keycloak/CodeFlowAuthorizationTest.java | {
"start": 3099,
"end": 54414
} | class ____ {
@OidcWireMock
WireMockServer wireMockServer;
@BeforeAll
public static void clearCache() {
// clear token cache to make tests idempotent as we experienced failures
// on Windows when BearerTokenAuthorizationTest run before CodeFlowAuthorizationTest
RestAssured
.given()
.get("http://localhost:8081/clear-token-cache")
.then()
.statusCode(204);
}
@Test
public void testCodeFlow() throws IOException {
defineCodeFlowLogoutStub();
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = webClient.getPage("http://localhost:8081/code-flow");
HtmlForm form = page.getFormByName("form");
form.getInputByName("username").type("alice");
form.getInputByName("password").type("alice");
TextPage textPage = form.getInputByValue("login").click();
assertEquals("alice, cache size: 0", textPage.getContent());
assertNotNull(getSessionCookie(webClient, "code-flow"));
// Logout
textPage = webClient.getPage("http://localhost:8081/code-flow/logout");
assertEquals("Welcome, clientId: quarkus-web-app", textPage.getContent());
assertNull(getSessionCookie(webClient, "code-flow"));
// Clear the post logout cookie
webClient.getCookieManager().clearCookies();
}
clearCache();
}
@Test
public void testCodeFlowOpaqueAccessToken() throws IOException {
defineCodeFlowOpaqueAccessTokenStub();
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = webClient.getPage("http://localhost:8081/code-flow-opaque-access-token");
HtmlForm form = page.getFormByName("form");
form.getInputByName("username").type("alice");
form.getInputByName("password").type("alice");
TextPage textPage = form.getInputByValue("login").click();
assertEquals("alice", textPage.getContent());
try {
webClient.getPage("http://localhost:8081/code-flow-opaque-access-token/jwt-access-token");
fail("500 status error is expected");
} catch (FailingHttpStatusCodeException ex) {
assertEquals(500, ex.getStatusCode());
}
webClient.getCookieManager().clearCookies();
}
clearCache();
}
@Test
public void testCodeFlowVerifyIdAndAccessToken() throws IOException {
defineCodeFlowLogoutStub();
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = webClient.getPage("http://localhost:8081/code-flow-verify-id-and-access-tokens");
HtmlForm form = page.getFormByName("form");
form.getInputByName("username").type("alice");
form.getInputByName("password").type("alice");
TextPage textPage = form.getInputByValue("login").click();
assertEquals("access token verified: true,"
+ " id_token issuer: https://server.example.com,"
+ " access_token issuer: https://server.example.com,"
+ " id_token audience: https://id.server.example.com;quarkus-web-app,"
+ " access_token audience: https://server.example.com,"
+ " cache size: 0", textPage.getContent());
assertNotNull(getSessionCookie(webClient, "code-flow-verify-id-and-access-tokens"));
webClient.getCookieManager().clearCookies();
}
clearCache();
}
@Test
public void testCodeFlowEncryptedIdTokenJwk() throws IOException {
doTestCodeFlowEncryptedIdToken("code-flow-encrypted-id-token-jwk", KeyEncryptionAlgorithm.DIR);
}
@Test
public void testCodeFlowEncryptedIdTokenPem() throws IOException {
doTestCodeFlowEncryptedIdToken("code-flow-encrypted-id-token-pem", KeyEncryptionAlgorithm.A256GCMKW);
}
private void doTestCodeFlowEncryptedIdToken(String tenant, KeyEncryptionAlgorithm alg) throws IOException {
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = webClient.getPage("http://localhost:8081/code-flow-encrypted-id-token/" + tenant);
HtmlForm form = page.getFormByName("form");
form.getInputByName("username").type("alice");
form.getInputByName("password").type("alice");
TextPage textPage = form.getInputByValue("login").click();
assertEquals("user: alice", textPage.getContent());
Cookie sessionCookie = getSessionCookie(webClient, tenant);
assertNotNull(sessionCookie);
// All the session cookie content is encrypted
String[] sessionCookieParts = sessionCookie.getValue().split("\\|");
assertEquals(1, sessionCookieParts.length);
assertTrue(isEncryptedToken(sessionCookieParts[0], alg));
JsonObject headers = OidcUtils.decodeJwtHeaders(sessionCookieParts[0]);
assertEquals(alg.getAlgorithm(), headers.getString("alg"));
// repeat the call with the session cookie containing the encrypted id token
textPage = webClient.getPage("http://localhost:8081/code-flow-encrypted-id-token/" + tenant);
assertEquals("user: alice", textPage.getContent());
webClient.getCookieManager().clearCookies();
}
clearCache();
}
@Test
public void testCodeFlowEncryptedIdTokenDisabled() throws IOException {
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = webClient
.getPage("http://localhost:8081/code-flow-encrypted-id-token/code-flow-encrypted-id-token-disabled");
HtmlForm form = page.getFormByName("form");
form.getInputByName("username").type("alice");
form.getInputByName("password").type("alice");
try {
form.getInputByValue("login").click();
fail("ID token decryption is disabled");
} catch (FailingHttpStatusCodeException ex) {
assertEquals(401, ex.getResponse().getStatusCode());
}
webClient.getCookieManager().clearCookies();
}
clearCache();
}
private static boolean isEncryptedToken(String token, KeyEncryptionAlgorithm alg) {
int expectedNonEmptyParts = alg == KeyEncryptionAlgorithm.DIR ? 4 : 5;
return new StringTokenizer(token, ".").countTokens() == expectedNonEmptyParts;
}
@Test
public void testCodeFlowFormPostAndBackChannelLogout() throws IOException {
defineCodeFlowLogoutStub();
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = webClient.getPage("http://localhost:8081/code-flow-form-post");
HtmlForm form = page.getFormByName("form");
form.getInputByName("username").type("alice");
form.getInputByName("password").type("alice");
TextPage textPage = form.getInputByValue("login").click();
assertEquals("alice", textPage.getContent());
assertNotNull(getSessionCookie(webClient, "code-flow-form-post"));
textPage = webClient.getPage("http://localhost:8081/code-flow-form-post");
assertEquals("alice", textPage.getContent());
// Session is still active
assertNotNull(getSessionCookie(webClient, "code-flow-form-post"));
// ID token subject is `123456`
// request a back channel logout for some other subject
RestAssured.given()
.when().contentType(ContentType.URLENC)
.body("logout_token=" + OidcWiremockTestResource.getLogoutToken("789"))
.post("/back-channel-logout")
.then()
.statusCode(200);
// No logout:
textPage = webClient.getPage("http://localhost:8081/code-flow-form-post");
assertEquals("alice", textPage.getContent());
// Session is still active
assertNotNull(getSessionCookie(webClient, "code-flow-form-post"));
// request a back channel logout for the same subject
RestAssured.given()
.when().contentType(ContentType.URLENC).body("logout_token="
+ OidcWiremockTestResource.getLogoutToken("123456"))
.post("/back-channel-logout")
.then()
.statusCode(200);
// Confirm 302 is returned and the session cookie is null
webClient.getOptions().setRedirectEnabled(false);
WebResponse webResponse = webClient
.loadWebResponse(new WebRequest(URI.create("http://localhost:8081/code-flow-form-post").toURL()));
assertEquals(302, webResponse.getStatusCode());
assertNull(getSessionCookie(webClient, "code-flow-form-post"));
webClient.getCookieManager().clearCookies();
}
clearCache();
}
@Test
public void testCodeFlowFormPostAndFrontChannelLogout() throws Exception {
defineCodeFlowLogoutStub();
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = webClient.getPage("http://localhost:8081/code-flow-form-post");
HtmlForm form = page.getFormByName("form");
form.getInputByName("username").type("alice");
form.getInputByName("password").type("alice");
TextPage textPage = form.getInputByValue("login").click();
assertEquals("alice", textPage.getContent());
assertNotNull(getSessionCookie(webClient, "code-flow-form-post"));
textPage = webClient.getPage("http://localhost:8081/code-flow-form-post");
assertEquals("alice", textPage.getContent());
// Session is still active
JsonObject idTokenClaims = decryptIdToken(webClient, "code-flow-form-post");
webClient.getOptions().setRedirectEnabled(false);
// Confirm 302 is returned and the session cookie is null when the frontchannel logout URL is called
URL frontchannelUrl = URI.create("http://localhost:8081/code-flow-form-post/front-channel-logout"
+ "?sid=" + idTokenClaims.getString("sid") + "&iss="
+ OidcCommonUtils.urlEncode(idTokenClaims.getString("iss"))).toURL();
WebResponse webResponse = webClient.loadWebResponse(new WebRequest(frontchannelUrl));
assertEquals(302, webResponse.getStatusCode());
assertNull(getSessionCookie(webClient, "code-flow-form-post"));
// remove the state cookie for Quarkus not to treat the next call as an expected redirect from OIDC
webClient.getCookieManager().clearCookies();
// Confirm 302 is returned and the session cookie is null when the endpoint is called
webResponse = webClient
.loadWebResponse(new WebRequest(URI.create("http://localhost:8081/code-flow-form-post").toURL()));
assertEquals(302, webResponse.getStatusCode());
assertNull(getSessionCookie(webClient, "code-flow-form-post"));
webClient.getCookieManager().clearCookies();
}
clearCache();
}
@Test
public void testCodeFlowUserInfo() throws Exception {
defineCodeFlowAuthorizationOauth2TokenStub();
wireMockServer.resetRequests();
// No internal ID token
doTestCodeFlowUserInfo("code-flow-user-info-only", 300, false, false, 1, 1);
clearCache();
// Internal ID token, allow in memory cache = true, cacheUserInfoInIdtoken = false without having to be configured
doTestCodeFlowUserInfo("code-flow-user-info-github", 25200, false, false, 1, 1);
clearCache();
// Internal ID token, allow in memory cache = false, cacheUserInfoInIdtoken = true without having to be configured
doTestCodeFlowUserInfo("code-flow-user-info-dynamic-github", 301, true, true, 0, 1);
clearCache();
// Internal ID token, allow in memory cache = false, cacheUserInfoInIdtoken = false
doTestCodeFlowUserInfo("code-flow-user-info-github-cache-disabled", 25200, false, false, 0, 4);
clearCache();
doTestCodeFlowUserInfoDynamicGithubUpdate();
clearCache();
}
@Test
public void testCodeFlowUserInfoCachedInIdToken() throws Exception {
// Internal ID token, allow in memory cache = false, cacheUserInfoInIdtoken = true
final String refreshJwtToken = generateAlreadyExpiredRefreshToken();
defineCodeFlowUserInfoCachedInIdTokenStub(refreshJwtToken);
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = webClient.getPage("http://localhost:8081/code-flow-user-info-github-cached-in-idtoken");
HtmlForm form = page.getFormByName("form");
form.getInputByName("username").type("alice");
form.getInputByName("password").type("alice");
Cookie stateCookie = getStateCookie(webClient, "code-flow-user-info-github-cached-in-idtoken");
Date stateCookieDate = stateCookie.getExpires();
final long nowInSecs = nowInSecs();
final long sessionCookieLifespan = stateCookieDate.toInstant().getEpochSecond() - nowInSecs;
// 5 mins is default
assertTrue(sessionCookieLifespan >= 299 && sessionCookieLifespan <= 304);
TextPage textPage = form.getInputByValue("login").click();
assertEquals("alice:alice:alice, cache size: 0, TenantConfigResolver: false, refresh_token:refresh1234",
textPage.getContent());
assertNull(getStateCookie(webClient, "code-flow-user-info-github-cached-in-idtoken"));
JsonObject idTokenClaims = decryptIdToken(webClient, "code-flow-user-info-github-cached-in-idtoken");
assertNotNull(idTokenClaims.getJsonObject(OidcUtils.USER_INFO_ATTRIBUTE));
long issuedAt = idTokenClaims.getLong("iat");
long expiresAt = idTokenClaims.getLong("exp");
assertEquals(299, expiresAt - issuedAt);
Cookie sessionCookie = getSessionCookie(webClient, "code-flow-user-info-github-cached-in-idtoken");
Date date = sessionCookie.getExpires();
assertTrue(date.toInstant().getEpochSecond() - issuedAt >= 299 + 300);
// This test enables the token refresh, in this case the cookie age is extended by additional 5 mins
// to minimize the risk of the browser losing immediately after it has expired, for this cookie
// be returned to Quarkus, analyzed and refreshed
assertTrue(date.toInstant().getEpochSecond() - issuedAt <= 299 + 300 + 3);
assertEquals(299, decryptAccessTokenExpiryTime(webClient, "code-flow-user-info-github-cached-in-idtoken"));
// This is the initial call to the token endpoint where the code was exchanged for tokens
wireMockServer.verify(1,
postRequestedFor(urlPathMatching("/auth/realms/quarkus/access_token_refreshed")));
wireMockServer.resetRequests();
// refresh: refresh token in JWT format
Thread.sleep(3000);
textPage = webClient.getPage("http://localhost:8081/code-flow-user-info-github-cached-in-idtoken");
assertEquals("alice:alice:bob, cache size: 0, TenantConfigResolver: false, refresh_token:" + refreshJwtToken,
textPage.getContent());
idTokenClaims = decryptIdToken(webClient, "code-flow-user-info-github-cached-in-idtoken");
assertNotNull(idTokenClaims.getJsonObject(OidcUtils.USER_INFO_ATTRIBUTE));
issuedAt = idTokenClaims.getLong("iat");
expiresAt = idTokenClaims.getLong("exp");
assertEquals(299, expiresAt - issuedAt);
sessionCookie = getSessionCookie(webClient, "code-flow-user-info-github-cached-in-idtoken");
date = sessionCookie.getExpires();
assertTrue(date.toInstant().getEpochSecond() - issuedAt >= 299 + 300);
assertTrue(date.toInstant().getEpochSecond() - issuedAt <= 299 + 300 + 3);
assertEquals(305, decryptAccessTokenExpiryTime(webClient, "code-flow-user-info-github-cached-in-idtoken"));
// access token must've been refreshed
wireMockServer.verify(1,
postRequestedFor(urlPathMatching("/auth/realms/quarkus/access_token_refreshed")));
wireMockServer.resetRequests();
Thread.sleep(3000);
// Refresh token is available but it is expired, so no token endpoint call is expected
assertTrue((System.currentTimeMillis() / 1000) > OidcCommonUtils.decodeJwtContent(refreshJwtToken)
.getLong(Claims.exp.name()));
webClient.getOptions().setRedirectEnabled(false);
WebResponse webResponse = webClient
.loadWebResponse(new WebRequest(
URI.create("http://localhost:8081/code-flow-user-info-github-cached-in-idtoken").toURL()));
assertEquals(302, webResponse.getStatusCode());
// no another token endpoint call is made:
wireMockServer.verify(0,
postRequestedFor(urlPathMatching("/auth/realms/quarkus/access_token_refreshed")));
wireMockServer.resetRequests();
webClient.getCookieManager().clearCookies();
}
// Now send a bearer access token with the inline chain
String bearerAccessToken = TestUtils.createTokenWithInlinedCertChain("alice-certificate");
RestAssured.given().auth().oauth2(bearerAccessToken)
.when().get("/code-flow-user-info-github-cached-in-idtoken")
.then()
.statusCode(200)
.body(Matchers.equalTo("alice:alice:alice-certificate, cache size: 0, TenantConfigResolver: false"));
clearCache();
checkSignedUserInfoRecordInLog();
}
private void checkSignedUserInfoRecordInLog() {
final Path logDirectory = Paths.get(".", "target");
given().await().pollInterval(100, TimeUnit.MILLISECONDS)
.atMost(10, TimeUnit.SECONDS)
.untilAsserted(new ThrowingRunnable() {
@Override
public void run() throws Throwable {
Path accessLogFilePath = logDirectory.resolve("quarkus.log");
boolean fileExists = Files.exists(accessLogFilePath);
if (!fileExists) {
accessLogFilePath = logDirectory.resolve("target/quarkus.log");
fileExists = Files.exists(accessLogFilePath);
}
Assertions.assertTrue(Files.exists(accessLogFilePath),
"quarkus log file " + accessLogFilePath + " is missing");
boolean lineConfirmingVerificationDetected = false;
boolean signedUserInfoResponseFilterMessageDetected = false;
boolean codeFlowCompletedResponseFilterMessageDetected = false;
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(accessLogFilePath)),
StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("Verifying the signed UserInfo with the local JWK keys: ey")) {
lineConfirmingVerificationDetected = true;
} else if (line.contains("Response contains signed UserInfo")) {
signedUserInfoResponseFilterMessageDetected = true;
} else if (line.contains(
"Authorization code completed for tenant 'code-flow-user-info-github-cached-in-idtoken' in an instant: true")) {
codeFlowCompletedResponseFilterMessageDetected = true;
}
if (lineConfirmingVerificationDetected
&& signedUserInfoResponseFilterMessageDetected
&& codeFlowCompletedResponseFilterMessageDetected) {
break;
}
}
}
assertTrue(lineConfirmingVerificationDetected,
"Log file must contain a record confirming that signed UserInfo is verified");
assertTrue(signedUserInfoResponseFilterMessageDetected,
"Log file must contain a record confirming that signed UserInfo is returned");
assertTrue(codeFlowCompletedResponseFilterMessageDetected,
"Log file must contain a record confirming that the code flow is completed");
}
});
}
@Test
public void testCodeFlowTokenIntrospectionActiveRefresh() throws Exception {
// This stub does not return an access token expires_in property
defineCodeFlowTokenIntrospectionStub();
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = webClient.getPage("http://localhost:8081/code-flow-token-introspection");
HtmlForm form = page.getFormByName("form");
form.getInputByName("username").type("alice");
form.getInputByName("password").type("alice");
TextPage textPage = form.getInputByValue("login").click();
assertEquals("alice:alice", textPage.getContent());
textPage = webClient.getPage("http://localhost:8081/code-flow-token-introspection");
assertEquals("alice:alice", textPage.getContent());
// Refresh
// The internal ID token lifespan is 5 mins
// Configured refresh token skew is 298 secs = 5 mins - 2 secs
// Therefore, after waiting for 3 secs, an active refresh is happening
Thread.sleep(3000);
textPage = webClient.getPage("http://localhost:8081/code-flow-token-introspection");
assertEquals("admin:admin", textPage.getContent());
webClient.getCookieManager().clearCookies();
}
clearCache();
}
@Test
public void testCodeFlowTokenIntrospectionActiveRefresh_noEncryption() throws Exception {
// exactly as testCodeFlowTokenIntrospectionActiveRefresh but with
// quarkus.oidc.token-state-manager.split-tokens=true
// quarkus.oidc.token-state-manager.encryption-required=false
// to assure that cookie is valid when there are multiple scopes
// This stub does not return an access token expires_in property
defineCodeFlowTokenIntrospectionStub();
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = webClient.getPage("http://localhost:8081/code-flow-token-introspection-no-encryption");
HtmlForm form = page.getFormByName("form");
form.getInputByName("username").type("alice");
form.getInputByName("password").type("alice");
TextPage textPage = form.getInputByValue("login").click();
assertEquals("alice:alice", textPage.getContent());
textPage = webClient.getPage("http://localhost:8081/code-flow-token-introspection-no-encryption");
assertEquals("alice:alice", textPage.getContent());
// Refresh
// The internal ID token lifespan is 5 mins
// Configured refresh token skew is 298 secs = 5 mins - 2 secs
// Therefore, after waiting for 3 secs, an active refresh is happening
Thread.sleep(3000);
textPage = webClient.getPage("http://localhost:8081/code-flow-token-introspection-no-encryption");
assertEquals("admin:admin", textPage.getContent());
webClient.getCookieManager().clearCookies();
}
clearCache();
}
@Test
public void testCodeFlowTokenIntrospectionExpiresInRefresh() throws Exception {
// This stub does return an access token expires_in property
defineCodeFlowTokenIntrospectionExpiresInStub();
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = webClient.getPage("http://localhost:8081/code-flow-token-introspection-expires-in");
HtmlForm form = page.getFormByName("form");
form.getInputByName("username").type("alice");
form.getInputByName("password").type("alice");
TextPage textPage = form.getInputByValue("login").click();
assertEquals("alice", textPage.getContent());
// Refresh the expired token
// The internal ID token lifespan is 5 mins, refresh token skew is not configured,
// code flow access token expires in 3 seconds from now. Therefore, after waiting for 5 secs
// the refresh is triggered because it is allowed in the config and token expires_in property is returned.
Thread.sleep(5000);
textPage = webClient.getPage("http://localhost:8081/code-flow-token-introspection-expires-in");
assertEquals("bob", textPage.getContent());
webClient.getCookieManager().clearCookies();
}
clearCache();
}
private void doTestCodeFlowUserInfo(String tenantId, long internalIdTokenLifetime, boolean cacheUserInfoInIdToken,
boolean tenantConfigResolver, int inMemoryCacheSize, int userInfoRequests) throws Exception {
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(true);
wireMockServer.verify(0, getRequestedFor(urlPathMatching("/auth/realms/quarkus/protocol/openid-connect/userinfo")));
HtmlPage page = webClient.getPage("http://localhost:8081/" + tenantId);
HtmlForm form = page.getFormByName("form");
form.getInputByName("username").type("alice");
form.getInputByName("password").type("alice");
TextPage textPage = form.getInputByValue("login").click();
assertEquals(
"alice:alice:alice, cache size: " + inMemoryCacheSize + ", TenantConfigResolver: " + tenantConfigResolver,
textPage.getContent());
textPage = webClient.getPage("http://localhost:8081/" + tenantId);
assertEquals(
"alice:alice:alice, cache size: " + inMemoryCacheSize + ", TenantConfigResolver: " + tenantConfigResolver,
textPage.getContent());
textPage = webClient.getPage("http://localhost:8081/" + tenantId);
assertEquals(
"alice:alice:alice, cache size: " + inMemoryCacheSize + ", TenantConfigResolver: " + tenantConfigResolver,
textPage.getContent());
wireMockServer.verify(userInfoRequests,
getRequestedFor(urlPathMatching("/auth/realms/quarkus/protocol/openid-connect/userinfo")));
wireMockServer.resetRequests();
JsonObject idTokenClaims = decryptIdToken(webClient, tenantId);
assertEquals(cacheUserInfoInIdToken, idTokenClaims.containsKey(OidcUtils.USER_INFO_ATTRIBUTE));
long issuedAt = idTokenClaims.getLong("iat");
long expiresAt = idTokenClaims.getLong("exp");
assertEquals(internalIdTokenLifetime, expiresAt - issuedAt);
Cookie sessionCookie = getSessionCookie(webClient, tenantId);
Date date = sessionCookie.getExpires();
assertTrue(date.toInstant().getEpochSecond() - issuedAt >= internalIdTokenLifetime);
assertTrue(date.toInstant().getEpochSecond() - issuedAt <= internalIdTokenLifetime + 3);
webClient.getCookieManager().clearCookies();
wireMockServer.resetRequests();
}
}
private void doTestCodeFlowUserInfoDynamicGithubUpdate() throws Exception {
try (final WebClient webClient = createWebClient()) {
HtmlPage htmlPage = webClient.getPage("http://localhost:8081/code-flow-user-info-dynamic-github");
HtmlForm htmlForm = htmlPage.getFormByName("form");
htmlForm.getInputByName("username").type("alice");
htmlForm.getInputByName("password").type("alice");
TextPage textPage = htmlForm.getInputByValue("login").click();
assertEquals("alice:alice:alice, cache size: 0, TenantConfigResolver: true", textPage.getContent());
textPage = webClient.getPage("http://localhost:8081/code-flow-user-info-dynamic-github");
assertEquals("alice:alice:alice, cache size: 0, TenantConfigResolver: true", textPage.getContent());
// Dynamic `code-flow-user-info-dynamic-github` tenant, resource is `code-flow-user-info-dynamic-github`
checkResourceMetadata("code-flow-user-info-dynamic-github", "quarkus");
textPage = webClient.getPage("http://localhost:8081/code-flow-user-info-dynamic-github?update=true");
assertEquals("alice@somecompany.com:alice:alice, cache size: 0, TenantConfigResolver: true", textPage.getContent());
// Dynamic `code-flow-user-info-dynamic-github` tenant, resource is `github`
checkResourceMetadata("github", "quarkus");
htmlPage = webClient.getPage("http://localhost:8081/code-flow-user-info-dynamic-github?reconnect=true");
htmlForm = htmlPage.getFormByName("form");
htmlForm.getInputByName("username").type("alice");
htmlForm.getInputByName("password").type("alice");
textPage = htmlForm.getInputByValue("login").click();
assertEquals("alice@anothercompany.com:alice:alice, cache size: 0, TenantConfigResolver: true",
textPage.getContent());
webClient.getCookieManager().clearCookies();
}
}
private static JsonObject decryptIdToken(WebClient webClient, String tenantId) throws Exception {
Cookie sessionCookie = getSessionCookie(webClient, tenantId);
assertNotNull(sessionCookie);
SecretKey key = getSessionCookieDecryptionKey(webClient, tenantId);
String decryptedSessionCookie = OidcUtils.decryptString(sessionCookie.getValue(), key);
String encodedIdToken = decryptedSessionCookie.split("\\|")[0];
return OidcCommonUtils.decodeJwtContent(encodedIdToken);
}
private static int decryptAccessTokenExpiryTime(WebClient webClient, String tenantId) throws Exception {
Cookie sessionCookie = getSessionCookie(webClient, tenantId);
assertNotNull(sessionCookie);
SecretKey key = getSessionCookieDecryptionKey(webClient, tenantId);
String decryptedSessionCookie = OidcUtils.decryptString(sessionCookie.getValue(), key);
// idtoken|accesstoken|accesstoken-exp-in-time|...
return Integer.valueOf(decryptedSessionCookie.split("\\|")[2]);
}
private static SecretKey getSessionCookieDecryptionKey(WebClient webClient, String tenantId) throws Exception {
if ("code-flow-user-info-github".equals(tenantId)) {
PrivateKey privateKey = KeyUtils.tryAsPemSigningPrivateKey(
"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCyXwKqKL/"
+ "hQWDkurdHyRn/9aZqmrgpCfiT5+gQ7KZ9RvDjgTqkJT6IIrRFvIpeBMwS"
+ "sw3dkUPGmgN1J4QOhLaR2VEXhc20UbxFbr6HXAskZGPuCL1tzRWDkLNMZaEO8jqhPbcq1Ro4GMhaSdm0sBHmcQnu8wAOrdAowdzGh"
+ "/HUaaYBDY0OZVAm9N8zzBXTahna9frJCMHq3e9szIiv6HYZTy1672/+hR/0D1HY+bqpQtJnzSrKjkFeXDAbYPgewYLEJ2Dk+oo6L"
+ "1I6S+UTrl4FRHw1fHAd2i75JD+vL/8w/AtKkej0CCBUSZJiV+KDJWjnDUVRWjq5hQb9pu4qEJKhAgMBAAECggEAJvBs4X7B3MfsAi"
+ "LszgQN4/3ZlZ4vI+5kUM2osMEo22J4RgI5Lgpfa1LALhUp07qSXmauWTdUJ3AJ3zKANrcsMAzUEiGItZu+UR4LA/vJBunPkvBfgi/"
+ "qSW12ZvAsx9mDiR2y9evNrH9khalnmHVzgu4ccAimc43oSm1/5+tXlLoZ1QK/FohxBxAshtuDHGs8yKUL0jpv7dOrjhCj2ibmPYe6A"
+ "Uk9F61sVWO0/i0Q8UAOcYT3L5nCS5WnLhdCdYpIJJ7xl2PrVE/BAD+JEG5uCOYfVeYh+iCZVfpX17ryfNNUaBtyxKEGVtHbje3mO86"
+ "mYN3noaS0w/zpUjBPgV+KEQKBgQDsp6VTmDIqHFTp2cC2yrDMxRznif92EGv7ccJDZtbTC37mAuf2J7x5b6AiE1EfxEXyGYzSk99sC"
+ "ns+GbL1EHABUt5pimDCl33b6XvuccQNpnJ0MfM5eRX9Ogyt/OKdDRnQsvrTPNCWOyJjvG01HQM4mfxaBBnxnvl5meH2pyG/ZQKBgQD"
+ "A87DnyqEFhTDLX5c1TtwHSRj2xeTPGKG0GyxOJXcxR8nhtY9ee0kyLZ14RytnOxKarCFgYXeG4IoGEc/I42WbA4sq88tZcbe4IJkdX"
+ "0WLMqOTdMrdx9hMU1ytKVUglUJZBVm7FaTQjA+ArMwqkXAA5HBMtArUsfJKUt3l0hMIjQKBgQDS1vmAZJQs2Fj+jzYWpLaneOWrk1K"
+ "5yR+rQUql6jVyiUdhfS1ULUrJlh3Avh0EhEUc0I6Z/YyMITpztUmu9BoV09K7jMFwHK/RAU+cvFbDIovN4cKkbbCdjt5FFIyBB278d"
+ "LjrAb+EWOLmoLVbIKICB47AU+8ZSV1SbTrYGUcD0QKBgQCAliZv4na6sg9ZiUPAr+QsKserNSiN5zFkULOPBKLRQbFFbPS1l12pRgL"
+ "qNCu1qQV19H5tt6arSRpSfy5FB14gFxV4s23yFrnDyF2h2GsFH+MpEq1bbaI1A10AvUnQ5AeKQemRpxPmM2DldMK/H5tPzO0WAOoy4"
+ "r/ATkc4sG4kxQKBgBL9neT0TmJtxlYGzjNcjdJXs3Q91+nZt3DRMGT9s0917SuP77+FdJYocDiH1rVa9sGG8rkh1jTdqliAxDXwIm5I"
+ "GS/0OBnkaN1nnGDk5yTiYxOutC5NSj7ecI5Erud8swW6iGqgz2ioFpGxxIYqRlgTv/6mVt41KALfKrYIkVLw",
SignatureAlgorithm.RS256);
return OidcUtils.createSecretKeyFromDigest(privateKey.getEncoded());
} else {
return OidcUtils.createSecretKeyFromDigest(
"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"
.getBytes(StandardCharsets.UTF_8));
}
}
private WebClient createWebClient() {
WebClient webClient = new WebClient();
webClient.setCssErrorHandler(new SilentCssErrorHandler());
return webClient;
}
private void defineCodeFlowAuthorizationOauth2TokenStub() {
wireMockServer
.stubFor(WireMock.post("/auth/realms/quarkus/access_token")
.withHeader("X-Custom", equalTo("XCustomHeaderValue"))
.withBasicAuth("quarkus-web-app",
"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow")
.withRequestBody(containing("extra-param=extra-param-value"))
.withRequestBody(containing("authorization_code"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"access_token\": \""
+ OidcWiremockTestResource.getAccessToken("alice", Set.of()) + "\","
+ " \"refresh_token\": \"refresh1234\""
+ "}")));
wireMockServer
.stubFor(WireMock.post("/auth/realms/quarkus/access_token")
.withHeader("X-Custom", equalTo("XCustomHeaderValue"))
.withRequestBody(containing("extra-param=extra-param-value"))
.withRequestBody(containing("authorization_code"))
.withRequestBody(
containing(
"client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer"))
.withRequestBody(containing("client_assertion=ey"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"access_token\": \""
+ OidcWiremockTestResource.getAccessToken("alice", Set.of()) + "\","
+ " \"refresh_token\": \"refresh1234\""
+ "}")));
wireMockServer
.stubFor(WireMock.post("/auth/realms/quarkus/access_token")
.withBasicAuth("quarkus-web-app",
"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow")
.withRequestBody(containing("refresh_token=refresh1234"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"access_token\": \""
+ OidcWiremockTestResource.getAccessToken("bob", Set.of()) + "\""
+ "}")));
wireMockServer.stubFor(
get(urlEqualTo("/auth/realms/github/.well-known/openid-configuration"))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"authorization_endpoint\": \"" + wireMockServer.baseUrl()
+ "/auth/realms/quarkus\"," +
" \"jwks_uri\": \"" + wireMockServer.baseUrl()
+ "/auth/realms/quarkus/protocol/openid-connect/certs\",\n" +
" \"token_endpoint\": \"" + wireMockServer.baseUrl()
+ "/auth/realms/quarkus/token\"," +
" \"userinfo_endpoint\": \"" + wireMockServer.baseUrl()
+ "/auth/realms/github/protocol/openid-connect/userinfo\""
+ "}")));
wireMockServer.stubFor(
get(urlEqualTo("/auth/realms/github/protocol/openid-connect/userinfo"))
.withHeader("Authorization", containing("Bearer ey"))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n"
+ "\"preferred_username\": \"alice\","
+ "\"personal-email\": \"alice@anothercompany.com\""
+ "}")));
}
private void defineCodeFlowUserInfoCachedInIdTokenStub(String expiredRefreshToken) {
wireMockServer
.stubFor(WireMock.post(urlPathMatching("/auth/realms/quarkus/access_token_refreshed"))
.withHeader("X-Custom", matching("XCustomHeaderValue"))
.withQueryParam("extra-param", equalTo("extra-param-value"))
.withQueryParam("grant_type", equalTo("authorization_code"))
.withQueryParam("client_id", equalTo("quarkus-web-app"))
.withQueryParam("client_secret", equalTo(
"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"))
.withRequestBody(notContaining("extra-param=extra-param-value"))
.withRequestBody(notContaining("authorization_code"))
.withRequestBody(notContaining("client_id=quarkus-web-app"))
.withRequestBody(notContaining(
"client_secret=AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"access_token\": \""
+ OidcWiremockTestResource.getAccessToken("alice", Set.of()) + "\","
+ "\"expires_in\": 299,"
+ " \"refresh_token\": \"refresh1234\""
+ "}")));
wireMockServer
.stubFor(WireMock.post(urlPathMatching("/auth/realms/quarkus/access_token_refreshed"))
.withQueryParam("refresh_token", equalTo("refresh1234"))
.withQueryParam("client_id", equalTo("quarkus-web-app"))
.withQueryParam("client_secret", equalTo(
"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"))
.withRequestBody(notContaining("refresh_token=refresh1234"))
.withRequestBody(notContaining("client_id=quarkus-web-app"))
.withRequestBody(notContaining(
"client_secret=AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"access_token\": \""
+ OidcWiremockTestResource.getAccessToken("bob", Set.of()) + "\","
+ " \"expires_in\": 305,"
+ " \"refresh_token\": \""
+ expiredRefreshToken + "\""
+ "}")));
wireMockServer.stubFor(
get(urlEqualTo("/auth/realms/quarkus/protocol/openid-connect/signeduserinfo"))
.withHeader("Authorization", containing("Bearer ey"))
.willReturn(aResponse()
.withHeader("Content-Type", " application/jwt ; charset=UTF-8")
.withBody(
Jwt.preferredUserName("alice")
.issuer("https://server.example.com")
.audience("quarkus-web-app")
.jws()
.keyId("1").sign("privateKey.jwk"))));
}
private void defineCodeFlowOpaqueAccessTokenStub() {
wireMockServer
.stubFor(WireMock.post(urlPathMatching("/auth/realms/quarkus/opaque-access-token"))
.withRequestBody(containing("&opaque_token_param=opaque_token_value"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"access_token\": \"alice\","
+ " \"scope\": \"laptop,phone\","
+ "\"expires_in\": 299}")));
}
private String generateAlreadyExpiredRefreshToken() {
return Jwt.claims().expiresIn(0).signWithSecret("0123456789ABCDEF0123456789ABCDEF");
}
private void defineCodeFlowTokenIntrospectionStub() {
wireMockServer
.stubFor(WireMock.post("/auth/realms/quarkus/access_token")
.withHeader("X-Custom", matching("XTokenIntrospection"))
.withRequestBody(containing("authorization_code"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"access_token\": \"alice\","
+ " \"scope\": \"openid profile email\","
+ " \"refresh_token\": \"refresh5678\""
+ "}")));
wireMockServer
.stubFor(WireMock.post("/auth/realms/quarkus/access_token")
.withRequestBody(containing("refresh_token=refresh5678"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"access_token\": \"admin\","
+ " \"scope\": \"openid profile email\""
+ "}")));
}
private static long nowInSecs() {
return Instant.now().getEpochSecond();
}
private void defineCodeFlowTokenIntrospectionExpiresInStub() {
wireMockServer
.stubFor(WireMock.post("/auth/realms/quarkus/access_token_expires_in")
.withRequestBody(containing("authorization_code"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"id_token\": \"" +
OidcWiremockTestResource.generateJwtToken("alice", Set.of(), "sub", "ID",
Set.of("quarkus-web-app"))
+ "\","
+ " \"access_token\": \"alice\","
+ " \"expires_in\":" + 3 + ","
+ " \"refresh_token\": \"refresh.expires.in\""
+ "}")));
wireMockServer
.stubFor(WireMock.post("/auth/realms/quarkus/introspect_expires_in")
.withRequestBody(containing("token=alice"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n"
+ " \"username\": \"alice\","
+ " \"exp\":" + (nowInSecs() + 3) + ","
+ " \"active\": true"
+ "}")));
wireMockServer
.stubFor(WireMock.post("/auth/realms/quarkus/introspect_expires_in")
.withRequestBody(containing("token=bob"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n"
+ " \"username\": \"bob\","
+ " \"active\": true"
+ "}")));
wireMockServer
.stubFor(WireMock.post("/auth/realms/quarkus/access_token_expires_in")
.withRequestBody(containing("refresh_token=refresh.expires.in"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"access_token\": \"bob\","
+ " \"id_token\": \"" +
OidcWiremockTestResource.generateJwtToken("bob", Set.of(), "sub", "ID",
Set.of("quarkus-web-app"))
+ "\""
+ "}")));
}
private void defineCodeFlowLogoutStub() {
wireMockServer.stubFor(
get(urlPathMatching("/auth/realms/quarkus/protocol/openid-connect/end-session"))
.willReturn(aResponse()
.withHeader("Location",
"{{request.query.returnTo}}?clientId={{request.query.client_id}}")
.withStatus(302)
.withTransformers("response-template")));
}
private static Cookie getSessionCookie(WebClient webClient, String tenantId) {
return webClient.getCookieManager().getCookie("q_session" + (tenantId == null ? "" : "_" + tenantId));
}
private static Cookie getStateCookie(WebClient webClient, String tenantId) {
return webClient.getCookieManager().getCookies().stream()
.filter(c -> c.getName().startsWith("q_auth" + (tenantId == null ? "" : "_" + tenantId))).findFirst()
.orElse(null);
}
private static void checkResourceMetadata(String resource, String realm) {
Response metadataResponse = RestAssured.when()
.get("http://localhost:8081" + OidcConstants.RESOURCE_METADATA_WELL_KNOWN_PATH
+ (resource == null ? "" : "/" + resource));
JsonObject jsonMetadata = new JsonObject(metadataResponse.asString());
assertEquals("https://localhost:8081" + (resource == null ? "" : "/" + resource),
jsonMetadata.getString(OidcConstants.RESOURCE_METADATA_RESOURCE));
JsonArray jsonAuthorizationServers = jsonMetadata.getJsonArray(OidcConstants.RESOURCE_METADATA_AUTHORIZATION_SERVERS);
assertEquals(1, jsonAuthorizationServers.size());
String authorizationServer = jsonAuthorizationServers.getString(0);
assertTrue(authorizationServer.startsWith("http://localhost:"));
assertTrue(authorizationServer.endsWith("/realms/" + realm));
}
}
| CodeFlowAuthorizationTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/orderby/IdClassAndOrderByTest.java | {
"start": 1246,
"end": 1351
} | class ____ {
public static final String COMPANY_NAME = "Foo Company";
public static | IdClassAndOrderByTest |
java | grpc__grpc-java | core/src/test/java/io/grpc/internal/PickFirstLeafLoadBalancerTest.java | {
"start": 147242,
"end": 148399
} | class ____ extends Subchannel {
private final Attributes attributes;
private List<EquivalentAddressGroup> eags;
private SubchannelStateListener listener;
@Keep
public FakeSubchannel(List<EquivalentAddressGroup> eags, Attributes attributes) {
this.eags = Collections.unmodifiableList(eags);
this.attributes = attributes;
}
@Override
public List<EquivalentAddressGroup> getAllAddresses() {
return eags;
}
@Override
public Attributes getAttributes() {
return attributes;
}
@Override
public void start(SubchannelStateListener listener) {
this.listener = checkNotNull(listener, "listener");
}
@Override
public void updateAddresses(List<EquivalentAddressGroup> addrs) {
this.eags = Collections.unmodifiableList(addrs);
}
@Override
public void shutdown() {
listener.onSubchannelState(ConnectivityStateInfo.forNonError(SHUTDOWN));
}
@Override
public void requestConnection() {
}
@Override
public String toString() {
return "FakeSubchannel@" + hashCode() + "(" + eags + ")";
}
}
private | FakeSubchannel |
java | quarkusio__quarkus | extensions/scheduler/runtime/src/main/java/io/quarkus/scheduler/runtime/CompositeScheduler.java | {
"start": 3543,
"end": 6098
} | class ____ extends AbstractJobDefinition<CompositeJobDefinition> {
public CompositeJobDefinition(String identity) {
super(identity);
}
@Override
public CompositeJobDefinition setExecuteWith(String implementation) {
Objects.requireNonNull(implementation);
if (!Scheduled.AUTO.equals(implementation)) {
if (schedulers.stream().map(Scheduler::implementation).noneMatch(implementation::equals)) {
throw new IllegalArgumentException("Scheduler implementation not available: " + implementation);
}
}
return super.setExecuteWith(implementation);
}
@Override
public Trigger schedule() {
String impl = implementation;
if (Scheduled.AUTO.equals(impl)) {
impl = schedulerContext.autoImplementation();
}
for (Scheduler scheduler : schedulers) {
if (scheduler.implementation().equals(impl)) {
return copy(scheduler.newJob(identity)).schedule();
}
}
throw new IllegalStateException("Matching scheduler implementation not found: " + implementation);
}
private JobDefinition<?> copy(JobDefinition<?> to) {
to.setCron(cron);
to.setInterval(every);
to.setDelayed(delayed);
to.setOverdueGracePeriod(overdueGracePeriod);
to.setConcurrentExecution(concurrentExecution);
to.setTimeZone(timeZone);
to.setExecuteWith(implementation);
if (skipPredicateClass != null) {
to.setSkipPredicate(skipPredicateClass);
} else if (skipPredicate != null) {
to.setSkipPredicate(skipPredicate);
}
if (taskClass != null) {
if (runOnVirtualThread) {
to.setTask(taskClass, runOnVirtualThread);
} else {
to.setTask(taskClass);
}
} else if (task != null) {
if (runOnVirtualThread) {
to.setTask(task, runOnVirtualThread);
} else {
to.setTask(task);
}
}
if (asyncTaskClass != null) {
to.setAsyncTask(asyncTaskClass);
} else if (asyncTask != null) {
to.setAsyncTask(asyncTask);
}
return to;
}
}
}
| CompositeJobDefinition |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/cache/SerializedCacheTest.java | {
"start": 2525,
"end": 3042
} | class ____ {
int x;
public CachingObjectWithoutSerializable(int x) {
this.x = x;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CachingObjectWithoutSerializable obj = (CachingObjectWithoutSerializable) o;
return x == obj.x;
}
@Override
public int hashCode() {
return Objects.hash(x);
}
}
}
| CachingObjectWithoutSerializable |
java | elastic__elasticsearch | modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/Whitelist.java | {
"start": 1652,
"end": 2627
} | class ____. */
public final List<WhitelistClassBinding> whitelistClassBindings;
/** The {@link List} of all the whitelisted Painless instance bindings. */
public final List<WhitelistInstanceBinding> whitelistInstanceBindings;
/** Standard constructor. All values must be not {@code null}. */
public Whitelist(
ClassLoader classLoader,
List<WhitelistClass> whitelistClasses,
List<WhitelistMethod> whitelistImportedMethods,
List<WhitelistClassBinding> whitelistClassBindings,
List<WhitelistInstanceBinding> whitelistInstanceBindings
) {
this.classLoader = Objects.requireNonNull(classLoader);
this.whitelistClasses = List.copyOf(whitelistClasses);
this.whitelistImportedMethods = List.copyOf(whitelistImportedMethods);
this.whitelistClassBindings = List.copyOf(whitelistClassBindings);
this.whitelistInstanceBindings = List.copyOf(whitelistInstanceBindings);
}
}
| bindings |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/fielddata/ScriptDocValuesGeoPointsTests.java | {
"start": 886,
"end": 6859
} | class ____ extends ESTestCase {
private static MultiGeoPointValues wrap(GeoPoint[][] points) {
return new MultiGeoPointValues(new SortedNumericLongValues() {
GeoPoint[] current;
int i;
@Override
public long nextValue() {
return current[i++].getEncoded();
}
@Override
public int docValueCount() {
return current.length;
}
@Override
public boolean advanceExact(int docId) throws IOException {
if (docId < points.length) {
current = points[docId];
} else {
current = new GeoPoint[0];
}
i = 0;
return current.length > 0;
}
});
}
private static double randomLat() {
return randomDouble() * 180 - 90;
}
private static double randomLon() {
return randomDouble() * 360 - 180;
}
public void testGeoGetLatLon() throws IOException {
final double lat1 = quantizeLat(randomLat());
final double lat2 = quantizeLat(randomLat());
final double lon1 = quantizeLon(randomLon());
final double lon2 = quantizeLon(randomLon());
GeoPoint[][] points = { { new GeoPoint(lat1, lon1), new GeoPoint(lat2, lon2) } };
final MultiGeoPointValues values = wrap(points);
final ScriptDocValues.GeoPoints script = (GeoPoints) new GeoPointDocValuesField(values, "test").toScriptDocValues();
script.getSupplier().setNextDocId(1);
assertEquals(true, script.isEmpty());
script.getSupplier().setNextDocId(0);
assertEquals(false, script.isEmpty());
assertEquals(new GeoPoint(lat1, lon1), script.getValue());
assertEquals(lat1, script.getLat(), 0);
assertEquals(lon1, script.getLon(), 0);
assertTrue(Arrays.equals(new double[] { lat1, lat2 }, script.getLats()));
assertTrue(Arrays.equals(new double[] { lon1, lon2 }, script.getLons()));
}
public void testGeoDistance() throws IOException {
final double lat = randomLat();
final double lon = randomLon();
GeoPoint[][] points = { { new GeoPoint(lat, lon) } };
final MultiGeoPointValues values = wrap(points);
final ScriptDocValues.GeoPoints script = (GeoPoints) new GeoPointDocValuesField(values, "test").toScriptDocValues();
script.getSupplier().setNextDocId(0);
GeoPoint[][] points2 = { new GeoPoint[0] };
final ScriptDocValues.GeoPoints emptyScript = (GeoPoints) new GeoPointDocValuesField(wrap(points2), "test").toScriptDocValues();
emptyScript.getSupplier().setNextDocId(0);
final double otherLat = randomLat();
final double otherLon = randomLon();
assertEquals(GeoUtils.arcDistance(lat, lon, otherLat, otherLon) / 1000d, script.arcDistance(otherLat, otherLon) / 1000d, 0.01);
assertEquals(
GeoUtils.arcDistance(lat, lon, otherLat, otherLon) / 1000d,
script.arcDistanceWithDefault(otherLat, otherLon, 42) / 1000d,
0.01
);
assertEquals(42, emptyScript.arcDistanceWithDefault(otherLat, otherLon, 42), 0);
assertEquals(GeoUtils.planeDistance(lat, lon, otherLat, otherLon) / 1000d, script.planeDistance(otherLat, otherLon) / 1000d, 0.01);
assertEquals(
GeoUtils.planeDistance(lat, lon, otherLat, otherLon) / 1000d,
script.planeDistanceWithDefault(otherLat, otherLon, 42) / 1000d,
0.01
);
assertEquals(42, emptyScript.planeDistanceWithDefault(otherLat, otherLon, 42), 0);
}
public void testMissingValues() throws IOException {
GeoPoint[][] points = new GeoPoint[between(3, 10)][];
for (int d = 0; d < points.length; d++) {
points[d] = new GeoPoint[randomBoolean() ? 0 : between(1, 10)];
for (int i = 0; i < points[d].length; i++) {
points[d][i] = new GeoPoint(quantizeLat(randomLat()), quantizeLon(randomLon()));
}
}
final ScriptDocValues.GeoPoints geoPoints = (GeoPoints) new GeoPointDocValuesField(wrap(points), "test").toScriptDocValues();
for (int d = 0; d < points.length; d++) {
geoPoints.getSupplier().setNextDocId(d);
if (points[d].length > 0) {
assertEquals(points[d][0], geoPoints.getValue());
Exception e = expectThrows(IndexOutOfBoundsException.class, () -> geoPoints.get(geoPoints.size()));
assertEquals("A document doesn't have a value for a field at position [" + geoPoints.size() + "]!", e.getMessage());
} else {
Exception e = expectThrows(IllegalStateException.class, () -> geoPoints.getValue());
assertEquals(
"A document doesn't have a value for a field! "
+ "Use doc[<field>].size()==0 to check if a document is missing a field!",
e.getMessage()
);
e = expectThrows(IllegalStateException.class, () -> geoPoints.get(0));
assertEquals(
"A document doesn't have a value for a field! "
+ "Use doc[<field>].size()==0 to check if a document is missing a field!",
e.getMessage()
);
}
assertEquals(points[d].length, geoPoints.size());
for (int i = 0; i < points[d].length; i++) {
assertEquals(points[d][i], geoPoints.get(i));
}
}
}
private static double quantizeLat(double lat) {
return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat));
}
private static double quantizeLon(double lon) {
return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon));
}
}
| ScriptDocValuesGeoPointsTests |
java | apache__maven | compat/maven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepository.java | {
"start": 1433,
"end": 2672
} | interface ____ {
String pathOf(Artifact artifact);
String pathOfRemoteRepositoryMetadata(ArtifactMetadata artifactMetadata);
String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository);
String getUrl();
void setUrl(String url);
String getBasedir();
default Path getBasedirPath() {
return Paths.get(getBasedir());
}
String getProtocol();
String getId();
void setId(String id);
ArtifactRepositoryPolicy getSnapshots();
void setSnapshotUpdatePolicy(ArtifactRepositoryPolicy policy);
ArtifactRepositoryPolicy getReleases();
void setReleaseUpdatePolicy(ArtifactRepositoryPolicy policy);
ArtifactRepositoryLayout getLayout();
void setLayout(ArtifactRepositoryLayout layout);
String getKey();
@Deprecated
boolean isUniqueVersion();
@Deprecated
boolean isBlacklisted();
@Deprecated
void setBlacklisted(boolean blackListed);
/**
* @return whether the repository is blocked
* @since 3.8.1
**/
boolean isBlocked();
/**
* @param blocked block the repository?
* @since 3.8.1
**/
void setBlocked(boolean blocked);
//
// New | ArtifactRepository |
java | spring-projects__spring-framework | spring-messaging/src/test/java/org/springframework/messaging/core/TestMessagePostProcessor.java | {
"start": 725,
"end": 997
} | class ____ implements MessagePostProcessor {
private Message<?> message;
Message<?> getMessage() {
return this.message;
}
@Override
public Message<?> postProcessMessage(Message<?> message) {
this.message = message;
return message;
}
}
| TestMessagePostProcessor |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/support/CacheKey.java | {
"start": 603,
"end": 722
} | interface ____ {
void buildCacheKey(StreamOutput out, DlsQueryEvaluationContext context) throws IOException;
}
| CacheKey |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/dataformat/BeanioDataFormat.java | {
"start": 5651,
"end": 6642
} | class ____ of the error handler. Notice the options ignoreUnidentifiedRecords,
* ignoreUnexpectedRecords, and ignoreInvalidRecords may not be in use when you use a custom error handler.
*/
public void setBeanReaderErrorHandlerType(String beanReaderErrorHandlerType) {
this.beanReaderErrorHandlerType = beanReaderErrorHandlerType;
}
public String getUnmarshalSingleObject() {
return unmarshalSingleObject;
}
/**
* This options controls whether to unmarshal as a list of objects or as a single object only. The former is the
* default mode, and the latter is only intended in special use-cases where beanio maps the Camel message to a
* single POJO bean.
*/
public void setUnmarshalSingleObject(String unmarshalSingleObject) {
this.unmarshalSingleObject = unmarshalSingleObject;
}
/**
* {@code Builder} is a specific builder for {@link BeanioDataFormat}.
*/
@XmlTransient
public static | name |
java | google__guice | core/src/com/google/inject/internal/aop/EnhancerBuilderImpl.java | {
"start": 1451,
"end": 3744
} | class ____ implements BytecodeGen.EnhancerBuilder {
/** Lazy association between classes and their generated enhancers. */
private static final ClassValue<
Map<BitSet, Function<String, BiFunction<Object, Object[], Object>>>>
ENHANCERS =
new ClassValue<Map<BitSet, Function<String, BiFunction<Object, Object[], Object>>>>() {
@Override
protected Map<BitSet, Function<String, BiFunction<Object, Object[], Object>>>
computeValue(Class<?> hostClass) {
return new HashMap<>();
}
};
private final Class<?> hostClass;
private final Method[] enhanceableMethods;
private final Map<Method, Method> bridgeDelegates;
EnhancerBuilderImpl(
Class<?> hostClass,
Collection<Method> enhanceableMethods,
Map<Method, Method> bridgeDelegates) {
this.hostClass = hostClass;
this.enhanceableMethods = enhanceableMethods.toArray(new Method[0]);
this.bridgeDelegates = ImmutableMap.copyOf(bridgeDelegates);
}
@Override
public Method[] getEnhanceableMethods() {
return enhanceableMethods;
}
@Override
public Function<String, BiFunction<Object, Object[], Object>> buildEnhancer(
BitSet methodIndices) {
if ((hostClass.getModifiers() & FINAL) != 0) {
throw new IllegalArgumentException("Cannot subclass final " + hostClass);
}
Map<BitSet, Function<String, BiFunction<Object, Object[], Object>>> enhancers =
ENHANCERS.get(hostClass);
synchronized (enhancers) {
return enhancers.computeIfAbsent(methodIndices, this::doBuildEnhancer);
}
}
private Function<String, BiFunction<Object, Object[], Object>> doBuildEnhancer(
BitSet methodIndices) {
NavigableMap<String, Executable> glueMap = new TreeMap<>();
visitMembers(
hostClass.getDeclaredConstructors(),
hasPackageAccess(),
ctor -> glueMap.put(signature(ctor), ctor));
for (int methodIndex = methodIndices.nextSetBit(0);
methodIndex >= 0;
methodIndex = methodIndices.nextSetBit(methodIndex + 1)) {
Method method = enhanceableMethods[methodIndex];
glueMap.put(signature(method), method);
}
return new Enhancer(hostClass, bridgeDelegates).glue(glueMap);
}
}
| EnhancerBuilderImpl |
java | spring-projects__spring-framework | spring-messaging/src/test/java/org/springframework/messaging/rsocket/service/RSocketServiceIntegrationTests.java | {
"start": 4246,
"end": 4674
} | class ____ {
@Bean
ServerController controller() {
return new ServerController();
}
@Bean
RSocketMessageHandler messageHandler(RSocketStrategies rsocketStrategies) {
RSocketMessageHandler handler = new RSocketMessageHandler();
handler.setRSocketStrategies(rsocketStrategies);
return handler;
}
@Bean
RSocketStrategies rsocketStrategies() {
return RSocketStrategies.create();
}
}
}
| ServerConfig |
java | quarkusio__quarkus | integration-tests/maven/src/test/resources-filtered/expected/new-extension-current-directory-project/deployment/src/main/java/org/acme/my/ext/deployment/MyExtProcessor.java | {
"start": 147,
"end": 327
} | class ____ {
private static final String FEATURE = "my-ext";
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(FEATURE);
}
}
| MyExtProcessor |
java | apache__camel | components/camel-ai/camel-langchain4j-tools/src/generated/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpointConfigurer.java | {
"start": 744,
"end": 5283
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
LangChain4jToolsEndpoint target = (LangChain4jToolsEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "cameltoolparameter":
case "camelToolParameter": target.setCamelToolParameter(property(camelContext, org.apache.camel.component.langchain4j.tools.spec.CamelSimpleToolParameter.class, value)); return true;
case "chatmodel":
case "chatModel": target.getConfiguration().setChatModel(property(camelContext, dev.langchain4j.model.chat.ChatModel.class, value)); return true;
case "description": target.setDescription(property(camelContext, java.lang.String.class, value)); return true;
case "exceptionhandler":
case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
case "exchangepattern":
case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "name": target.setName(property(camelContext, java.lang.String.class, value)); return true;
case "parameters": target.setParameters(property(camelContext, java.util.Map.class, value)); return true;
case "tags": target.setTags(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public String[] getAutowiredNames() {
return new String[]{"chatModel"};
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "cameltoolparameter":
case "camelToolParameter": return org.apache.camel.component.langchain4j.tools.spec.CamelSimpleToolParameter.class;
case "chatmodel":
case "chatModel": return dev.langchain4j.model.chat.ChatModel.class;
case "description": return java.lang.String.class;
case "exceptionhandler":
case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class;
case "exchangepattern":
case "exchangePattern": return org.apache.camel.ExchangePattern.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "name": return java.lang.String.class;
case "parameters": return java.util.Map.class;
case "tags": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
LangChain4jToolsEndpoint target = (LangChain4jToolsEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "cameltoolparameter":
case "camelToolParameter": return target.getCamelToolParameter();
case "chatmodel":
case "chatModel": return target.getConfiguration().getChatModel();
case "description": return target.getDescription();
case "exceptionhandler":
case "exceptionHandler": return target.getExceptionHandler();
case "exchangepattern":
case "exchangePattern": return target.getExchangePattern();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "name": return target.getName();
case "parameters": return target.getParameters();
case "tags": return target.getTags();
default: return null;
}
}
@Override
public Object getCollectionValueType(Object target, String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "parameters": return java.lang.String.class;
default: return null;
}
}
}
| LangChain4jToolsEndpointConfigurer |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/InlineTrivialConstantTest.java | {
"start": 1884,
"end": 1996
} | class ____ {
private final String EMPTY_STRING = "";
}
static | NonStatic |
java | hibernate__hibernate-orm | hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleMapKeyPropertyComponentMapper.java | {
"start": 711,
"end": 1800
} | class ____ extends AbstractMiddleComponentMapper {
private final String propertyName;
private final String accessType;
public MiddleMapKeyPropertyComponentMapper(String propertyName, String accessType) {
this.propertyName = propertyName;
this.accessType = accessType;
}
@Override
public Object mapToObjectFromFullMap(
final EntityInstantiator entityInstantiator,
final Map<String, Object> data,
final Object dataObject,
Number revision) {
// dataObject is not null, as this mapper can only be used in an index.
return getValueFromObject(
propertyName,
accessType,
dataObject,
entityInstantiator.getEnversService().getServiceRegistry()
);
}
@Override
public void mapToMapFromObject(
SharedSessionContractImplementor session,
Map<String, Object> idData,
Map<String, Object> data,
Object obj) {
// Doing nothing.
}
@Override
public void addMiddleEqualToQuery(
Parameters parameters,
String idPrefix1,
String prefix1,
String idPrefix2,
String prefix2) {
// Doing nothing.
}
}
| MiddleMapKeyPropertyComponentMapper |
java | quarkusio__quarkus | extensions/hibernate-reactive/deployment/src/test/java/io/quarkus/hibernate/reactive/compatibility/ORMReactiveCompatbilityNamedDataSourceNamedPersistenceUnitBothUnitTest.java | {
"start": 606,
"end": 2534
} | class ____ extends CompatibilityUnitTestBase {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(Hero.class)
.addAsResource("complexMultilineImports.sql", "import.sql"))
.setForcedDependencies(List.of(
Dependency.of("io.quarkus", "quarkus-jdbc-postgresql-deployment", Version.getVersion()) // this triggers Agroal
))
.withConfigurationResource("application-unittest-both-named.properties")
.overrideConfigKey("quarkus.hibernate-orm.\"named-pu\".schema-management.strategy", SCHEMA_MANAGEMENT_STRATEGY)
.overrideConfigKey("quarkus.hibernate-orm.\"named-pu\".datasource", "named-datasource")
.overrideConfigKey("quarkus.hibernate-orm.\"named-pu\".packages", "io.quarkus.hibernate.reactive.entities")
.overrideConfigKey("quarkus.datasource.\"named-datasource\".reactive", "true")
.overrideConfigKey("quarkus.datasource.\"named-datasource\".db-kind", POSTGRES_KIND)
.overrideConfigKey("quarkus.datasource.\"named-datasource\".username", USERNAME_PWD)
.overrideConfigKey("quarkus.datasource.\"named-datasource\".password", USERNAME_PWD)
.overrideConfigKey("quarkus.log.category.\"io.quarkus.hibernate\".level", "DEBUG");
@PersistenceUnit("named-pu")
Mutiny.SessionFactory namedMutinySessionFactory;
@Test
@RunOnVertxContext
public void test(UniAsserter uniAsserter) {
testReactiveWorks(namedMutinySessionFactory, uniAsserter);
}
@Inject
@PersistenceUnit("named-pu")
SessionFactory namedPersistenceUnitSessionFactory;
@Test
public void testBlocking() {
testBlockingWorks(namedPersistenceUnitSessionFactory);
}
}
| ORMReactiveCompatbilityNamedDataSourceNamedPersistenceUnitBothUnitTest |
java | netty__netty | common/src/main/java/io/netty/util/Signal.java | {
"start": 867,
"end": 3148
} | class ____ extends Error implements Constant<Signal> {
private static final long serialVersionUID = -221145131122459977L;
private static final ConstantPool<Signal> pool = new ConstantPool<Signal>() {
@Override
protected Signal newConstant(int id, String name) {
return new Signal(id, name);
}
};
/**
* Returns the {@link Signal} of the specified name.
*/
public static Signal valueOf(String name) {
return pool.valueOf(name);
}
/**
* Shortcut of {@link #valueOf(String) valueOf(firstNameComponent.getName() + "#" + secondNameComponent)}.
*/
public static Signal valueOf(Class<?> firstNameComponent, String secondNameComponent) {
return pool.valueOf(firstNameComponent, secondNameComponent);
}
private final SignalConstant constant;
/**
* Creates a new {@link Signal} with the specified {@code name}.
*/
private Signal(int id, String name) {
constant = new SignalConstant(id, name);
}
/**
* Check if the given {@link Signal} is the same as this instance. If not an {@link IllegalStateException} will
* be thrown.
*/
public void expect(Signal signal) {
if (this != signal) {
throw new IllegalStateException("unexpected signal: " + signal);
}
}
// Suppress a warning since the method doesn't need synchronization
@Override
public Throwable initCause(Throwable cause) {
return this;
}
// Suppress a warning since the method doesn't need synchronization
@Override
public Throwable fillInStackTrace() {
return this;
}
@Override
public int id() {
return constant.id();
}
@Override
public String name() {
return constant.name();
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
@Override
public int compareTo(Signal other) {
if (this == other) {
return 0;
}
return constant.compareTo(other.constant);
}
@Override
public String toString() {
return name();
}
private static final | Signal |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/http/customconfigurer/CustomHttpSecurityConfigurerTests.java | {
"start": 4803,
"end": 5632
} | class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.with(CustomConfigurer.customConfigurer(), Customizer.withDefaults())
.csrf((csrf) -> csrf.disable())
.formLogin((login) -> login
.loginPage("/other"));
return http.build();
// @formatter:on
}
@Bean
static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
// Typically externalize this as a properties file
Properties properties = new Properties();
properties.setProperty("permitAllPattern", "/public/**");
PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertyPlaceholderConfigurer.setProperties(properties);
return propertyPlaceholderConfigurer;
}
}
}
| ConfigCustomize |
java | spring-projects__spring-framework | spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValidationException.java | {
"start": 937,
"end": 1478
} | class ____ extends FatalBeanException {
/**
* Create a new BeanDefinitionValidationException with the specified message.
* @param msg the detail message
*/
public BeanDefinitionValidationException(String msg) {
super(msg);
}
/**
* Create a new BeanDefinitionValidationException with the specified message
* and root cause.
* @param msg the detail message
* @param cause the root cause
*/
public BeanDefinitionValidationException(String msg, Throwable cause) {
super(msg, cause);
}
}
| BeanDefinitionValidationException |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultStreamsRebalanceListener.java | {
"start": 1533,
"end": 6394
} | class ____ implements StreamsRebalanceListener {
private final Logger log;
private final Time time;
private final StreamsRebalanceData streamsRebalanceData;
private final TaskManager taskManager;
private final StreamThread streamThread;
private final Sensor tasksRevokedSensor;
private final Sensor tasksAssignedSensor;
private final Sensor tasksLostSensor;
public DefaultStreamsRebalanceListener(final Logger log,
final Time time,
final StreamsRebalanceData streamsRebalanceData,
final StreamThread streamThread,
final TaskManager taskManager,
final StreamsMetricsImpl streamsMetrics,
final String threadId) {
this.log = log;
this.time = time;
this.streamsRebalanceData = streamsRebalanceData;
this.streamThread = streamThread;
this.taskManager = taskManager;
// Create sensors for rebalance metrics
this.tasksRevokedSensor = RebalanceListenerMetrics.tasksRevokedSensor(threadId, streamsMetrics);
this.tasksAssignedSensor = RebalanceListenerMetrics.tasksAssignedSensor(threadId, streamsMetrics);
this.tasksLostSensor = RebalanceListenerMetrics.tasksLostSensor(threadId, streamsMetrics);
}
@Override
public void onTasksRevoked(final Set<StreamsRebalanceData.TaskId> tasks) {
final Map<TaskId, Set<TopicPartition>> activeTasksToRevokeWithPartitions =
pairWithTopicPartitions(tasks.stream());
final Set<TopicPartition> partitionsToRevoke = activeTasksToRevokeWithPartitions.values().stream()
.flatMap(Collection::stream)
.collect(Collectors.toSet());
final long start = time.milliseconds();
try {
log.info("Revoking active tasks {}.", tasks);
taskManager.handleRevocation(partitionsToRevoke);
} finally {
final long latency = time.milliseconds() - start;
tasksRevokedSensor.record(latency);
log.info("partition revocation took {} ms.", latency);
}
if (streamThread.state() != StreamThread.State.PENDING_SHUTDOWN) {
streamThread.setState(StreamThread.State.PARTITIONS_REVOKED);
}
}
@Override
public void onTasksAssigned(final StreamsRebalanceData.Assignment assignment) {
final long start = time.milliseconds();
final Map<TaskId, Set<TopicPartition>> activeTasksWithPartitions =
pairWithTopicPartitions(assignment.activeTasks().stream());
final Map<TaskId, Set<TopicPartition>> standbyTasksWithPartitions =
pairWithTopicPartitions(Stream.concat(assignment.standbyTasks().stream(), assignment.warmupTasks().stream()));
log.info("Processing new assignment {} from Streams Rebalance Protocol", assignment);
try {
taskManager.handleAssignment(activeTasksWithPartitions, standbyTasksWithPartitions);
streamThread.setState(StreamThread.State.PARTITIONS_ASSIGNED);
taskManager.handleRebalanceComplete();
streamsRebalanceData.setReconciledAssignment(assignment);
} finally {
tasksAssignedSensor.record(time.milliseconds() - start);
}
}
@Override
public void onAllTasksLost() {
final long start = time.milliseconds();
try {
taskManager.handleLostAll();
streamsRebalanceData.setReconciledAssignment(StreamsRebalanceData.Assignment.EMPTY);
} finally {
tasksLostSensor.record(time.milliseconds() - start);
}
}
private Map<TaskId, Set<TopicPartition>> pairWithTopicPartitions(final Stream<StreamsRebalanceData.TaskId> taskIdStream) {
return taskIdStream
.collect(Collectors.toMap(
this::toTaskId,
task -> toTopicPartitions(task, streamsRebalanceData.subtopologies().get(task.subtopologyId()))
));
}
private TaskId toTaskId(final StreamsRebalanceData.TaskId task) {
return new TaskId(Integer.parseInt(task.subtopologyId()), task.partitionId());
}
private Set<TopicPartition> toTopicPartitions(final StreamsRebalanceData.TaskId task,
final StreamsRebalanceData.Subtopology subTopology) {
return
Stream.concat(
subTopology.sourceTopics().stream(),
subTopology.repartitionSourceTopics().keySet().stream()
)
.map(t -> new TopicPartition(t, task.partitionId()))
.collect(Collectors.toSet());
}
}
| DefaultStreamsRebalanceListener |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/StreamCache.java | {
"start": 1869,
"end": 3582
} | interface ____ {
long DEFAULT_SPOOL_THRESHOLD = 128 * 1024L;
/**
* Resets the StreamCache for a new stream consumption.
*/
void reset();
/**
* Writes the stream to the given output
*
* @param os the destination to write to
* @throws java.io.IOException is thrown if write fails
*/
void writeTo(OutputStream os) throws IOException;
/**
* Create a copy of the stream. If possible use the same cached data in the copied instance.
* <p/>
* This method is useful for parallel processing.
* <p/>
* Implementations note: A copy of the stream is recommended to read from the start of the stream.
*
* @param exchange exchange in which the stream cache object is used; can be used to delete resources of
* the stream cache when the exchange is completed
* @return a copy, or <tt>null</tt> if copy is not possible
* @throws java.io.IOException is thrown if the copy fails
*/
StreamCache copy(Exchange exchange) throws IOException;
/**
* Whether this {@link StreamCache} is in memory only or spooled to persistent storage such as files.
*/
boolean inMemory();
/**
* Gets the length of the cached stream.
* <p/>
* The implementation may return <tt>0</tt> in cases where the length cannot be computed, or if the implementation
* does not support this.
*
* @return number of bytes in the cache.
*/
long length();
/**
* Read position
*
* @return position or -1 if not supported in the cached implementation
*/
long position();
}
| StreamCache |
java | junit-team__junit5 | junit-jupiter-api/src/main/java/org/junit/jupiter/api/TestInstance.java | {
"start": 890,
"end": 986
} | class ____ test interface.
*
* <p>If {@code @TestInstance} is not explicitly declared on a test | or |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/cluster/commands/reactive/HashClusterReactiveCommandIntegrationTests.java | {
"start": 480,
"end": 927
} | class ____ extends HashCommandIntegrationTests {
@Inject
HashClusterReactiveCommandIntegrationTests(StatefulRedisClusterConnection<String, String> connection) {
super(ReactiveSyncInvocationHandler.sync(connection));
}
@Test
@Disabled("API differences")
public void hgetall() {
}
@Test
@Disabled("API differences")
public void hgetallStreaming() {
}
}
| HashClusterReactiveCommandIntegrationTests |
java | spring-projects__spring-boot | integration-test/spring-boot-actuator-integration-tests/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java | {
"start": 2818,
"end": 21635
} | class ____<T extends ConfigurableApplicationContext & AnnotationConfigRegistry> {
private static final Duration TIMEOUT = Duration.ofMinutes(5);
private static final String ACTUATOR_MEDIA_TYPE_PATTERN = "application/vnd.test\\+json(;charset=UTF-8)?";
private static final String JSON_MEDIA_TYPE_PATTERN = "application/json(;charset=UTF-8)?";
private final Supplier<T> applicationContextSupplier;
private final Consumer<T> authenticatedContextCustomizer;
protected AbstractWebEndpointIntegrationTests(Supplier<T> applicationContextSupplier,
Consumer<T> authenticatedContextCustomizer) {
this.applicationContextSupplier = applicationContextSupplier;
this.authenticatedContextCustomizer = authenticatedContextCustomizer;
}
@Test
void readOperation() {
load(TestEndpointConfiguration.class,
(client) -> client.get()
.uri("/test")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("All")
.isEqualTo(true));
}
@Test
void readOperationWithEndpointsMappedToTheRoot() {
load(TestEndpointConfiguration.class, "",
(client) -> client.get()
.uri("/test")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("All")
.isEqualTo(true));
}
@Test
void readOperationWithEndpointPathMappedToTheRoot() {
load(EndpointPathMappedToRootConfiguration.class, "", (client) -> {
client.get().uri("/").exchange().expectStatus().isOk().expectBody().jsonPath("All").isEqualTo(true);
client.get()
.uri("/some-part")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("part")
.isEqualTo("some-part");
});
}
@Test
void readOperationWithSelector() {
load(TestEndpointConfiguration.class,
(client) -> client.get()
.uri("/test/one")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("part")
.isEqualTo("one"));
}
@Test
void readOperationWithSelectorContainingADot() {
load(TestEndpointConfiguration.class,
(client) -> client.get()
.uri("/test/foo.bar")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("part")
.isEqualTo("foo.bar"));
}
@Test
void linksToOtherEndpointsAreProvided() {
load(TestEndpointConfiguration.class,
(client) -> client.get()
.uri("")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("_links.length()")
.isEqualTo(3)
.jsonPath("_links.self.href")
.isNotEmpty()
.jsonPath("_links.self.templated")
.isEqualTo(false)
.jsonPath("_links.test.href")
.isNotEmpty()
.jsonPath("_links.test.templated")
.isEqualTo(false)
.jsonPath("_links.test-part.href")
.isNotEmpty()
.jsonPath("_links.test-part.templated")
.isEqualTo(true));
}
@Test
void linksMappingIsDisabledWhenEndpointPathIsEmpty() {
load(TestEndpointConfiguration.class, "",
(client) -> client.get().uri("").exchange().expectStatus().isNotFound());
}
@Test
protected void operationWithTrailingSlashShouldNotMatch() {
load(TestEndpointConfiguration.class,
(client) -> client.get().uri("/test/").exchange().expectStatus().isNotFound());
}
@Test
void matchAllRemainingPathsSelectorShouldMatchFullPath() {
load(MatchAllRemainingEndpointConfiguration.class,
(client) -> client.get()
.uri("/matchallremaining/one/two/three")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("selection")
.isEqualTo("one|two|three"));
}
@Test
void matchAllRemainingPathsSelectorShouldDecodePath() {
load(MatchAllRemainingEndpointConfiguration.class,
(client) -> client.get()
.uri("/matchallremaining/one/two three/")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("selection")
.isEqualTo("one|two three"));
}
@Test
void readOperationWithSingleQueryParameters() {
load(QueryEndpointConfiguration.class,
(client) -> client.get()
.uri("/query?one=1&two=2")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("query")
.isEqualTo("1 2"));
}
@Test
void readOperationWithQueryParametersMissing() {
load(QueryEndpointConfiguration.class,
(client) -> client.get().uri("/query").exchange().expectStatus().isBadRequest());
}
@Test
void reactiveReadOperationWithSingleQueryParameters() {
load(ReactiveQueryEndpointConfiguration.class,
(client) -> client.get()
.uri("/query?param=test")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("query")
.isEqualTo("test"));
}
@Test
void reactiveReadOperationWithQueryParametersMissing() {
load(ReactiveQueryEndpointConfiguration.class,
(client) -> client.get().uri("/query").exchange().expectStatus().isBadRequest());
}
@Test
void readOperationWithSingleQueryParametersAndMultipleValues() {
load(QueryEndpointConfiguration.class,
(client) -> client.get()
.uri("/query?one=1&one=1&two=2")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("query")
.isEqualTo("1,1 2"));
}
@Test
void readOperationWithListQueryParameterAndSingleValue() {
load(QueryWithListEndpointConfiguration.class,
(client) -> client.get()
.uri("/query?one=1&two=2")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("query")
.isEqualTo("1 [2]"));
}
@Test
void readOperationWithListQueryParameterAndMultipleValues() {
load(QueryWithListEndpointConfiguration.class,
(client) -> client.get()
.uri("/query?one=1&two=2&two=2")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("query")
.isEqualTo("1 [2, 2]"));
}
@Test
void readOperationWithMappingFailureProducesBadRequestResponse() {
load(QueryEndpointConfiguration.class, (client) -> {
WebTestClient.BodyContentSpec body = client.get()
.uri("/query?two=two")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isBadRequest()
.expectBody();
validateErrorBody(body, HttpStatus.BAD_REQUEST, "/endpoints/query", "Missing parameters: one");
});
}
@Test
void writeOperation() {
load(TestEndpointConfiguration.class, (client) -> {
Map<String, Object> body = new HashMap<>();
body.put("foo", "one");
body.put("bar", "two");
client.post().uri("/test").bodyValue(body).exchange().expectStatus().isNoContent().expectBody().isEmpty();
});
}
@Test
void writeOperationWithListOfValuesIsRejected() {
load(TestEndpointConfiguration.class, (client) -> {
Map<String, Object> body = new HashMap<>();
body.put("generic", List.of("one", "two"));
client.post().uri("/test/one").bodyValue(body).exchange().expectStatus().isBadRequest();
});
}
@Test
void writeOperationWithNestedValueIsRejected() {
load(TestEndpointConfiguration.class, (client) -> {
Map<String, Object> body = new HashMap<>();
body.put("generic", Map.of("nested", "one"));
client.post().uri("/test/one").bodyValue(body).exchange().expectStatus().isBadRequest();
});
}
@Test
void writeOperationWithVoidResponse() {
load(VoidWriteResponseEndpointConfiguration.class, (context, client) -> {
client.post().uri("/voidwrite").exchange().expectStatus().isNoContent().expectBody().isEmpty();
then(context.getBean(EndpointDelegate.class)).should().write();
});
}
@Test
void deleteOperation() {
load(TestEndpointConfiguration.class,
(client) -> client.delete()
.uri("/test/one")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("part")
.isEqualTo("one"));
}
@Test
void deleteOperationWithVoidResponse() {
load(VoidDeleteResponseEndpointConfiguration.class, (context, client) -> {
client.delete().uri("/voiddelete").exchange().expectStatus().isNoContent().expectBody().isEmpty();
then(context.getBean(EndpointDelegate.class)).should().delete();
});
}
@Test
void nullIsPassedToTheOperationWhenArgumentIsNotFoundInPostRequestBody() {
load(TestEndpointConfiguration.class, (context, client) -> {
Map<String, Object> body = new HashMap<>();
body.put("foo", "one");
client.post().uri("/test").bodyValue(body).exchange().expectStatus().isNoContent().expectBody().isEmpty();
then(context.getBean(EndpointDelegate.class)).should().write("one", null);
});
}
@Test
void nullsArePassedToTheOperationWhenPostRequestHasNoBody() {
load(TestEndpointConfiguration.class, (context, client) -> {
client.post()
.uri("/test")
.contentType(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isNoContent()
.expectBody()
.isEmpty();
then(context.getBean(EndpointDelegate.class)).should().write(null, null);
});
}
@Test
void nullResponseFromReadOperationResultsInNotFoundResponseStatus() {
load(NullReadResponseEndpointConfiguration.class,
(context, client) -> client.get().uri("/nullread").exchange().expectStatus().isNotFound());
}
@Test
void nullResponseFromDeleteOperationResultsInNoContentResponseStatus() {
load(NullDeleteResponseEndpointConfiguration.class,
(context, client) -> client.delete().uri("/nulldelete").exchange().expectStatus().isNoContent());
}
@Test
void nullResponseFromWriteOperationResultsInNoContentResponseStatus() {
load(NullWriteResponseEndpointConfiguration.class,
(context, client) -> client.post().uri("/nullwrite").exchange().expectStatus().isNoContent());
}
@Test
void readOperationWithResourceResponse() {
load(ResourceEndpointConfiguration.class, (context, client) -> {
byte[] responseBody = client.get()
.uri("/resource")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.returnResult(byte[].class)
.getResponseBodyContent();
assertThat(responseBody).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
});
}
@Test
void readOperationWithResourceWebOperationResponse() {
load(ResourceWebEndpointResponseEndpointConfiguration.class, (context, client) -> {
byte[] responseBody = client.get()
.uri("/resource")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.returnResult(byte[].class)
.getResponseBodyContent();
assertThat(responseBody).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
});
}
@Test
void readOperationWithMonoResponse() {
load(MonoResponseEndpointConfiguration.class,
(client) -> client.get()
.uri("/mono")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("a")
.isEqualTo("alpha"));
}
@Test
void readOperationWithFluxResponse() {
load(FluxResponseEndpointConfiguration.class,
(client) -> client.get()
.uri("/flux")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("[0].a")
.isEqualTo("alpha")
.jsonPath("[1].b")
.isEqualTo("bravo")
.jsonPath("[2].c")
.isEqualTo("charlie"));
}
@Test
void readOperationWithCustomMediaType() {
load(CustomMediaTypesEndpointConfiguration.class,
(client) -> client.get()
.uri("/custommediatypes")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.valueMatches("Content-Type", "text/plain(;charset=.*)?"));
}
@Test
void readOperationWithMissingRequiredParametersReturnsBadRequestResponse() {
load(RequiredParameterEndpointConfiguration.class, (client) -> {
WebTestClient.BodyContentSpec body = client.get()
.uri("/requiredparameters")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isBadRequest()
.expectBody();
validateErrorBody(body, HttpStatus.BAD_REQUEST, "/endpoints/requiredparameters", "Missing parameters: foo");
});
}
@Test
void readOperationWithMissingNullableParametersIsOk() {
load(RequiredParameterEndpointConfiguration.class,
(client) -> client.get().uri("/requiredparameters?foo=hello").exchange().expectStatus().isOk());
}
@Test
void endpointsProducePrimaryMediaTypeByDefault() {
load(TestEndpointConfiguration.class,
(client) -> client.get()
.uri("/test")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN));
}
@Test
void endpointsProduceSecondaryMediaTypeWhenRequested() {
load(TestEndpointConfiguration.class,
(client) -> client.get()
.uri("/test")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN));
}
@Test
void linksProducesPrimaryMediaTypeByDefault() {
load(TestEndpointConfiguration.class,
(client) -> client.get()
.uri("")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN));
}
@Test
void linksProducesSecondaryMediaTypeWhenRequested() {
load(TestEndpointConfiguration.class,
(client) -> client.get()
.uri("")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN));
}
@Test
void principalIsNullWhenRequestHasNoPrincipal() {
load(PrincipalEndpointConfiguration.class,
(client) -> client.get()
.uri("/principal")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("None"));
}
@Test
void principalIsAvailableWhenRequestHasAPrincipal() {
load((context) -> {
this.authenticatedContextCustomizer.accept(context);
context.register(PrincipalEndpointConfiguration.class);
}, (client) -> client.get()
.uri("/principal")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("Alice"));
}
@Test
void operationWithAQueryNamedPrincipalCanBeAccessedWhenAuthenticated() {
load((context) -> {
this.authenticatedContextCustomizer.accept(context);
context.register(PrincipalQueryEndpointConfiguration.class);
}, (client) -> client.get()
.uri("/principalquery?principal=Zoe")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("Zoe"));
}
@Test
void securityContextIsAvailableAndHasNullPrincipalWhenRequestHasNoPrincipal() {
load(SecurityContextEndpointConfiguration.class,
(client) -> client.get()
.uri("/securitycontext")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("None"));
}
@Test
void securityContextIsAvailableAndHasPrincipalWhenRequestHasPrincipal() {
load((context) -> {
this.authenticatedContextCustomizer.accept(context);
context.register(SecurityContextEndpointConfiguration.class);
}, (client) -> client.get()
.uri("/securitycontext")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("Alice"));
}
@Test
void userInRoleReturnsFalseWhenRequestHasNoPrincipal() {
load(UserInRoleEndpointConfiguration.class,
(client) -> client.get()
.uri("/userinrole?role=ADMIN")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("ADMIN: false"));
}
@Test
void userInRoleReturnsFalseWhenUserIsNotInRole() {
load((context) -> {
this.authenticatedContextCustomizer.accept(context);
context.register(UserInRoleEndpointConfiguration.class);
}, (client) -> client.get()
.uri("/userinrole?role=ADMIN")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("ADMIN: false"));
}
@Test
void userInRoleReturnsTrueWhenUserIsInRole() {
load((context) -> {
this.authenticatedContextCustomizer.accept(context);
context.register(UserInRoleEndpointConfiguration.class);
}, (client) -> client.get()
.uri("/userinrole?role=ACTUATOR")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("ACTUATOR: true"));
}
@Test
void endpointCanProduceAResponseWithACustomStatus() {
load((context) -> context.register(CustomResponseStatusEndpointConfiguration.class),
(client) -> client.get().uri("/customstatus").exchange().expectStatus().isEqualTo(234));
}
protected abstract int getPort(T context);
protected void validateErrorBody(WebTestClient.BodyContentSpec body, HttpStatus status, String path,
String message) {
body.jsonPath("status")
.isEqualTo(status.value())
.jsonPath("error")
.isEqualTo(status.getReasonPhrase())
.jsonPath("path")
.isEqualTo(path)
.jsonPath("message")
.isEqualTo(message);
}
private void load(Class<?> configuration, BiConsumer<ApplicationContext, WebTestClient> consumer) {
load((context) -> context.register(configuration), "/endpoints", consumer);
}
protected void load(Class<?> configuration, Consumer<WebTestClient> clientConsumer) {
load((context) -> context.register(configuration), "/endpoints",
(context, client) -> clientConsumer.accept(client));
}
protected void load(Consumer<T> contextCustomizer, Consumer<WebTestClient> clientConsumer) {
load(contextCustomizer, "/endpoints", (context, client) -> clientConsumer.accept(client));
}
protected void load(Class<?> configuration, String endpointPath, Consumer<WebTestClient> clientConsumer) {
load((context) -> context.register(configuration), endpointPath,
(context, client) -> clientConsumer.accept(client));
}
private void load(Consumer<T> contextCustomizer, String endpointPath,
BiConsumer<ApplicationContext, WebTestClient> consumer) {
T applicationContext = this.applicationContextSupplier.get();
contextCustomizer.accept(applicationContext);
Map<String, Object> properties = new HashMap<>();
properties.put("endpointPath", endpointPath);
properties.put("spring.web.error.include-message", "always");
applicationContext.getEnvironment().getPropertySources().addLast(new MapPropertySource("test", properties));
applicationContext.refresh();
try {
InetSocketAddress address = new InetSocketAddress(getPort(applicationContext));
String url = "http://" + address.getHostString() + ":" + address.getPort() + endpointPath;
consumer.accept(applicationContext,
WebTestClient.bindToServer().baseUrl(url).responseTimeout(TIMEOUT).build());
}
finally {
applicationContext.close();
}
}
@Configuration(proxyBeanMethods = false)
@Import(BaseConfiguration.class)
protected static | AbstractWebEndpointIntegrationTests |
java | quarkusio__quarkus | extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/maxmessagesize/MaxMessageSizeTest.java | {
"start": 699,
"end": 1443
} | class ____ {
@RegisterExtension
public static final QuarkusUnitTest test = new QuarkusUnitTest()
.withApplicationRoot(root -> {
root.addClasses(Echo.class, WSClient.class);
}).overrideConfigKey("quarkus.websockets-next.server.max-message-size", "10");
@Inject
Vertx vertx;
@TestHTTPResource("/echo")
URI echoUri;
@Test
void testMaxMessageSize() {
WSClient client = WSClient.create(vertx).connect(echoUri);
String msg = "foo".repeat(10);
String reply = client.sendAndAwaitReply(msg).toString();
assertNotEquals(msg, reply);
assertTrue(Echo.ISE_THROWN.get());
}
@WebSocket(path = "/echo")
public static | MaxMessageSizeTest |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/processing/JavaModelUtils.java | {
"start": 9106,
"end": 9781
} | class ____
*/
public static String getClassArrayName(TypeElement typeElement) {
return "[L" + getClassName(typeElement) + ";";
}
/**
* Return whether this is a record or a component of a record.
* @param e The element
* @return True if it is
*/
public static boolean isRecordOrRecordComponent(Element e) {
return isRecord(e) || isRecordComponent(e);
}
/**
* Return whether this is a component of a record.
* @param e The element
* @return True if it is
*/
public static boolean isRecordComponent(Element e) {
return resolveKind(e, RECORD_COMPONENT_KIND).isPresent();
}
}
| name |
java | quarkusio__quarkus | extensions/micrometer/runtime/src/main/java/io/quarkus/micrometer/runtime/config/runtime/VertxConfig.java | {
"start": 357,
"end": 1587
} | interface ____ {
/**
* Comma-separated list of regular expressions used to specify uri
* labels in http metrics.
*
* Vertx instrumentation will attempt to transform parameterized
* resource paths, `/item/123`, into a generic form, `/item/{id}`,
* to reduce the cardinality of uri label values.
*
* Patterns specified here will take precedence over those computed
* values.
*
* For example, if `/item/\\\\d+=/item/custom` or
* `/item/[0-9]+=/item/custom` is specified in this list,
* a request to a matching path (`/item/123`) will use the specified
* replacement value (`/item/custom`) as the value for the uri label.
* Note that backslashes must be double escaped as `\\\\`.
*
* @asciidoclet
* @deprecated use {@code quarkus.micrometer.binder.http-server.match-patterns}
*/
@Deprecated
Optional<List<String>> matchPatterns();
/**
* Comma-separated list of regular expressions defining uri paths
* that should be ignored (not measured).
*
* @deprecated use {@code quarkus.micrometer.binder.http-server.ignore-patterns}
*/
@Deprecated
Optional<List<String>> ignorePatterns();
}
| VertxConfig |
java | spring-projects__spring-security | config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java | {
"start": 22223,
"end": 23423
} | class ____ {
*
* @Bean
* public SecurityFilterChain securityFilterChain(HttpSecurity http) {
* http
* .authorizeHttpRequests((authorizeHttpRequests) ->
* authorizeHttpRequests
* .requestMatchers("/**").hasRole("USER")
* )
* .x509(withDefaults());
* return http.build();
* }
* }
* </pre>
* @param x509Customizer the {@link Customizer} to provide more options for the
* {@link X509Configurer}
* @return the {@link HttpSecurity} for further customizations @
*/
public HttpSecurity x509(Customizer<X509Configurer<HttpSecurity>> x509Customizer) {
x509Customizer.customize(getOrApply(new X509Configurer<>()));
return HttpSecurity.this;
}
/**
* Allows configuring of Remember Me authentication.
*
* <h2>Example Configuration</h2>
*
* The following configuration demonstrates how to allow token based remember me
* authentication. Upon authenticating if the HTTP parameter named "remember-me"
* exists, then the user will be remembered even after their
* {@link jakarta.servlet.http.HttpSession} expires.
*
* <pre>
* @Configuration
* @EnableWebSecurity
* public | X509SecurityConfig |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java | {
"start": 15130,
"end": 15294
} | interface ____ extends Suppressible {
Description matchConstantCaseLabel(ConstantCaseLabelTree tree, VisitorState state);
}
public | ConstantCaseLabelTreeMatcher |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/input/chain/ExecutableChainInput.java | {
"start": 925,
"end": 2171
} | class ____ extends ExecutableInput<ChainInput, ChainInput.Result> {
private static final Logger logger = LogManager.getLogger(ExecutableChainInput.class);
private final List<Tuple<String, ExecutableInput<?, ?>>> inputs;
public ExecutableChainInput(ChainInput input, List<Tuple<String, ExecutableInput<?, ?>>> inputs) {
super(input);
this.inputs = inputs;
}
@Override
public ChainInput.Result execute(WatchExecutionContext ctx, Payload payload) {
List<Tuple<String, Input.Result>> results = new ArrayList<>();
Map<String, Object> payloads = new HashMap<>();
try {
for (Tuple<String, ExecutableInput<?, ?>> tuple : inputs) {
Input.Result result = tuple.v2().execute(ctx, new Payload.Simple(payloads));
results.add(new Tuple<>(tuple.v1(), result));
payloads.put(tuple.v1(), result.payload().data());
}
return new ChainInput.Result(results, new Payload.Simple(payloads));
} catch (Exception e) {
logger.error(() -> format("failed to execute [%s] input for watch [%s]", TYPE, ctx.watch().id()), e);
return new ChainInput.Result(e);
}
}
}
| ExecutableChainInput |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/core/ResultSetExtractor.java | {
"start": 1183,
"end": 1985
} | interface ____ mainly used within the JDBC framework itself.
* A {@link RowMapper} is usually a simpler choice for ResultSet processing,
* mapping one result object per row instead of one result object for
* the entire ResultSet.
*
* <p>Note: In contrast to a {@link RowCallbackHandler}, a ResultSetExtractor
* object is typically stateless and thus reusable, as long as it doesn't
* access stateful resources (such as output streams when streaming LOB
* contents) or keep result state within the object.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since April 24, 2003
* @param <T> the result type
* @see JdbcTemplate
* @see RowCallbackHandler
* @see RowMapper
* @see org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor
*/
@FunctionalInterface
public | is |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.