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 | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/expressions/parser/ast/access/SubscriptOperator.java | {
"start": 1432,
"end": 4156
} | class ____ extends ExpressionNode {
private static final Method LIST_GET_METHOD = ReflectionUtils.getRequiredMethod(List.class, "get", int.class);
private static final Method MAP_GET_METHOD = ReflectionUtils.getRequiredMethod(Map.class, "get", Object.class);
private final ExpressionNode callee;
private final ExpressionNode index;
private boolean isArray = false;
private boolean isMap = false;
public SubscriptOperator(ExpressionNode callee, ExpressionNode index) {
this.callee = callee;
this.index = index;
}
@Override
protected ExpressionDef generateExpression(ExpressionCompilationContext ctx) {
ExpressionDef calleeExp = callee.compile(ctx);
ClassElement indexType = index.resolveClassElement(ctx);
ExpressionDef indexExp = index.compile(ctx);
TypeDef resultType = resolveType(ctx);
if (isMap) {
if (!indexType.isAssignable(String.class)) {
throw new ExpressionCompilationException("Invalid subscript operator. Map key must be a string.");
}
return calleeExp.invoke(MAP_GET_METHOD, indexExp).cast(resultType);
}
if (!indexType.equals(PrimitiveElement.INT)) {
throw new ExpressionCompilationException("Invalid subscript operator. Index must be an integer.");
}
if (isArray) {
return calleeExp.arrayElement(indexExp);
}
return calleeExp.invoke(LIST_GET_METHOD, indexExp).cast(resultType);
}
@Override
protected ClassElement doResolveClassElement(ExpressionVisitorContext ctx) {
ClassElement classElement = callee.resolveClassElement(ctx);
this.isArray = classElement.isArray();
this.isMap = classElement.isAssignable(Map.class);
if (!isMap && !classElement.isAssignable(List.class) && !isArray) {
throw new ExpressionCompilationException("Invalid subscript operator. Subscript operator can only be applied to maps, lists and arrays");
}
if (isArray) {
return classElement.fromArray();
} else if (isMap) {
Map<String, ClassElement> typeArguments = classElement.getTypeArguments();
if (typeArguments.containsKey("V")) {
return typeArguments.get("V");
} else {
return ClassElement.of(Object.class);
}
} else {
return classElement.getFirstTypeArgument()
.orElseGet(() -> ClassElement.of(Object.class));
}
}
@Override
protected TypeDef doResolveType(@NonNull ExpressionVisitorContext ctx) {
return TypeDef.erasure(resolveClassElement(ctx));
}
}
| SubscriptOperator |
java | elastic__elasticsearch | x-pack/plugin/monitoring/src/internalClusterTest/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterSslIT.java | {
"start": 1710,
"end": 8646
} | class ____ extends MonitoringIntegTestCase {
private final Settings globalSettings = Settings.builder().put("path.home", createTempDir()).build();
private static MockWebServer webServer;
private MockSecureSettings secureSettings;
@AfterClass
public static void cleanUpStatics() {
if (webServer != null) {
webServer.close();
webServer = null;
}
}
@Override
protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) {
final Path truststore = getDataPath("/org/elasticsearch/xpack/monitoring/exporter/http/testnode.jks");
assertThat(Files.exists(truststore), CoreMatchers.is(true));
if (webServer == null) {
try {
webServer = buildWebServer();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
final String address = "https://" + webServer.getHostName() + ":" + webServer.getPort();
final Settings.Builder builder = Settings.builder()
.put(super.nodeSettings(nodeOrdinal, otherSettings))
.put("xpack.monitoring.exporters.plaintext.type", "http")
.put("xpack.monitoring.exporters.plaintext.enabled", true)
.put("xpack.monitoring.exporters.plaintext.host", address)
.put("xpack.monitoring.exporters.plaintext.ssl.truststore.path", truststore)
.put("xpack.monitoring.exporters.plaintext.ssl.truststore.password", "testnode")
.put("xpack.monitoring.exporters.secure.type", "http")
.put("xpack.monitoring.exporters.secure.enabled", true)
.put("xpack.monitoring.exporters.secure.host", address)
.put("xpack.monitoring.exporters.secure.ssl.truststore.path", truststore);
secureSettings = new MockSecureSettings();
secureSettings.setString("xpack.monitoring.exporters.secure.ssl.truststore.secure_password", "testnode");
builder.setSecureSettings(secureSettings);
return builder.build();
}
private MockWebServer buildWebServer() throws IOException {
final Path cert = getDataPath("/org/elasticsearch/xpack/monitoring/exporter/http/testnode.crt");
final Path key = getDataPath("/org/elasticsearch/xpack/monitoring/exporter/http/testnode.pem");
final Settings sslSettings = Settings.builder()
.put("xpack.transport.security.ssl.certificate", cert)
.put("xpack.transport.security.ssl.key", key)
.put("xpack.transport.security.ssl.key_passphrase", "testnode")
.putList("xpack.transport.security.ssl.supported_protocols", XPackSettings.DEFAULT_SUPPORTED_PROTOCOLS)
.put(globalSettings)
.build();
TestsSSLService sslService = new TestsSSLService(TestEnvironment.newEnvironment(sslSettings));
final SSLContext sslContext = sslService.sslContext("xpack.security.transport.ssl");
MockWebServer server = new MockWebServer(sslContext, false);
server.start();
return server;
}
@Before
// Force the exporters to be built from closed secure settings (as they would be in a production environment)
public void closeSecureSettings() throws IOException {
if (secureSettings != null) {
secureSettings.close();
}
}
public void testCannotUpdateSslSettingsWithSecureSettings() throws Exception {
// Verify that it was created even though it has a secure setting
assertExporterExists("secure");
// Verify that we cannot modify the SSL settings
final ActionFuture<ClusterUpdateSettingsResponse> future = setVerificationMode("secure", SslVerificationMode.CERTIFICATE);
final IllegalArgumentException iae = expectThrows(IllegalArgumentException.class, future::actionGet);
assertThat(iae.getCause(), instanceOf(IllegalStateException.class));
assertThat(iae.getCause().getMessage(), containsString("secure_password"));
}
public void testCanUpdateSslSettingsWithNoSecureSettings() {
final ActionFuture<ClusterUpdateSettingsResponse> future = setVerificationMode("plaintext", SslVerificationMode.CERTIFICATE);
final ClusterUpdateSettingsResponse response = future.actionGet();
assertThat(response, notNullValue());
clearPersistentSettings("plaintext");
}
public void testCanAddNewExporterWithSsl() {
Path truststore = getDataPath("/org/elasticsearch/xpack/monitoring/exporter/http/testnode.jks");
assertThat(Files.exists(truststore), CoreMatchers.is(true));
updateClusterSettings(
Settings.builder()
.put("xpack.monitoring.exporters._new.type", "http")
.put("xpack.monitoring.exporters._new.host", "https://" + webServer.getHostName() + ":" + webServer.getPort())
.put("xpack.monitoring.exporters._new.ssl.truststore.path", truststore)
.put("xpack.monitoring.exporters._new.ssl.truststore.password", "testnode")
.put("xpack.monitoring.exporters._new.ssl.verification_mode", SslVerificationMode.CERTIFICATE.name())
);
assertExporterExists("_new");
clearPersistentSettings("_new");
}
private void assertExporterExists(String secure) {
final Exporter httpExporter = getExporter(secure);
assertThat(httpExporter, notNullValue());
assertThat(httpExporter, instanceOf(HttpExporter.class));
}
private Exporter getExporter(String name) {
final Exporters exporters = internalCluster().getInstance(Exporters.class);
assertThat(exporters, notNullValue());
return exporters.getExporter(name);
}
private ActionFuture<ClusterUpdateSettingsResponse> setVerificationMode(String name, SslVerificationMode mode) {
final ClusterUpdateSettingsRequest updateSettings = new ClusterUpdateSettingsRequest(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT);
final String verificationModeName = randomBoolean() ? mode.name() : mode.name().toLowerCase(Locale.ROOT);
final Settings settings = Settings.builder()
.put("xpack.monitoring.exporters." + name + ".type", HttpExporter.TYPE)
.put("xpack.monitoring.exporters." + name + ".host", "https://" + webServer.getHostName() + ":" + webServer.getPort())
.put("xpack.monitoring.exporters." + name + ".ssl.verification_mode", verificationModeName)
.build();
updateSettings.persistentSettings(settings);
return clusterAdmin().updateSettings(updateSettings);
}
private void clearPersistentSettings(String... names) {
final Settings.Builder builder = Settings.builder();
for (String name : names) {
builder.put("xpack.monitoring.exporters." + name + ".*", (String) null);
}
updateClusterSettings(builder);
}
}
| HttpExporterSslIT |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/node/AbsentNodeViaCreator3214Test.java | {
"start": 407,
"end": 1154
} | class ____
{
JsonNode fromCtor = StringNode.valueOf("x");
JsonNode fromSetter = StringNode.valueOf("x");
@JsonCreator
public Pojo3214(@JsonProperty("node") JsonNode n) {
this.fromCtor = n;
}
public void setNodeFromSetter(JsonNode nodeFromSetter) {
this.fromSetter = nodeFromSetter;
}
}
private final ObjectMapper MAPPER = newJsonMapper();
// [databind#3214]
@Test
public void testNullFromMissingNodeParameter() throws Exception
{
Pojo3214 p = MAPPER.readValue("{}", Pojo3214.class);
if (p.fromCtor != null) {
fail("Expected null to be passed, got instance of "+p.fromCtor.getClass());
}
}
}
| Pojo3214 |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/xslt/XsltRouteXsltWithErrorTest.java | {
"start": 1135,
"end": 2085
} | class ____ extends ContextTestSupport {
@Override
public boolean isUseRouteBuilder() {
return false;
}
@Test
public void testXsltWithError() throws Exception {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:start").to("xslt:org/apache/camel/component/xslt/transform-with-error.xsl");
}
});
Exception e = assertThrows(Exception.class,
() -> context.start(),
"Should have thrown exception");
TransformerConfigurationException cause = ObjectHelper.getException(TransformerConfigurationException.class, e);
assertNotNull(cause);
// not sure if XSLT errors may be i18n and not english always so
// just check for the spelling mistake of select -> slect
assertTrue(cause.getMessage().contains("slect"));
}
}
| XsltRouteXsltWithErrorTest |
java | spring-projects__spring-security | config/src/integration-test/java/org/springframework/security/config/ldap/LdapPasswordComparisonAuthenticationManagerFactoryITests.java | {
"start": 2819,
"end": 3305
} | class ____ extends BaseLdapServerConfig {
@Bean
AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {
LdapPasswordComparisonAuthenticationManagerFactory factory = new LdapPasswordComparisonAuthenticationManagerFactory(
contextSource, new BCryptPasswordEncoder());
factory.setUserDnPatterns("uid={0},ou=people");
return factory.createAuthenticationManager();
}
}
@Configuration
@EnableWebSecurity
static | CustomPasswordEncoderConfig |
java | google__guice | core/test/com/google/inject/internal/MapBinderTest.java | {
"start": 21160,
"end": 21441
} | class ____ extends AbstractModule {
@Override
protected void configure() {
MapBinder<String, Object> mapbinder =
MapBinder.newMapBinder(binder(), String.class, Object.class);
mapbinder.addBinding("b").to(Integer.class);
}
}
| Module3 |
java | apache__spark | sql/core/src/main/java/org/apache/spark/sql/execution/datasources/parquet/ParquetVectorUpdaterFactory.java | {
"start": 2226,
"end": 11800
} | class ____ {
private static final ZoneId UTC = ZoneOffset.UTC;
private final LogicalTypeAnnotation logicalTypeAnnotation;
// The timezone conversion to apply to int96 timestamps. Null if no conversion.
private final ZoneId convertTz;
private final String datetimeRebaseMode;
private final String datetimeRebaseTz;
private final String int96RebaseMode;
private final String int96RebaseTz;
ParquetVectorUpdaterFactory(
LogicalTypeAnnotation logicalTypeAnnotation,
ZoneId convertTz,
String datetimeRebaseMode,
String datetimeRebaseTz,
String int96RebaseMode,
String int96RebaseTz) {
this.logicalTypeAnnotation = logicalTypeAnnotation;
this.convertTz = convertTz;
this.datetimeRebaseMode = datetimeRebaseMode;
this.datetimeRebaseTz = datetimeRebaseTz;
this.int96RebaseMode = int96RebaseMode;
this.int96RebaseTz = int96RebaseTz;
}
public ParquetVectorUpdater getUpdater(ColumnDescriptor descriptor, DataType sparkType) {
PrimitiveType type = descriptor.getPrimitiveType();
PrimitiveType.PrimitiveTypeName typeName = type.getPrimitiveTypeName();
boolean isUnknownType = type.getLogicalTypeAnnotation() instanceof UnknownLogicalTypeAnnotation;
if (isUnknownType && sparkType instanceof NullType) {
return new NullTypeUpdater();
}
switch (typeName) {
case BOOLEAN -> {
if (sparkType == DataTypes.BooleanType) {
return new BooleanUpdater();
}
}
case INT32 -> {
if (sparkType == DataTypes.IntegerType || canReadAsIntDecimal(descriptor, sparkType)) {
return new IntegerUpdater();
} else if (sparkType == DataTypes.LongType && isUnsignedIntTypeMatched(32)) {
// In `ParquetToSparkSchemaConverter`, we map parquet UINT32 to our LongType.
// For unsigned int32, it stores as plain signed int32 in Parquet when dictionary
// fallbacks. We read them as long values.
return new UnsignedIntegerUpdater();
} else if (sparkType == DataTypes.LongType || canReadAsLongDecimal(descriptor, sparkType)) {
return new IntegerToLongUpdater();
} else if (canReadAsBinaryDecimal(descriptor, sparkType)) {
return new IntegerToBinaryUpdater();
} else if (sparkType == DataTypes.ByteType) {
return new ByteUpdater();
} else if (sparkType == DataTypes.ShortType) {
return new ShortUpdater();
} else if (sparkType == DataTypes.DoubleType) {
return new IntegerToDoubleUpdater();
} else if (sparkType == DataTypes.DateType) {
if ("CORRECTED".equals(datetimeRebaseMode)) {
return new IntegerUpdater();
} else {
boolean failIfRebase = "EXCEPTION".equals(datetimeRebaseMode);
return new IntegerWithRebaseUpdater(failIfRebase);
}
} else if (sparkType == DataTypes.TimestampNTZType && isDateTypeMatched(descriptor)) {
if ("CORRECTED".equals(datetimeRebaseMode)) {
return new DateToTimestampNTZUpdater();
} else {
boolean failIfRebase = "EXCEPTION".equals(datetimeRebaseMode);
return new DateToTimestampNTZWithRebaseUpdater(failIfRebase);
}
} else if (sparkType instanceof YearMonthIntervalType) {
return new IntegerUpdater();
} else if (canReadAsDecimal(descriptor, sparkType)) {
return new IntegerToDecimalUpdater(descriptor, (DecimalType) sparkType);
}
}
case INT64 -> {
// This is where we implement support for the valid type conversions.
if (sparkType == DataTypes.LongType || canReadAsLongDecimal(descriptor, sparkType)) {
if (DecimalType.is32BitDecimalType(sparkType)) {
return new DowncastLongUpdater();
} else {
return new LongUpdater();
}
} else if (canReadAsBinaryDecimal(descriptor, sparkType)) {
return new LongToBinaryUpdater();
} else if (isLongDecimal(sparkType) && isUnsignedIntTypeMatched(64)) {
// In `ParquetToSparkSchemaConverter`, we map parquet UINT64 to our Decimal(20, 0).
// For unsigned int64, it stores as plain signed int64 in Parquet when dictionary
// fallbacks. We read them as decimal values.
return new UnsignedLongUpdater();
} else if (sparkType == DataTypes.TimestampType &&
isTimestampTypeMatched(LogicalTypeAnnotation.TimeUnit.MICROS)) {
if ("CORRECTED".equals(datetimeRebaseMode)) {
return new LongUpdater();
} else {
boolean failIfRebase = "EXCEPTION".equals(datetimeRebaseMode);
return new LongWithRebaseUpdater(failIfRebase, datetimeRebaseTz);
}
} else if (sparkType == DataTypes.TimestampType &&
isTimestampTypeMatched(LogicalTypeAnnotation.TimeUnit.MILLIS)) {
if ("CORRECTED".equals(datetimeRebaseMode)) {
return new LongAsMicrosUpdater();
} else {
final boolean failIfRebase = "EXCEPTION".equals(datetimeRebaseMode);
return new LongAsMicrosRebaseUpdater(failIfRebase, datetimeRebaseTz);
}
} else if (sparkType == DataTypes.TimestampNTZType &&
isTimestampTypeMatched(LogicalTypeAnnotation.TimeUnit.MICROS)) {
// TIMESTAMP_NTZ is a new data type and has no legacy files that need to do rebase.
return new LongUpdater();
} else if (sparkType == DataTypes.TimestampNTZType &&
isTimestampTypeMatched(LogicalTypeAnnotation.TimeUnit.MILLIS)) {
// TIMESTAMP_NTZ is a new data type and has no legacy files that need to do rebase.
return new LongAsMicrosUpdater();
} else if (sparkType instanceof DayTimeIntervalType) {
return new LongUpdater();
} else if (canReadAsDecimal(descriptor, sparkType)) {
return new LongToDecimalUpdater(descriptor, (DecimalType) sparkType);
} else if (sparkType instanceof TimeType) {
return new LongAsNanosUpdater();
}
}
case FLOAT -> {
if (sparkType == DataTypes.FloatType) {
return new FloatUpdater();
} else if (sparkType == DataTypes.DoubleType) {
return new FloatToDoubleUpdater();
}
}
case DOUBLE -> {
if (sparkType == DataTypes.DoubleType) {
return new DoubleUpdater();
}
}
case INT96 -> {
if (sparkType == DataTypes.TimestampNTZType) {
// TimestampNTZ type does not require rebasing due to its lack of time zone context.
return new BinaryToSQLTimestampUpdater();
} else if (sparkType == DataTypes.TimestampType) {
final boolean failIfRebase = "EXCEPTION".equals(int96RebaseMode);
if (!shouldConvertTimestamps()) {
if ("CORRECTED".equals(int96RebaseMode)) {
return new BinaryToSQLTimestampUpdater();
} else {
return new BinaryToSQLTimestampRebaseUpdater(failIfRebase, int96RebaseTz);
}
} else {
if ("CORRECTED".equals(int96RebaseMode)) {
return new BinaryToSQLTimestampConvertTzUpdater(convertTz);
} else {
return new BinaryToSQLTimestampConvertTzRebaseUpdater(
failIfRebase,
convertTz,
int96RebaseTz);
}
}
}
}
case BINARY -> {
if (sparkType instanceof StringType || sparkType == DataTypes.BinaryType ||
canReadAsBinaryDecimal(descriptor, sparkType)) {
return new BinaryUpdater();
} else if (canReadAsDecimal(descriptor, sparkType)) {
return new BinaryToDecimalUpdater(descriptor, (DecimalType) sparkType);
}
}
case FIXED_LEN_BYTE_ARRAY -> {
int arrayLen = descriptor.getPrimitiveType().getTypeLength();
if (canReadAsIntDecimal(descriptor, sparkType)) {
return new FixedLenByteArrayAsIntUpdater(arrayLen);
} else if (canReadAsLongDecimal(descriptor, sparkType)) {
return new FixedLenByteArrayAsLongUpdater(arrayLen);
} else if (canReadAsBinaryDecimal(descriptor, sparkType)) {
return new FixedLenByteArrayUpdater(arrayLen);
} else if (sparkType == DataTypes.BinaryType) {
return new FixedLenByteArrayUpdater(arrayLen);
} else if (canReadAsDecimal(descriptor, sparkType)) {
return new FixedLenByteArrayToDecimalUpdater(descriptor, (DecimalType) sparkType);
}
}
default -> {}
}
// If we get here, it means the combination of Spark and Parquet type is invalid or not
// supported.
throw constructConvertNotSupportedException(descriptor, sparkType);
}
boolean isTimestampTypeMatched(LogicalTypeAnnotation.TimeUnit unit) {
return logicalTypeAnnotation instanceof TimestampLogicalTypeAnnotation annotation &&
annotation.getUnit() == unit;
}
boolean isTimeTypeMatched(LogicalTypeAnnotation.TimeUnit unit) {
return logicalTypeAnnotation instanceof TimeLogicalTypeAnnotation annotation &&
annotation.getUnit() == unit;
}
boolean isUnsignedIntTypeMatched(int bitWidth) {
return logicalTypeAnnotation instanceof IntLogicalTypeAnnotation annotation &&
!annotation.isSigned() && annotation.getBitWidth() == bitWidth;
}
/**
* Updater should not be called if all values are nulls, so all methods throw exception here.
*/
private static | ParquetVectorUpdaterFactory |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/search/NestedHelperTests.java | {
"start": 1430,
"end": 22426
} | class ____ extends MapperServiceTestCase {
MapperService mapperService;
SearchExecutionContext searchExecutionContext;
@Override
public void setUp() throws Exception {
super.setUp();
String mapping = """
{ "_doc" : {
"properties" : {
"foo" : { "type" : "keyword" },
"foo2" : { "type" : "long" },
"nested1" : {
"type" : "nested",
"properties" : {
"foo" : { "type" : "keyword" },
"foo2" : { "type" : "long" }
}
},
"nested2" : {
"type" : "nested",
"include_in_parent" : true,
"properties": {
"foo" : { "type" : "keyword" },
"foo2" : { "type" : "long" }
}
},
"nested3" : {
"type" : "nested",
"include_in_root" : true,
"properties": {
"foo" : { "type" : "keyword" },
"foo2" : { "type" : "long" }
}
}
}
} }
""";
mapperService = createMapperService(mapping);
searchExecutionContext = new SearchExecutionContext(
0,
0,
mapperService.getIndexSettings(),
null,
null,
mapperService,
mapperService.mappingLookup(),
null,
null,
parserConfig(),
writableRegistry(),
null,
null,
System::currentTimeMillis,
null,
null,
() -> true,
null,
emptyMap(),
MapperMetrics.NOOP
);
}
public void testMatchAll() {
assertTrue(NestedHelper.mightMatchNestedDocs(new MatchAllDocsQuery(), searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(new MatchAllDocsQuery(), "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(new MatchAllDocsQuery(), "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(new MatchAllDocsQuery(), "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(new MatchAllDocsQuery(), "nested_missing", searchExecutionContext));
}
public void testMatchNo() {
assertFalse(NestedHelper.mightMatchNestedDocs(new MatchNoDocsQuery(), searchExecutionContext));
assertFalse(NestedHelper.mightMatchNonNestedDocs(new MatchNoDocsQuery(), "nested1", searchExecutionContext));
assertFalse(NestedHelper.mightMatchNonNestedDocs(new MatchNoDocsQuery(), "nested2", searchExecutionContext));
assertFalse(NestedHelper.mightMatchNonNestedDocs(new MatchNoDocsQuery(), "nested3", searchExecutionContext));
assertFalse(NestedHelper.mightMatchNonNestedDocs(new MatchNoDocsQuery(), "nested_missing", searchExecutionContext));
}
public void testTermsQuery() {
Query termsQuery = mapperService.fieldType("foo").termsQuery(Collections.singletonList("bar"), null);
assertFalse(NestedHelper.mightMatchNestedDocs(termsQuery, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested_missing", searchExecutionContext));
termsQuery = mapperService.fieldType("nested1.foo").termsQuery(Collections.singletonList("bar"), null);
assertTrue(NestedHelper.mightMatchNestedDocs(termsQuery, searchExecutionContext));
assertFalse(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested_missing", searchExecutionContext));
termsQuery = mapperService.fieldType("nested2.foo").termsQuery(Collections.singletonList("bar"), null);
assertTrue(NestedHelper.mightMatchNestedDocs(termsQuery, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested_missing", searchExecutionContext));
termsQuery = mapperService.fieldType("nested3.foo").termsQuery(Collections.singletonList("bar"), null);
assertTrue(NestedHelper.mightMatchNestedDocs(termsQuery, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termsQuery, "nested_missing", searchExecutionContext));
}
public void testTermQuery() {
Query termQuery = mapperService.fieldType("foo").termQuery("bar", null);
assertFalse(NestedHelper.mightMatchNestedDocs(termQuery, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested_missing", searchExecutionContext));
termQuery = mapperService.fieldType("nested1.foo").termQuery("bar", null);
assertTrue(NestedHelper.mightMatchNestedDocs(termQuery, searchExecutionContext));
assertFalse(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested_missing", searchExecutionContext));
termQuery = mapperService.fieldType("nested2.foo").termQuery("bar", null);
assertTrue(NestedHelper.mightMatchNestedDocs(termQuery, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested_missing", searchExecutionContext));
termQuery = mapperService.fieldType("nested3.foo").termQuery("bar", null);
assertTrue(NestedHelper.mightMatchNestedDocs(termQuery, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(termQuery, "nested_missing", searchExecutionContext));
}
public void testRangeQuery() {
SearchExecutionContext context = mock(SearchExecutionContext.class);
Query rangeQuery = mapperService.fieldType("foo2").rangeQuery(2, 5, true, true, null, null, null, context);
assertFalse(NestedHelper.mightMatchNestedDocs(rangeQuery, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested_missing", searchExecutionContext));
rangeQuery = mapperService.fieldType("nested1.foo2").rangeQuery(2, 5, true, true, null, null, null, context);
assertTrue(NestedHelper.mightMatchNestedDocs(rangeQuery, searchExecutionContext));
assertFalse(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested_missing", searchExecutionContext));
rangeQuery = mapperService.fieldType("nested2.foo2").rangeQuery(2, 5, true, true, null, null, null, context);
assertTrue(NestedHelper.mightMatchNestedDocs(rangeQuery, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested_missing", searchExecutionContext));
rangeQuery = mapperService.fieldType("nested3.foo2").rangeQuery(2, 5, true, true, null, null, null, context);
assertTrue(NestedHelper.mightMatchNestedDocs(rangeQuery, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(rangeQuery, "nested_missing", searchExecutionContext));
}
public void testDisjunction() {
BooleanQuery bq = new BooleanQuery.Builder().add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD)
.add(new TermQuery(new Term("foo", "baz")), Occur.SHOULD)
.build();
assertFalse(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested1", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new TermQuery(new Term("nested1.foo", "bar")), Occur.SHOULD)
.add(new TermQuery(new Term("nested1.foo", "baz")), Occur.SHOULD)
.build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertFalse(NestedHelper.mightMatchNonNestedDocs(bq, "nested1", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new TermQuery(new Term("nested2.foo", "bar")), Occur.SHOULD)
.add(new TermQuery(new Term("nested2.foo", "baz")), Occur.SHOULD)
.build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested2", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new TermQuery(new Term("nested3.foo", "bar")), Occur.SHOULD)
.add(new TermQuery(new Term("nested3.foo", "baz")), Occur.SHOULD)
.build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested3", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD)
.add(new MatchAllDocsQuery(), Occur.SHOULD)
.build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested1", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new TermQuery(new Term("nested1.foo", "bar")), Occur.SHOULD)
.add(new MatchAllDocsQuery(), Occur.SHOULD)
.build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested1", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new TermQuery(new Term("nested2.foo", "bar")), Occur.SHOULD)
.add(new MatchAllDocsQuery(), Occur.SHOULD)
.build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested2", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new TermQuery(new Term("nested3.foo", "bar")), Occur.SHOULD)
.add(new MatchAllDocsQuery(), Occur.SHOULD)
.build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested3", searchExecutionContext));
}
private static Occur requiredOccur() {
return random().nextBoolean() ? Occur.MUST : Occur.FILTER;
}
public void testConjunction() {
BooleanQuery bq = new BooleanQuery.Builder().add(new TermQuery(new Term("foo", "bar")), requiredOccur())
.add(new MatchAllDocsQuery(), requiredOccur())
.build();
assertFalse(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested1", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new TermQuery(new Term("nested1.foo", "bar")), requiredOccur())
.add(new MatchAllDocsQuery(), requiredOccur())
.build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertFalse(NestedHelper.mightMatchNonNestedDocs(bq, "nested1", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new TermQuery(new Term("nested2.foo", "bar")), requiredOccur())
.add(new MatchAllDocsQuery(), requiredOccur())
.build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested2", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new TermQuery(new Term("nested3.foo", "bar")), requiredOccur())
.add(new MatchAllDocsQuery(), requiredOccur())
.build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested3", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new MatchAllDocsQuery(), requiredOccur()).add(new MatchAllDocsQuery(), requiredOccur()).build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested1", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new MatchAllDocsQuery(), requiredOccur()).add(new MatchAllDocsQuery(), requiredOccur()).build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested1", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new MatchAllDocsQuery(), requiredOccur()).add(new MatchAllDocsQuery(), requiredOccur()).build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested2", searchExecutionContext));
bq = new BooleanQuery.Builder().add(new MatchAllDocsQuery(), requiredOccur()).add(new MatchAllDocsQuery(), requiredOccur()).build();
assertTrue(NestedHelper.mightMatchNestedDocs(bq, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(bq, "nested3", searchExecutionContext));
}
public void testNested() throws IOException {
SearchExecutionContext context = createSearchExecutionContext(mapperService);
NestedQueryBuilder queryBuilder = new NestedQueryBuilder("nested1", new MatchAllQueryBuilder(), ScoreMode.Avg);
ESToParentBlockJoinQuery query = (ESToParentBlockJoinQuery) queryBuilder.toQuery(context);
Query expectedChildQuery = new BooleanQuery.Builder().add(new MatchAllDocsQuery(), Occur.MUST)
// we automatically add a filter since the inner query might match non-nested docs
.add(new TermQuery(new Term("_nested_path", "nested1")), Occur.FILTER)
.build();
assertEquals(expectedChildQuery, query.getChildQuery());
assertFalse(NestedHelper.mightMatchNestedDocs(query, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested_missing", searchExecutionContext));
queryBuilder = new NestedQueryBuilder("nested1", new TermQueryBuilder("nested1.foo", "bar"), ScoreMode.Avg);
query = (ESToParentBlockJoinQuery) queryBuilder.toQuery(context);
// this time we do not add a filter since the inner query only matches inner docs
expectedChildQuery = new TermQuery(new Term("nested1.foo", "bar"));
assertEquals(expectedChildQuery, query.getChildQuery());
assertFalse(NestedHelper.mightMatchNestedDocs(query, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested_missing", searchExecutionContext));
queryBuilder = new NestedQueryBuilder("nested2", new TermQueryBuilder("nested2.foo", "bar"), ScoreMode.Avg);
query = (ESToParentBlockJoinQuery) queryBuilder.toQuery(context);
// we need to add the filter again because of include_in_parent
expectedChildQuery = new BooleanQuery.Builder().add(new TermQuery(new Term("nested2.foo", "bar")), Occur.MUST)
.add(new TermQuery(new Term("_nested_path", "nested2")), Occur.FILTER)
.build();
assertEquals(expectedChildQuery, query.getChildQuery());
assertFalse(NestedHelper.mightMatchNestedDocs(query, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested_missing", searchExecutionContext));
queryBuilder = new NestedQueryBuilder("nested3", new TermQueryBuilder("nested3.foo", "bar"), ScoreMode.Avg);
query = (ESToParentBlockJoinQuery) queryBuilder.toQuery(context);
// we need to add the filter again because of include_in_root
expectedChildQuery = new BooleanQuery.Builder().add(new TermQuery(new Term("nested3.foo", "bar")), Occur.MUST)
.add(new TermQuery(new Term("_nested_path", "nested3")), Occur.FILTER)
.build();
assertEquals(expectedChildQuery, query.getChildQuery());
assertFalse(NestedHelper.mightMatchNestedDocs(query, searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested1", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested2", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested3", searchExecutionContext));
assertTrue(NestedHelper.mightMatchNonNestedDocs(query, "nested_missing", searchExecutionContext));
}
}
| NestedHelperTests |
java | elastic__elasticsearch | test/framework/src/integTest/java/org/elasticsearch/test/test/TestScopeClusterIT.java | {
"start": 920,
"end": 1896
} | class ____ extends ESIntegTestCase {
private static int ITER = 0;
private static long[] SEQUENCE = new long[100];
private static Long CLUSTER_SEED = null;
public void testReproducible() throws IOException {
if (ITER++ == 0) {
CLUSTER_SEED = cluster().seed();
for (int i = 0; i < SEQUENCE.length; i++) {
SEQUENCE[i] = randomLong();
}
} else {
assertEquals(CLUSTER_SEED, Long.valueOf(cluster().seed()));
for (int i = 0; i < SEQUENCE.length; i++) {
assertThat(SEQUENCE[i], equalTo(randomLong()));
}
}
}
@Override
protected TestCluster buildTestCluster(Scope scope, long seed) throws IOException {
// produce some randomness
int iters = between(1, 100);
for (int i = 0; i < iters; i++) {
randomLong();
}
return super.buildTestCluster(scope, seed);
}
}
| TestScopeClusterIT |
java | apache__spark | examples/src/main/java/org/apache/spark/examples/sql/JavaSparkSQLExample.java | {
"start": 2325,
"end": 2397
} | class ____ {
// $example on:create_ds$
public static | JavaSparkSQLExample |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/OpensearchEndpointBuilderFactory.java | {
"start": 28513,
"end": 28850
} | class ____ extends AbstractEndpointBuilder implements OpensearchEndpointBuilder, AdvancedOpensearchEndpointBuilder {
public OpensearchEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new OpensearchEndpointBuilderImpl(path);
}
} | OpensearchEndpointBuilderImpl |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java | {
"start": 5712,
"end": 5798
} | enum ____ {
ADD,
REMOVE,
REPLACE
}
private final | NodeLabelUpdateOperation |
java | spring-projects__spring-framework | spring-jms/src/test/java/org/springframework/jms/StubTextMessage.java | {
"start": 962,
"end": 7027
} | class ____ implements TextMessage {
private String messageId;
private String text;
private int deliveryMode = DEFAULT_DELIVERY_MODE;
private Destination destination;
private String correlationId;
private Destination replyTo;
private String type;
private long deliveryTime;
private long timestamp = 0L;
private long expiration = 0L;
private int priority = DEFAULT_PRIORITY;
private boolean redelivered;
private ConcurrentHashMap<String, Object> properties = new ConcurrentHashMap<>();
public StubTextMessage() {
}
public StubTextMessage(String text) {
this.text = text;
}
@Override
public String getText() {
return this.text;
}
@Override
public void setText(String text) {
this.text = text;
}
@Override
public void acknowledge() {
throw new UnsupportedOperationException();
}
@Override
public void clearBody() {
this.text = null;
}
@Override
public void clearProperties() {
this.properties.clear();
}
@Override
public boolean getBooleanProperty(String name) {
Object value = this.properties.get(name);
return (value instanceof Boolean b) ? b : false;
}
@Override
public byte getByteProperty(String name) {
Object value = this.properties.get(name);
return (value instanceof Byte b) ? b : 0;
}
@Override
public double getDoubleProperty(String name) {
Object value = this.properties.get(name);
return (value instanceof Double d) ? d : 0;
}
@Override
public float getFloatProperty(String name) {
Object value = this.properties.get(name);
return (value instanceof Float f) ? f : 0;
}
@Override
public int getIntProperty(String name) {
Object value = this.properties.get(name);
return (value instanceof Integer i) ? i : 0;
}
@Override
public String getJMSCorrelationID() throws JMSException {
return this.correlationId;
}
@Override
public byte[] getJMSCorrelationIDAsBytes() {
return this.correlationId.getBytes();
}
@Override
public int getJMSDeliveryMode() throws JMSException {
return this.deliveryMode;
}
@Override
public Destination getJMSDestination() throws JMSException {
return this.destination;
}
@Override
public long getJMSExpiration() throws JMSException {
return this.expiration;
}
@Override
public String getJMSMessageID() throws JMSException {
return this.messageId;
}
@Override
public int getJMSPriority() throws JMSException {
return this.priority;
}
@Override
public boolean getJMSRedelivered() throws JMSException {
return this.redelivered;
}
@Override
public Destination getJMSReplyTo() throws JMSException {
return this.replyTo;
}
@Override
public long getJMSTimestamp() throws JMSException {
return this.timestamp;
}
@Override
public String getJMSType() throws JMSException {
return this.type;
}
@Override
public long getJMSDeliveryTime() {
return this.deliveryTime;
}
@Override
public long getLongProperty(String name) {
Object value = this.properties.get(name);
return (value instanceof Long l) ? l : 0;
}
@Override
public Object getObjectProperty(String name) throws JMSException {
return this.properties.get(name);
}
@Override
public Enumeration<?> getPropertyNames() {
return this.properties.keys();
}
@Override
public short getShortProperty(String name) {
Object value = this.properties.get(name);
return (value instanceof Short s) ? s : 0;
}
@Override
public String getStringProperty(String name) {
Object value = this.properties.get(name);
return (value instanceof String text) ? text : null;
}
@Override
public boolean propertyExists(String name) {
return this.properties.containsKey(name);
}
@Override
public void setBooleanProperty(String name, boolean value) {
this.properties.put(name, value);
}
@Override
public void setByteProperty(String name, byte value) {
this.properties.put(name, value);
}
@Override
public void setDoubleProperty(String name, double value) {
this.properties.put(name, value);
}
@Override
public void setFloatProperty(String name, float value) {
this.properties.put(name, value);
}
@Override
public void setIntProperty(String name, int value) {
this.properties.put(name, value);
}
@Override
public void setJMSCorrelationID(String correlationId) throws JMSException {
this.correlationId = correlationId;
}
@Override
public void setJMSCorrelationIDAsBytes(byte[] correlationID) {
this.correlationId = new String(correlationID);
}
@Override
public void setJMSDeliveryMode(int deliveryMode) {
this.deliveryMode = deliveryMode;
}
@Override
public void setJMSDestination(Destination destination) {
this.destination = destination;
}
@Override
public void setJMSExpiration(long expiration) {
this.expiration = expiration;
}
@Override
public void setJMSMessageID(String id) {
this.messageId = id;
}
@Override
public void setJMSPriority(int priority) {
this.priority = priority;
}
@Override
public void setJMSRedelivered(boolean redelivered) {
this.redelivered = redelivered;
}
@Override
public void setJMSReplyTo(Destination replyTo) throws JMSException {
this.replyTo = replyTo;
}
@Override
public void setJMSTimestamp(long timestamp) {
this.timestamp = timestamp;
}
@Override
public void setJMSType(String type) throws JMSException {
this.type = type;
}
@Override
public void setJMSDeliveryTime(long deliveryTime) {
this.deliveryTime = deliveryTime;
}
@Override
public void setLongProperty(String name, long value) {
this.properties.put(name, value);
}
@Override
public void setObjectProperty(String name, Object value) throws JMSException {
this.properties.put(name, value);
}
@Override
public void setShortProperty(String name, short value) {
this.properties.put(name, value);
}
@Override
public void setStringProperty(String name, String value) {
this.properties.put(name, value);
}
@Override
public <T> T getBody(Class<T> c) {
return null;
}
@Override
@SuppressWarnings("rawtypes")
public boolean isBodyAssignableTo(Class c) {
return false;
}
}
| StubTextMessage |
java | dropwizard__dropwizard | dropwizard-core/src/test/java/io/dropwizard/core/validation/InjectValidatorFeatureTest.java | {
"start": 2962,
"end": 3095
} | class ____ {
@Min(10)
final int value;
Bean(int value) {
this.value = value;
}
}
}
| Bean |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/cluster/models/slots/ClusterSlotsParserUnitTests.java | {
"start": 525,
"end": 4764
} | class ____ {
@Test
void testEmpty() {
List<ClusterSlotRange> result = ClusterSlotsParser.parse(new ArrayList<>());
assertThat(result).isNotNull().isEmpty();
}
@Test
void testOneString() {
List<ClusterSlotRange> result = ClusterSlotsParser.parse(LettuceLists.newList(""));
assertThat(result).isNotNull().isEmpty();
}
@Test
void testOneStringInList() {
List<?> list = Arrays.asList(LettuceLists.newList("0"));
List<ClusterSlotRange> result = ClusterSlotsParser.parse(list);
assertThat(result).isNotNull().isEmpty();
}
@Test
void testParse() {
List<?> list = Arrays.asList(LettuceLists.newList("0", "1", LettuceLists.newList("1", "2")));
List<ClusterSlotRange> result = ClusterSlotsParser.parse(list);
assertThat(result).hasSize(1);
assertThat(result.get(0).getUpstream()).isNotNull();
}
@Test
void testParseWithReplica() {
List<?> list = Arrays.asList(LettuceLists.newList("100", "200", LettuceLists.newList("1", "2", "nodeId1"),
LettuceLists.newList("1", 2, "nodeId2")));
List<ClusterSlotRange> result = ClusterSlotsParser.parse(list);
assertThat(result).hasSize(1);
ClusterSlotRange clusterSlotRange = result.get(0);
RedisClusterNode upstreamNode = clusterSlotRange.getUpstream();
assertThat(upstreamNode).isNotNull();
assertThat(upstreamNode.getNodeId()).isEqualTo("nodeId1");
assertThat(upstreamNode.getUri().getHost()).isEqualTo("1");
assertThat(upstreamNode.getUri().getPort()).isEqualTo(2);
assertThat(upstreamNode.is(RedisClusterNode.NodeFlag.MASTER)).isTrue();
assertThat(upstreamNode.getSlots()).contains(100, 101, 199, 200);
assertThat(upstreamNode.getSlots()).doesNotContain(99, 201);
assertThat(upstreamNode.getSlots()).hasSize(101);
assertThat(clusterSlotRange.getSlaveNodes()).hasSize(1);
RedisClusterNode replica = clusterSlotRange.getReplicaNodes().get(0);
assertThat(replica.getNodeId()).isEqualTo("nodeId2");
assertThat(replica.getSlaveOf()).isEqualTo("nodeId1");
assertThat(replica.is(RedisClusterNode.NodeFlag.SLAVE)).isTrue();
}
@Test
void testSameNode() {
List<?> list = Arrays.asList(
LettuceLists.newList("100", "200", LettuceLists.newList("1", "2", "nodeId1"),
LettuceLists.newList("1", 2, "nodeId2")),
LettuceLists.newList("200", "300", LettuceLists.newList("1", "2", "nodeId1"),
LettuceLists.newList("1", 2, "nodeId2")));
List<ClusterSlotRange> result = ClusterSlotsParser.parse(list);
assertThat(result).hasSize(2);
assertThat(result.get(0).getUpstream()).isSameAs(result.get(1).getUpstream());
RedisClusterNode upstreamNode = result.get(0).getUpstream();
assertThat(upstreamNode).isNotNull();
assertThat(upstreamNode.getNodeId()).isEqualTo("nodeId1");
assertThat(upstreamNode.getUri().getHost()).isEqualTo("1");
assertThat(upstreamNode.getUri().getPort()).isEqualTo(2);
assertThat(upstreamNode.is(RedisClusterNode.NodeFlag.MASTER)).isTrue();
assertThat(upstreamNode.getSlots()).contains(100, 101, 199, 200, 203);
assertThat(upstreamNode.getSlots()).doesNotContain(99, 301);
assertThat(upstreamNode.getSlots()).hasSize(201);
}
@Test
void testParseInvalidUpstream() {
List<?> list = Arrays.asList(LettuceLists.newList("0", "1", LettuceLists.newList("1")));
assertThatThrownBy(() -> ClusterSlotsParser.parse(list)).isInstanceOf(IllegalArgumentException.class);
}
@Test
void testParseInvalidUpstream2() {
List<?> list = Arrays.asList(LettuceLists.newList("0", "1", ""));
assertThatThrownBy(() -> ClusterSlotsParser.parse(list)).isInstanceOf(IllegalArgumentException.class);
}
@Test
void testModel() {
ClusterSlotRange range = new ClusterSlotRange();
range.setFrom(1);
range.setTo(2);
assertThat(range.toString()).contains(ClusterSlotRange.class.getSimpleName());
}
}
| ClusterSlotsParserUnitTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/event/spi/PreUpdateEvent.java | {
"start": 440,
"end": 1658
} | class ____ extends AbstractPreDatabaseOperationEvent {
private final Object[] state;
private final Object[] oldState;
/**
* Constructs an event containing the pertinent information.
* @param entity The entity to be updated.
* @param id The id of the entity to use for updating.
* @param state The state to be updated.
* @param oldState The state of the entity at the time it was loaded from
* the database.
* @param persister The entity's persister.
* @param source The session from which the event originated.
*/
public PreUpdateEvent(
Object entity,
Object id,
Object[] state,
Object[] oldState,
EntityPersister persister,
SharedSessionContractImplementor source) {
super( source, entity, id, persister );
this.state = state;
this.oldState = oldState;
}
/**
* Retrieves the state to be used in the update.
*
* @return The current state.
*/
public Object[] getState() {
return state;
}
/**
* The old state of the entity at the time it was last loaded from the
* database; can be null in the case of detached entities.
*
* @return The loaded state, or null.
*/
public Object[] getOldState() {
return oldState;
}
}
| PreUpdateEvent |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/Traceable.java | {
"start": 995,
"end": 1225
} | interface ____ {
/**
* Gets the trace label used for logging when tracing is enabled.
* <p/>
* The label should be short and precise.
*
* @return the label
*/
String getTraceLabel();
}
| Traceable |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/long_/LongAssert_usingComparator_Test.java | {
"start": 1019,
"end": 1588
} | class ____ extends LongAssertBaseTest {
private final Comparator<Long> comparator = alwaysEqual();
@Override
protected LongAssert invoke_api_method() {
// in that, we don't care of the comparator, the point to check is that we switch correctly of comparator
return assertions.usingComparator(comparator);
}
@Override
protected void verify_internal_effects() {
assertThat(getObjects(assertions).getComparator()).isSameAs(comparator);
assertThat(getLongs(assertions).getComparator()).isSameAs(comparator);
}
}
| LongAssert_usingComparator_Test |
java | spring-projects__spring-boot | module/spring-boot-session/src/main/java/org/springframework/boot/session/autoconfigure/SessionsEndpointAutoConfiguration.java | {
"start": 2520,
"end": 3018
} | class ____ {
@Bean
@ConditionalOnMissingBean
SessionsEndpoint sessionEndpoint(SessionRepository<?> sessionRepository,
ObjectProvider<FindByIndexNameSessionRepository<?>> indexedSessionRepository) {
return new SessionsEndpoint(sessionRepository, indexedSessionRepository.getIfAvailable());
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.REACTIVE)
@ConditionalOnBean(ReactiveSessionRepository.class)
static | ServletSessionEndpointConfiguration |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/resource/VersionResourceResolver.java | {
"start": 9193,
"end": 11538
} | class ____ extends AbstractResource implements HttpResource {
private final Resource original;
private final String version;
public FileNameVersionedResource(Resource original, String version) {
this.original = original;
this.version = version;
}
@Override
public boolean exists() {
return this.original.exists();
}
@Override
public boolean isReadable() {
return this.original.isReadable();
}
@Override
public boolean isOpen() {
return this.original.isOpen();
}
@Override
public boolean isFile() {
return this.original.isFile();
}
@Override
public URL getURL() throws IOException {
return this.original.getURL();
}
@Override
public URI getURI() throws IOException {
return this.original.getURI();
}
@Override
public File getFile() throws IOException {
return this.original.getFile();
}
@Override
public Path getFilePath() throws IOException {
return this.original.getFilePath();
}
@Override
public InputStream getInputStream() throws IOException {
return this.original.getInputStream();
}
@Override
public ReadableByteChannel readableChannel() throws IOException {
return this.original.readableChannel();
}
@Override
public byte[] getContentAsByteArray() throws IOException {
return this.original.getContentAsByteArray();
}
@Override
public String getContentAsString(Charset charset) throws IOException {
return this.original.getContentAsString(charset);
}
@Override
public long contentLength() throws IOException {
return this.original.contentLength();
}
@Override
public long lastModified() throws IOException {
return this.original.lastModified();
}
@Override
public Resource createRelative(String relativePath) throws IOException {
return this.original.createRelative(relativePath);
}
@Override
public @Nullable String getFilename() {
return this.original.getFilename();
}
@Override
public String getDescription() {
return this.original.getDescription();
}
@Override
public HttpHeaders getResponseHeaders() {
HttpHeaders headers = (this.original instanceof HttpResource httpResource ?
httpResource.getResponseHeaders() : new HttpHeaders());
headers.setETag("W/\"" + this.version + "\"");
return headers;
}
}
}
| FileNameVersionedResource |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/MvMaxTests.java | {
"start": 913,
"end": 2322
} | class ____ extends AbstractMultivalueFunctionTestCase {
public MvMaxTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) {
this.testCase = testCaseSupplier.get();
}
@ParametersFactory
public static Iterable<Object[]> parameters() {
List<TestCaseSupplier> cases = new ArrayList<>();
booleans(cases, "mv_max", "MvMax", (size, values) -> equalTo(values.max(Comparator.naturalOrder()).get()));
bytesRefs(cases, "mv_max", "MvMax", (size, values) -> equalTo(values.max(Comparator.naturalOrder()).get()));
doubles(cases, "mv_max", "MvMax", (size, values) -> equalTo(values.max().getAsDouble()));
ints(cases, "mv_max", "MvMax", (size, values) -> equalTo(values.max().getAsInt()));
longs(cases, "mv_max", "MvMax", (size, values) -> equalTo(values.max().getAsLong()));
unsignedLongs(cases, "mv_max", "MvMax", (size, values) -> equalTo(values.reduce(BigInteger::max).get()));
dateTimes(cases, "mv_max", "MvMax", (size, values) -> equalTo(values.max().getAsLong()));
dateNanos(cases, "mv_max", "MvMax", DataType.DATE_NANOS, (size, values) -> equalTo(values.max().getAsLong()));
return parameterSuppliersFromTypedDataWithDefaultChecks(false, cases);
}
@Override
protected Expression build(Source source, Expression field) {
return new MvMax(source, field);
}
}
| MvMaxTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/serialization/ProxySerializationNoSessionFactoryTest.java | {
"start": 3202,
"end": 3559
} | class ____ implements Serializable {
@Id
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
@Entity(name = "ChildEntity")
static | SimpleEntity |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/NestedTestClassesTests.java | {
"start": 16315,
"end": 16403
} | interface ____ static and should have been filtered out");
}
}
}
static abstract | is |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/security/authenticator/CredentialCache.java | {
"start": 1836,
"end": 2557
} | class ____<C> {
private final Class<C> credentialClass;
private final ConcurrentHashMap<String, C> credentials;
public Cache(Class<C> credentialClass) {
this.credentialClass = credentialClass;
this.credentials = new ConcurrentHashMap<>();
}
public C get(String username) {
return credentials.get(username);
}
public C put(String username, C credential) {
return credentials.put(username, credential);
}
public C remove(String username) {
return credentials.remove(username);
}
public Class<C> credentialClass() {
return credentialClass;
}
}
}
| Cache |
java | apache__rocketmq | common/src/main/java/org/apache/rocketmq/common/namesrv/NamesrvUtil.java | {
"start": 855,
"end": 961
} | class ____ {
public static final String NAMESPACE_ORDER_TOPIC_CONFIG = "ORDER_TOPIC_CONFIG";
}
| NamesrvUtil |
java | apache__dubbo | dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/utils/ProtoTypeMap.java | {
"start": 607,
"end": 5769
} | class ____ {
private static final Joiner DOT_JOINER = Joiner.on('.').skipNulls();
private final ImmutableMap<String, String> types;
private ProtoTypeMap(@Nonnull ImmutableMap<String, String> types) {
Preconditions.checkNotNull(types, "types");
this.types = types;
}
public static ProtoTypeMap of(@Nonnull Collection<DescriptorProtos.FileDescriptorProto> fileDescriptorProtos) {
Preconditions.checkNotNull(fileDescriptorProtos, "fileDescriptorProtos");
Preconditions.checkArgument(!fileDescriptorProtos.isEmpty(), "fileDescriptorProtos.isEmpty()");
ImmutableMap.Builder<String, String> types = ImmutableMap.builder();
for (DescriptorProtos.FileDescriptorProto fileDescriptor : fileDescriptorProtos) {
DescriptorProtos.FileOptions fileOptions = fileDescriptor.getOptions();
String protoPackage = fileDescriptor.hasPackage() ? "." + fileDescriptor.getPackage() : "";
String javaPackage = Strings.emptyToNull(fileOptions.hasJavaPackage() ? fileOptions.getJavaPackage() : fileDescriptor.getPackage());
String enclosingClassName = fileOptions.getJavaMultipleFiles() ? null : getJavaOuterClassname(fileDescriptor, fileOptions);
fileDescriptor.getEnumTypeList().forEach((e) -> {
types.put(protoPackage + "." + e.getName(), DOT_JOINER.join(javaPackage, enclosingClassName, new Object[]{e.getName()}));
});
fileDescriptor.getMessageTypeList().forEach((m) -> {
recursivelyAddTypes(types, m, protoPackage, enclosingClassName, javaPackage);
});
}
return new ProtoTypeMap(types.build());
}
private static void recursivelyAddTypes(ImmutableMap.Builder<String, String> types, DescriptorProtos.DescriptorProto m, String protoPackage, String enclosingClassName, String javaPackage) {
String protoTypeName = protoPackage + "." + m.getName();
types.put(protoTypeName, DOT_JOINER.join(javaPackage, enclosingClassName, new Object[]{m.getName()}));
m.getEnumTypeList().forEach((e) -> {
types.put(protoPackage + "." + m.getName() + "." + e.getName(), DOT_JOINER.join(javaPackage, enclosingClassName, new Object[]{m.getName(), e.getName()}));
});
m.getNestedTypeList().forEach((n) -> {
recursivelyAddTypes(types, n, protoPackage + "." + m.getName(), DOT_JOINER.join(enclosingClassName, m.getName(), new Object[0]), javaPackage);
});
}
public String toJavaTypeName(@Nonnull String protoTypeName) {
Preconditions.checkNotNull(protoTypeName, "protoTypeName");
return (String)this.types.get(protoTypeName);
}
public static String getJavaOuterClassname(DescriptorProtos.FileDescriptorProto fileDescriptor, DescriptorProtos.FileOptions fileOptions) {
if (fileOptions.hasJavaOuterClassname()) {
return fileOptions.getJavaOuterClassname();
} else {
String filename = fileDescriptor.getName().substring(0, fileDescriptor.getName().length() - ".proto".length());
if (filename.contains("/")) {
filename = filename.substring(filename.lastIndexOf(47) + 1);
}
filename = makeInvalidCharactersUnderscores(filename);
filename = convertToCamelCase(filename);
filename = appendOuterClassSuffix(filename, fileDescriptor);
return filename;
}
}
private static String appendOuterClassSuffix(String enclosingClassName, DescriptorProtos.FileDescriptorProto fd) {
return !fd.getEnumTypeList().stream().anyMatch((enumProto) -> {
return enumProto.getName().equals(enclosingClassName);
}) && !fd.getMessageTypeList().stream().anyMatch((messageProto) -> {
return messageProto.getName().equals(enclosingClassName);
}) && !fd.getServiceList().stream().anyMatch((serviceProto) -> {
return serviceProto.getName().equals(enclosingClassName);
}) ? enclosingClassName : enclosingClassName + "OuterClass";
}
private static String makeInvalidCharactersUnderscores(String filename) {
char[] filechars = filename.toCharArray();
for(int i = 0; i < filechars.length; ++i) {
char c = filechars[i];
if (!CharMatcher.inRange('0', '9').or(CharMatcher.inRange('A', 'Z')).or(CharMatcher.inRange('a', 'z')).matches(c)) {
filechars[i] = '_';
}
}
return new String(filechars);
}
private static String convertToCamelCase(String name) {
StringBuilder sb = new StringBuilder();
sb.append(Character.toUpperCase(name.charAt(0)));
for(int i = 1; i < name.length(); ++i) {
char c = name.charAt(i);
char prev = name.charAt(i - 1);
if (c != '_') {
if (prev != '_' && !CharMatcher.inRange('0', '9').matches(prev)) {
sb.append(c);
} else {
sb.append(Character.toUpperCase(c));
}
}
}
return sb.toString();
}
}
| ProtoTypeMap |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/aggfunctions/ArrayAggFunctionTest.java | {
"start": 10541,
"end": 12626
} | class ____ extends ArrayAggFunctionTestBase<RowData> {
private RowData getValue(Integer f0, String f1) {
GenericRowData rowData = new GenericRowData(RowKind.INSERT, 2);
rowData.setField(0, f0);
rowData.setField(1, f1 == null ? null : StringData.fromString(f1));
return rowData;
}
@Override
protected List<List<RowData>> getInputValueSets() {
return Arrays.asList(
Arrays.asList(
getValue(0, "abc"),
getValue(1, "def"),
getValue(2, "ghi"),
null,
getValue(3, "jkl"),
null,
getValue(4, "zzz")),
Arrays.asList(null, null),
Arrays.asList(null, getValue(null, "a")),
Arrays.asList(getValue(5, null), null, getValue(null, "e")));
}
@Override
protected List<ArrayData> getExpectedResults() {
return Arrays.asList(
new GenericArrayData(
new Object[] {
getValue(0, "abc"),
getValue(1, "def"),
getValue(2, "ghi"),
getValue(3, "jkl"),
getValue(4, "zzz")
}),
null,
new GenericArrayData(new Object[] {getValue(null, "a")}),
new GenericArrayData(new Object[] {getValue(5, null), getValue(null, "e")}));
}
@Override
protected AggregateFunction<ArrayData, ArrayAggFunction.ArrayAggAccumulator<RowData>>
getAggregator() {
return new ArrayAggFunction<>(
DataTypes.ROW(DataTypes.INT(), DataTypes.STRING()).getLogicalType(), true);
}
}
/** Test for {@link ArrayType}. */
@Nested
final | RowDArrayAggFunctionTest |
java | google__dagger | javatests/dagger/internal/codegen/MissingBindingValidationTest.java | {
"start": 23656,
"end": 23784
} | class ____ {",
" @Inject X() {}",
" }",
"",
" @Module",
" static | X |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/registration/RetryingRegistrationTest.java | {
"start": 19006,
"end": 20766
} | class ____
extends RetryingRegistration<
UUID,
TestRegistrationGateway,
TestRegistrationSuccess,
TestRegistrationRejection> {
// we use shorter timeouts here to speed up the tests
static final long INITIAL_TIMEOUT = 20;
static final long MAX_TIMEOUT = 200;
static final long DELAY_ON_ERROR = 200;
static final long DELAY_ON_FAILURE = 200;
static final RetryingRegistrationConfiguration RETRYING_REGISTRATION_CONFIGURATION =
new RetryingRegistrationConfiguration(
INITIAL_TIMEOUT, MAX_TIMEOUT, DELAY_ON_ERROR, DELAY_ON_FAILURE);
public TestRetryingRegistration(RpcService rpc, String targetAddress, UUID leaderId) {
this(rpc, targetAddress, leaderId, RETRYING_REGISTRATION_CONFIGURATION);
}
public TestRetryingRegistration(
RpcService rpc,
String targetAddress,
UUID leaderId,
RetryingRegistrationConfiguration retryingRegistrationConfiguration) {
super(
LoggerFactory.getLogger(RetryingRegistrationTest.class),
rpc,
"TestEndpoint",
TestRegistrationGateway.class,
targetAddress,
leaderId,
retryingRegistrationConfiguration);
}
@Override
protected CompletableFuture<RegistrationResponse> invokeRegistration(
TestRegistrationGateway gateway, UUID leaderId, long timeoutMillis) {
return gateway.registrationCall(leaderId, timeoutMillis);
}
}
}
| TestRetryingRegistration |
java | netty__netty | common/src/main/java/io/netty/util/concurrent/Ticker.java | {
"start": 792,
"end": 1838
} | interface ____ {
/**
* Returns the singleton {@link Ticker} that returns the values from the real system clock source.
* However, note that this is not the same as {@link System#nanoTime()} because we apply a fixed offset
* to the {@link System#nanoTime() nanoTime}.
*/
static Ticker systemTicker() {
return SystemTicker.INSTANCE;
}
/**
* Returns a newly created mock {@link Ticker} that allows the caller control the flow of time.
* This can be useful when you test time-sensitive logic without waiting for too long or introducing
* flakiness due to non-deterministic nature of system clock.
*/
static MockTicker newMockTicker() {
return new DefaultMockTicker();
}
/**
* The initial value used for delay and computations based upon a monotonic time source.
* @return initial value used for delay and computations based upon a monotonic time source.
*/
long initialNanoTime();
/**
* The time elapsed since initialization of this | Ticker |
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/server/context/ReactorContextWebFilterTests.java | {
"start": 2334,
"end": 6187
} | class ____ {
@Mock
private Authentication principal;
@Mock
private ServerSecurityContextRepository repository;
private MockServerHttpRequest.BaseBuilder<?> exchange = MockServerHttpRequest.get("/");
private TestPublisher<SecurityContext> securityContext = TestPublisher.create();
private ReactorContextWebFilter filter;
private WebTestHandler handler;
@BeforeEach
public void setup() {
this.filter = new ReactorContextWebFilter(this.repository);
this.handler = WebTestHandler.bindToWebFilters(this.filter);
}
@Test
public void constructorNullSecurityContextRepository() {
assertThatIllegalArgumentException().isThrownBy(() -> new ReactorContextWebFilter(null));
}
@Test
public void filterWhenNoPrincipalAccessThenNoInteractions() {
given(this.repository.load(any())).willReturn(this.securityContext.mono());
this.handler.exchange(this.exchange);
this.securityContext.assertWasNotSubscribed();
}
@Test
public void filterWhenGetPrincipalMonoThenNoInteractions() {
given(this.repository.load(any())).willReturn(this.securityContext.mono());
this.handler = WebTestHandler.bindToWebFilters(this.filter, (e, c) -> {
ReactiveSecurityContextHolder.getContext();
return c.filter(e);
});
this.handler.exchange(this.exchange);
this.securityContext.assertWasNotSubscribed();
}
@Test
public void filterWhenPrincipalAndGetPrincipalThenInteractAndUseOriginalPrincipal() {
SecurityContextImpl context = new SecurityContextImpl(this.principal);
given(this.repository.load(any())).willReturn(Mono.just(context));
this.handler = WebTestHandler.bindToWebFilters(this.filter,
(e, c) -> ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.doOnSuccess((p) -> assertThat(p).isSameAs(this.principal))
.flatMap((p) -> c.filter(e)));
WebTestHandler.WebHandlerResult result = this.handler.exchange(this.exchange);
this.securityContext.assertWasNotSubscribed();
}
@Test
// gh-4962
public void filterWhenMainContextThenDoesNotOverride() {
given(this.repository.load(any())).willReturn(this.securityContext.mono());
String contextKey = "main";
WebFilter mainContextWebFilter = (e, c) -> c.filter(e).contextWrite(Context.of(contextKey, true));
WebFilterChain chain = new DefaultWebFilterChain((e) -> Mono.empty(),
List.of(mainContextWebFilter, this.filter));
Mono<Void> filter = chain.filter(MockServerWebExchange.from(this.exchange.build()));
StepVerifier.create(filter).expectAccessibleContext().hasKey(contextKey).then().verifyComplete();
}
@Test
public void filterWhenThreadFactoryIsPlatformThenSecurityContextLoaded() {
ThreadFactory threadFactory = Executors.defaultThreadFactory();
assertSecurityContextLoaded(threadFactory);
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void filterWhenThreadFactoryIsVirtualThenSecurityContextLoaded() {
ThreadFactory threadFactory = new VirtualThreadTaskExecutor().getVirtualThreadFactory();
assertSecurityContextLoaded(threadFactory);
}
private void assertSecurityContextLoaded(ThreadFactory threadFactory) {
SecurityContextImpl context = new SecurityContextImpl(this.principal);
given(this.repository.load(any())).willReturn(Mono.just(context));
// @formatter:off
WebFilter subscribeOnThreadFactory = (exchange, chain) -> chain.filter(exchange)
.subscribeOn(Schedulers.newSingle(threadFactory));
WebFilter assertSecurityContext = (exchange, chain) -> ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.doOnSuccess((authentication) -> assertThat(authentication).isSameAs(this.principal))
.then(chain.filter(exchange));
// @formatter:on
this.handler = WebTestHandler.bindToWebFilters(subscribeOnThreadFactory, this.filter, assertSecurityContext);
this.handler.exchange(this.exchange);
}
}
| ReactorContextWebFilterTests |
java | spring-projects__spring-framework | spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java | {
"start": 24972,
"end": 26099
} | class ____ {
final List<Person> persons = new ArrayList<>();
@PostMapping("/publisher")
Publisher<Void> createWithPublisher(@RequestBody Publisher<Person> publisher) {
return Flux.from(publisher).doOnNext(persons::add).then();
}
@PostMapping("/mono")
Mono<Void> createWithMono(@RequestBody Mono<Person> mono) {
return mono.doOnNext(persons::add).then();
}
@PostMapping("/single")
Completable createWithSingle(@RequestBody Single<Person> single) {
return single.map(persons::add).ignoreElement();
}
@PostMapping("/flux")
Mono<Void> createWithFlux(@RequestBody Flux<Person> flux) {
return flux.doOnNext(persons::add).then();
}
@PostMapping("/observable")
Completable createWithObservable(@RequestBody Observable<Person> observable) {
return observable.toList().doOnSuccess(persons::addAll).ignoreElement();
}
@PostMapping("/flowable")
Completable createWithFlowable(@RequestBody Flowable<Person> flowable) {
return flowable.toList().doOnSuccess(persons::addAll).ignoreElement();
}
}
@XmlRootElement
@SuppressWarnings("unused")
private static | PersonCreateController |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/support/ibatis/SpringIbatisBeanNameAutoProxyCreatorMBean.java | {
"start": 690,
"end": 784
} | interface ____ {
List<String> getProxyBeanNames();
}
| SpringIbatisBeanNameAutoProxyCreatorMBean |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/bootstrap/BootstrapChecks.java | {
"start": 26371,
"end": 27240
} | class ____ extends MightForkCheck {
@Override
boolean mightFork() {
final String onOutOfMemoryError = onOutOfMemoryError();
return onOutOfMemoryError != null && onOutOfMemoryError.isEmpty() == false;
}
// visible for testing
String onOutOfMemoryError() {
return JvmInfo.jvmInfo().onOutOfMemoryError();
}
String message(BootstrapContext context) {
return String.format(
Locale.ROOT,
"OnOutOfMemoryError [%s] requires forking but is prevented by system call filters;"
+ " upgrade to at least Java 8u92 and use ExitOnOutOfMemoryError",
onOutOfMemoryError()
);
}
}
/**
* Bootstrap check for early-access builds from OpenJDK.
*/
static | OnOutOfMemoryErrorCheck |
java | apache__hadoop | hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Folder.java | {
"start": 1484,
"end": 6927
} | class ____ extends Configured implements Tool {
private long outputDuration = -1;
private long inputCycle = -1;
private double concentration = 1.0;
private long randomSeed = 0; // irrelevant if seeded == false
private boolean seeded = false;
private boolean debug = false;
private boolean allowMissorting = false;
private int skewBufferLength = 0;
private long startsAfter = -1;
static final private Logger LOG = LoggerFactory.getLogger(Folder.class);
private DeskewedJobTraceReader reader = null;
private Outputter<LoggedJob> outGen = null;
private List<Path> tempPaths = new LinkedList<Path>();
private Path tempDir = null;
private long firstJobSubmitTime;
private double timeDilation;
private double transcriptionRateFraction;
private int transcriptionRateInteger;
private Random random;
static private final long TICKS_PER_SECOND = 1000L;
// error return codes
static private final int NON_EXISTENT_FILES = 1;
static private final int NO_INPUT_CYCLE_LENGTH = 2;
static private final int EMPTY_JOB_TRACE = 3;
static private final int OUT_OF_ORDER_JOBS = 4;
static private final int ALL_JOBS_SIMULTANEOUS = 5;
static private final int IO_ERROR = 6;
static private final int OTHER_ERROR = 7;
private Set<Closeable> closees = new HashSet<Closeable>();
private Set<Path> deletees = new HashSet<Path>();
static long parseDuration(String durationString) {
String numeral = durationString.substring(0, durationString.length() - 1);
char durationCode = durationString.charAt(durationString.length() - 1);
long result = Integer.parseInt(numeral);
if (result <= 0) {
throw new IllegalArgumentException("Negative durations are not allowed");
}
switch (durationCode) {
case 'D':
case 'd':
return 24L * 60L * 60L * TICKS_PER_SECOND * result;
case 'H':
case 'h':
return 60L * 60L * TICKS_PER_SECOND * result;
case 'M':
case 'm':
return 60L * TICKS_PER_SECOND * result;
case 'S':
case 's':
return TICKS_PER_SECOND * result;
default:
throw new IllegalArgumentException("Missing or invalid duration code");
}
}
private int initialize(String[] args) throws IllegalArgumentException {
String tempDirName = null;
String inputPathName = null;
String outputPathName = null;
for (int i = 0; i < args.length; ++i) {
String thisArg = args[i];
if (thisArg.equalsIgnoreCase("-starts-after")) {
startsAfter = parseDuration(args[++i]);
} else if (thisArg.equalsIgnoreCase("-output-duration")) {
outputDuration = parseDuration(args[++i]);
} else if (thisArg.equalsIgnoreCase("-input-cycle")) {
inputCycle = parseDuration(args[++i]);
} else if (thisArg.equalsIgnoreCase("-concentration")) {
concentration = Double.parseDouble(args[++i]);
} else if (thisArg.equalsIgnoreCase("-debug")) {
debug = true;
} else if (thisArg.equalsIgnoreCase("-allow-missorting")) {
allowMissorting = true;
} else if (thisArg.equalsIgnoreCase("-seed")) {
seeded = true;
randomSeed = Long.parseLong(args[++i]);
} else if (thisArg.equalsIgnoreCase("-skew-buffer-length")) {
skewBufferLength = Integer.parseInt(args[++i]);
} else if (thisArg.equalsIgnoreCase("-temp-directory")) {
tempDirName = args[++i];
} else if (thisArg.equals("") || thisArg.startsWith("-")) {
throw new IllegalArgumentException("Illegal switch argument, "
+ thisArg + " at position " + i);
} else {
inputPathName = thisArg;
outputPathName = args[++i];
if (i != args.length - 1) {
throw new IllegalArgumentException("Too many non-switch arguments");
}
}
}
try {
Configuration conf = getConf();
Path inPath = new Path(inputPathName);
reader =
new DeskewedJobTraceReader(new JobTraceReader(inPath, conf),
skewBufferLength, !allowMissorting);
Path outPath = new Path(outputPathName);
outGen = new DefaultOutputter<LoggedJob>();
outGen.init(outPath, conf);
tempDir =
tempDirName == null ? outPath.getParent() : new Path(tempDirName);
FileSystem fs = tempDir.getFileSystem(getConf());
if (!fs.getFileStatus(tempDir).isDirectory()) {
throw new IOException("Your temp directory is not a directory");
}
if (inputCycle <= 0) {
LOG.error("You must have an input cycle length.");
return NO_INPUT_CYCLE_LENGTH;
}
if (outputDuration <= 0) {
outputDuration = 60L * 60L * TICKS_PER_SECOND;
}
if (inputCycle <= 0) {
inputCycle = outputDuration;
}
timeDilation = (double) outputDuration / (double) inputCycle;
random = seeded ? new Random(randomSeed) : new Random();
if (debug) {
randomSeed = random.nextLong();
LOG.warn("This run effectively has a -seed of " + randomSeed);
random = new Random(randomSeed);
seeded = true;
}
} catch (IOException e) {
e.printStackTrace(System.err);
return NON_EXISTENT_FILES;
}
return 0;
}
@Override
public int run(String[] args) throws IOException {
int result = initialize(args);
if (result != 0) {
return result;
}
return run();
}
public int run() throws IOException {
| Folder |
java | quarkusio__quarkus | extensions/devservices/deployment/src/main/java/io/quarkus/devservices/deployment/compose/ComposeServiceDefinition.java | {
"start": 371,
"end": 2292
} | class ____ {
private final String serviceName;
private final Map<String, ?> definitionMap;
public ComposeServiceDefinition(String serviceName, Map<String, ?> definitionMap) {
this.serviceName = serviceName;
this.definitionMap = definitionMap;
}
public String getServiceName() {
return serviceName;
}
public String getContainerName() {
return (String) definitionMap.get("container_name");
}
public List<ExposedPort> getPorts() {
List<String> ports = (List<String>) definitionMap.get("ports");
if (ports == null) {
return Collections.emptyList();
}
return ports.stream().map(PortBinding::parse)
.map(PortBinding::getExposedPort)
.collect(Collectors.toList());
}
public boolean hasHealthCheck() {
return definitionMap.get("healthcheck") instanceof Map;
}
public Map<String, Object> getLabels() {
Object labels = definitionMap.get("labels");
if (labels instanceof List) {
Map<String, Object> map = new HashMap<>();
for (Object label : ((List<?>) labels)) {
if (label instanceof String) {
String[] split = ((String) label).split("=");
map.put(split[0], split[1]);
} else if (label instanceof Map) {
map.putAll((Map<String, Object>) label);
}
}
return map;
} else if (labels instanceof Map) {
return new HashMap<>((Map<String, Object>) labels);
}
return Collections.emptyMap();
}
public List<String> getProfiles() {
Object profiles = definitionMap.get("profiles");
if (profiles instanceof List) {
return (List<String>) profiles;
}
return Collections.emptyList();
}
}
| ComposeServiceDefinition |
java | apache__camel | components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/AbstractApprovalManualIT.java | {
"start": 1335,
"end": 3592
} | class ____ extends AbstractSalesforceTestBase {
protected static final Object NOT_USED = null;
protected List<String> accountIds = Collections.emptyList();
protected String userId;
private final int accountCount;
AbstractApprovalManualIT(final int accountCount) {
this.accountCount = accountCount;
}
@BeforeEach
public void createAccounts() {
final List<Account> accountsToCreate = IntStream.range(0, accountCount + 1).mapToObj(idx -> {
final String name = "test-account-" + idx;
final Account account = new Account();
account.setName(name);
return account;
}).collect(Collectors.toList());
accountIds = accountsToCreate.stream()
.map(account -> template.requestBody("salesforce:createSObject?sObjectName=Account", account,
CreateSObjectResult.class))
.map(CreateSObjectResult::getId).collect(Collectors.toList());
}
@AfterEach
public void deleteAccounts() {
accountIds.forEach(id -> template.sendBody("salesforce:deleteSObject?sObjectName=Account", id));
}
@BeforeEach
public void setupUserId() throws IOException {
final SalesforceLoginConfig loginConfig = LoginConfigHelper.getLoginConfig();
final String userName = loginConfig.getUserName();
// I happen to have a username (e-mail address) with '+' sign in it,
// DefaultRestClient#urlEncode would encode '+' as '%20' and the query
// would not return any result, so replacing '+' with '%' and '=' with
// 'LIKE' makes sense in my case. It should also work for every other
// case where '+' is not used as a part of the username.
final String wildcardUsername = userName.replace('+', '%');
final QueryRecordsReport results = template
.requestBody("salesforce:query?sObjectClass=" + QueryRecordsReport.class.getName()//
+ "&sObjectQuery=SELECT Id FROM User WHERE Username LIKE '" + wildcardUsername + "'",
NOT_USED,
QueryRecordsReport.class);
userId = results.getRecords().get(0).getId();
}
}
| AbstractApprovalManualIT |
java | netty__netty | transport/src/test/java/io/netty/channel/embedded/EmbeddedChannelIdTest.java | {
"start": 1062,
"end": 1999
} | class ____ {
@Test
public void testSerialization() throws IOException, ClassNotFoundException {
// test that a deserialized instance works the same as a normal instance (issue #2869)
ChannelId normalInstance = EmbeddedChannelId.INSTANCE;
ByteBuf buf = Unpooled.buffer();
try (ObjectOutputStream outStream = new ObjectOutputStream(new ByteBufOutputStream(buf))) {
outStream.writeObject(normalInstance);
}
final ChannelId deserializedInstance;
try (ObjectInputStream inStream = new ObjectInputStream(new ByteBufInputStream(buf, true))) {
deserializedInstance = (ChannelId) inStream.readObject();
}
assertEquals(normalInstance, deserializedInstance);
assertEquals(normalInstance.hashCode(), deserializedInstance.hashCode());
assertEquals(0, normalInstance.compareTo(deserializedInstance));
}
}
| EmbeddedChannelIdTest |
java | netty__netty | codec-http3/src/main/java/io/netty/handler/codec/http3/Http3RequestStreamEncodeStateValidator.java | {
"start": 1010,
"end": 1147
} | class ____ extends ChannelOutboundHandlerAdapter
implements Http3RequestStreamCodecState {
| Http3RequestStreamEncodeStateValidator |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreResponseTests.java | {
"start": 1780,
"end": 7519
} | class ____ extends ESTestCase {
public void testBasicSerialization() throws Exception {
DiscoveryNode node1 = DiscoveryNodeUtils.builder("node1").roles(emptySet()).build();
DiscoveryNode node2 = DiscoveryNodeUtils.builder("node2").roles(emptySet()).build();
List<StoreStatus> storeStatusList = List.of(
new StoreStatus(node1, null, AllocationStatus.PRIMARY, null),
new StoreStatus(node2, UUIDs.randomBase64UUID(), AllocationStatus.REPLICA, null),
new StoreStatus(node1, UUIDs.randomBase64UUID(), AllocationStatus.UNUSED, new IOException("corrupted"))
);
Map<Integer, List<StoreStatus>> storeStatuses = Map.of(0, storeStatusList, 1, storeStatusList);
var indexStoreStatuses = Map.of("test", storeStatuses, "test2", storeStatuses);
var failures = List.of(new Failure("node1", "test", 3, new NodeDisconnectedException(node1, "")));
var storesResponse = new IndicesShardStoresResponse(indexStoreStatuses, failures);
AbstractChunkedSerializingTestCase.assertChunkCount(storesResponse, this::getExpectedChunkCount);
XContentBuilder contentBuilder = XContentFactory.jsonBuilder();
ChunkedToXContent.wrapAsToXContent(storesResponse).toXContent(contentBuilder, ToXContent.EMPTY_PARAMS);
BytesReference bytes = BytesReference.bytes(contentBuilder);
try (XContentParser parser = createParser(JsonXContent.jsonXContent, bytes)) {
Map<String, Object> map = parser.map();
List<?> failureList = (List<?>) map.get("failures");
assertThat(failureList.size(), equalTo(1));
@SuppressWarnings("unchecked")
Map<String, ?> failureMap = (Map<String, ?>) failureList.get(0);
assertThat(failureMap.containsKey("index"), equalTo(true));
assertThat(((String) failureMap.get("index")), equalTo("test"));
assertThat(failureMap.containsKey("shard"), equalTo(true));
assertThat(((int) failureMap.get("shard")), equalTo(3));
assertThat(failureMap.containsKey("node"), equalTo(true));
assertThat(((String) failureMap.get("node")), equalTo("node1"));
@SuppressWarnings("unchecked")
Map<String, Object> indices = (Map<String, Object>) map.get("indices");
for (String index : new String[] { "test", "test2" }) {
assertThat(indices.containsKey(index), equalTo(true));
@SuppressWarnings("unchecked")
Map<String, Object> shards = ((Map<String, Object>) ((Map<String, Object>) indices.get(index)).get("shards"));
assertThat(shards.size(), equalTo(2));
for (String shardId : shards.keySet()) {
@SuppressWarnings("unchecked")
Map<String, ?> shardStoresStatus = (Map<String, ?>) shards.get(shardId);
assertThat(shardStoresStatus.containsKey("stores"), equalTo(true));
List<?> stores = (List<?>) shardStoresStatus.get("stores");
assertThat(stores.size(), equalTo(storeStatusList.size()));
for (int i = 0; i < stores.size(); i++) {
@SuppressWarnings("unchecked")
Map<String, ?> storeInfo = ((Map<String, ?>) stores.get(i));
StoreStatus storeStatus = storeStatusList.get(i);
assertThat(((String) storeInfo.get("allocation_id")), equalTo((storeStatus.getAllocationId())));
assertThat(storeInfo.containsKey("allocation"), equalTo(true));
assertThat(((String) storeInfo.get("allocation")), equalTo(storeStatus.getAllocationStatus().value()));
assertThat(storeInfo.containsKey(storeStatus.getNode().getId()), equalTo(true));
if (storeStatus.getStoreException() != null) {
assertThat(storeInfo.containsKey("store_exception"), equalTo(true));
}
}
}
}
}
}
private int getExpectedChunkCount(IndicesShardStoresResponse response) {
return 6 + response.getFailures().size() + response.getStoreStatuses().values().stream().mapToInt(m -> 4 + m.size()).sum();
}
public void testStoreStatusOrdering() throws Exception {
DiscoveryNode node1 = DiscoveryNodeUtils.builder("node1").roles(emptySet()).build();
List<StoreStatus> orderedStoreStatuses = new ArrayList<>();
orderedStoreStatuses.add(new StoreStatus(node1, UUIDs.randomBase64UUID(), AllocationStatus.PRIMARY, null));
orderedStoreStatuses.add(new StoreStatus(node1, UUIDs.randomBase64UUID(), AllocationStatus.REPLICA, null));
orderedStoreStatuses.add(new StoreStatus(node1, UUIDs.randomBase64UUID(), AllocationStatus.UNUSED, null));
orderedStoreStatuses.add(new StoreStatus(node1, null, AllocationStatus.PRIMARY, null));
orderedStoreStatuses.add(new StoreStatus(node1, null, AllocationStatus.REPLICA, null));
orderedStoreStatuses.add(new StoreStatus(node1, null, AllocationStatus.UNUSED, null));
orderedStoreStatuses.add(new StoreStatus(node1, UUIDs.randomBase64UUID(), AllocationStatus.REPLICA, new IOException("corrupted")));
orderedStoreStatuses.add(new StoreStatus(node1, null, AllocationStatus.REPLICA, new IOException("corrupted")));
List<StoreStatus> storeStatuses = new ArrayList<>(orderedStoreStatuses);
Collections.shuffle(storeStatuses, random());
CollectionUtil.timSort(storeStatuses);
assertThat(storeStatuses, equalTo(orderedStoreStatuses));
}
}
| IndicesShardStoreResponseTests |
java | quarkusio__quarkus | extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java | {
"start": 84134,
"end": 84321
} | class ____ implements BooleanSupplier {
@Override
public boolean getAsBoolean() {
return true;
}
}
private static | AlwaysCreateBodyHandlerSupplier |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/load/resource/transcode/BitmapBytesTranscoder.java | {
"start": 623,
"end": 1423
} | class ____ implements ResourceTranscoder<Bitmap, byte[]> {
private final Bitmap.CompressFormat compressFormat;
private final int quality;
public BitmapBytesTranscoder() {
this(Bitmap.CompressFormat.JPEG, 100);
}
// Public API.
@SuppressWarnings("WeakerAccess")
public BitmapBytesTranscoder(@NonNull Bitmap.CompressFormat compressFormat, int quality) {
this.compressFormat = compressFormat;
this.quality = quality;
}
@Nullable
@Override
public Resource<byte[]> transcode(
@NonNull Resource<Bitmap> toTranscode, @NonNull Options options) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
toTranscode.get().compress(compressFormat, quality, os);
toTranscode.recycle();
return new BytesResource(os.toByteArray());
}
}
| BitmapBytesTranscoder |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/annotations/Consume.java | {
"start": 780,
"end": 943
} | interface ____ {
/**
* The {@link Consume} instances.
*
* @return the instances
*/
Consume[] value();
}
}
| List |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/AvroFSInput.java | {
"start": 1459,
"end": 2793
} | class ____ implements Closeable, SeekableInput {
private final FSDataInputStream stream;
private final long len;
/**
* Construct given an {@link FSDataInputStream} and its length.
*
* @param in inputstream.
* @param len len.
*/
public AvroFSInput(final FSDataInputStream in, final long len) {
this.stream = in;
this.len = len;
}
/** Construct given a {@link FileContext} and a {@link Path}.
* @param fc filecontext.
* @param p the path.
* @throws IOException If an I/O error occurred.
* */
public AvroFSInput(final FileContext fc, final Path p) throws IOException {
FileStatus status = fc.getFileStatus(p);
this.len = status.getLen();
this.stream = awaitFuture(fc.openFile(p)
.opt(FS_OPTION_OPENFILE_READ_POLICY,
FS_OPTION_OPENFILE_READ_POLICY_SEQUENTIAL)
.withFileStatus(status)
.build());
}
@Override
public long length() {
return len;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return stream.read(b, off, len);
}
@Override
public void seek(long p) throws IOException {
stream.seek(p);
}
@Override
public long tell() throws IOException {
return stream.getPos();
}
@Override
public void close() throws IOException {
stream.close();
}
}
| AvroFSInput |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/autodetect/writer/AutodetectControlMsgWriter.java | {
"start": 1505,
"end": 12009
} | class ____ extends AbstractControlMsgWriter {
/**
* This must match the code defined in the api::CFieldDataCategorizer C++ class.
*/
private static final String CATEGORIZATION_STOP_ON_WARN_MESSAGE_CODE = "c";
/**
* This must match the code defined in the api::CAnomalyJob C++ class.
*/
private static final String FLUSH_MESSAGE_CODE = "f";
/**
* This must match the code defined in the api::CAnomalyJob C++ class.
*/
private static final String INTERIM_MESSAGE_CODE = "i";
/**
* This must match the code defined in the api::CAnomalyJob C++ class.
*/
private static final String FORECAST_MESSAGE_CODE = "p";
/**
* This must match the code defined in the api::CAnomalyJob C++ class.
*/
public static final String RESET_BUCKETS_MESSAGE_CODE = "r";
/**
* This must match the code defined in the api::CAnomalyJob C++ class.
*/
private static final String ADVANCE_TIME_MESSAGE_CODE = "t";
/**
* This must match the code defined in the api::CAnomalyJob C++ class.
*/
private static final String SKIP_TIME_MESSAGE_CODE = "s";
/**
* This must match the code defined in the api::CAnomalyJob C++ class.
*/
public static final String UPDATE_MESSAGE_CODE = "u";
/**
* This must match the code defined in the api::CAnomalyJob C++ class.
*/
public static final String BACKGROUND_PERSIST_MESSAGE_CODE = "w";
/**
* This must match the code defined in the api::CAnomalyJob C++ class.
*/
public static final String REFRESH_REQUIRED_MESSAGE_CODE = "z";
/**
* An number to uniquely identify each flush so that subsequent code can
* wait for acknowledgement of the correct flush.
*/
private static AtomicLong flushIdCounter = new AtomicLong(1);
/**
* This field name must match that in the api::CAnomalyJobConfig C++ class.
*/
private static final String DETECTOR_INDEX = "detector_index";
/**
* This field name must match that in the api::CAnomalyJobConfig C++ class.
*/
private static final String CUSTOM_RULES = "custom_rules";
/**
* This field name must match that in the api::CAnomalyJobConfig C++ class.
*/
private static final String DETECTOR_RULES = "detector_rules";
/**
* Construct the control message writer with a LengthEncodedWriter
*
* @param lengthEncodedWriter The writer
* @param numberOfFields The number of fields the process expects in each record
*/
public AutodetectControlMsgWriter(LengthEncodedWriter lengthEncodedWriter, int numberOfFields) {
super(lengthEncodedWriter, numberOfFields);
}
/**
* Create the control message writer with a OutputStream. A
* LengthEncodedWriter is created on the OutputStream parameter
*
* @param os The output stream
* @param numberOfFields The number of fields the process expects in each record
*/
public static AutodetectControlMsgWriter create(OutputStream os, int numberOfFields) {
return new AutodetectControlMsgWriter(new LengthEncodedWriter(os), numberOfFields);
}
/**
* Writes the control messages that are requested when flushing a job.
* Those control messages need to be followed by a flush message in order
* for them to reach the C++ process immediately. List of supported controls:
*
* <ul>
* <li>advance time</li>
* <li>calculate interim results</li>
* </ul>
*
* @param params Parameters describing the controls that will accompany the flushing
* (e.g. calculating interim results, time control, etc.)
*/
public void writeFlushControlMessage(FlushJobParams params) throws IOException {
if (params.shouldSkipTime()) {
writeMessage(SKIP_TIME_MESSAGE_CODE + params.getSkipTime());
}
if (params.shouldAdvanceTime()) {
writeMessage(ADVANCE_TIME_MESSAGE_CODE + params.getAdvanceTime());
}
if (params.shouldCalculateInterim()) {
writeControlCodeFollowedByTimeRange(INTERIM_MESSAGE_CODE, params.getStart(), params.getEnd());
}
writeMessage(REFRESH_REQUIRED_MESSAGE_CODE + params.isRefreshRequired());
}
/**
* Send a flush message to the C++ autodetect process.
* This actually consists of two messages: one to carry the flush ID and the
* other (which might not be processed until much later) to fill the buffers
* and force prior messages through.
*
* @return an ID for this flush that will be echoed back by the C++
* autodetect process once it is complete.
*/
public String writeFlushMessage() throws IOException {
String flushId = Long.toString(flushIdCounter.getAndIncrement());
writeMessage(FLUSH_MESSAGE_CODE + flushId);
fillCommandBuffer();
lengthEncodedWriter.flush();
return flushId;
}
public void writeForecastMessage(ForecastParams params) throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
builder.field("forecast_id", params.getForecastId());
builder.field("create_time", params.getCreateTime());
if (params.getDuration() != 0) {
builder.field("duration", params.getDuration());
}
if (params.getExpiresIn() != -1) {
builder.field("expires_in", params.getExpiresIn());
}
if (params.getTmpStorage() != null) {
builder.field("tmp_storage", params.getTmpStorage());
}
if (params.getMaxModelMemory() != null) {
builder.field("max_model_memory", params.getMaxModelMemory());
}
if (params.getMinAvailableDiskSpace() != null) {
builder.field("min_available_disk_space", params.getMinAvailableDiskSpace());
}
builder.endObject();
writeMessage(FORECAST_MESSAGE_CODE + Strings.toString(builder));
fillCommandBuffer();
lengthEncodedWriter.flush();
}
public void writeResetBucketsMessage(DataLoadParams params) throws IOException {
writeControlCodeFollowedByTimeRange(RESET_BUCKETS_MESSAGE_CODE, params.getStart(), params.getEnd());
}
private void writeControlCodeFollowedByTimeRange(String code, String start, String end) throws IOException {
StringBuilder message = new StringBuilder(code);
if (start.isEmpty() == false) {
message.append(start);
message.append(' ');
message.append(end);
}
writeMessage(message.toString());
}
public void writeUpdateModelPlotMessage(ModelPlotConfig modelPlotConfig) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(UPDATE_MESSAGE_CODE);
try (XContentBuilder jsonBuilder = JsonXContent.contentBuilder()) {
jsonBuilder.startObject();
jsonBuilder.field(ModelPlotConfig.TYPE_FIELD.getPreferredName(), modelPlotConfig);
jsonBuilder.endObject();
String msg = Strings.toString(jsonBuilder);
stringBuilder.append(msg);
}
writeMessage(stringBuilder.toString());
}
public void writeCategorizationStopOnWarnMessage(boolean isStopOnWarn) throws IOException {
writeMessage(CATEGORIZATION_STOP_ON_WARN_MESSAGE_CODE + isStopOnWarn);
}
public void writeUpdateDetectorRulesMessage(int detectorIndex, List<DetectionRule> rules) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(UPDATE_MESSAGE_CODE);
try (XContentBuilder builder = JsonXContent.contentBuilder()) {
builder.startObject();
builder.field(DETECTOR_RULES).startObject();
builder.field(DETECTOR_INDEX, detectorIndex);
builder.field(CUSTOM_RULES, rules);
builder.endObject();
builder.endObject();
stringBuilder.append(Strings.toString(builder));
}
writeMessage(stringBuilder.toString());
}
public void writeUpdateFiltersMessage(List<MlFilter> filters) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(UPDATE_MESSAGE_CODE);
try (XContentBuilder jsonBuilder = JsonXContent.contentBuilder()) {
jsonBuilder.startObject().field(MlFilter.RESULTS_FIELD.getPreferredName(), filters).endObject();
String msg = Strings.toString(jsonBuilder);
stringBuilder.append(msg);
}
writeMessage(stringBuilder.toString());
}
public void writeUpdateScheduledEventsMessage(List<ScheduledEvent> events, TimeValue bucketSpan) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(UPDATE_MESSAGE_CODE);
List<ScheduledEventToRuleWriter> scheduledEventToRuleWriters = events.stream()
.map(x -> new ScheduledEventToRuleWriter(x.getDescription(), x.toDetectionRule(bucketSpan)))
.collect(Collectors.toList());
try (XContentBuilder jsonBuilder = JsonXContent.contentBuilder()) {
jsonBuilder.startObject().field(ScheduledEvent.RESULTS_FIELD.getPreferredName(), scheduledEventToRuleWriters).endObject();
String msg = Strings.toString(jsonBuilder);
stringBuilder.append(msg);
}
writeMessage(stringBuilder.toString());
}
public void writeStartBackgroundPersistMessage() throws IOException {
writeMessage(BACKGROUND_PERSIST_MESSAGE_CODE);
fillCommandBuffer();
lengthEncodedWriter.flush();
}
/**
* @param snapshotTimestampMs The snapshot timestamp with MILLISECONDS resolution
* @param snapshotId The snapshot ID
* @param description The snapshot description
*/
public void writeStartBackgroundPersistMessage(long snapshotTimestampMs, String snapshotId, String description) throws IOException {
StringBuilder stringBuilder = new StringBuilder(BACKGROUND_PERSIST_MESSAGE_CODE);
stringBuilder.append(snapshotTimestampMs / 1000).append(" ").append(snapshotId);
if (description != null) {
stringBuilder.append(" ").append(description);
}
writeMessage(stringBuilder.toString());
fillCommandBuffer();
lengthEncodedWriter.flush();
}
}
| AutodetectControlMsgWriter |
java | quarkusio__quarkus | integration-tests/hibernate-orm-panache/src/test/java/io/quarkus/it/panache/defaultpu/PanacheRepositoryBaseTest.java | {
"start": 176,
"end": 321
} | class ____ {
@Test
public void test() {
RestAssured.when().get("/users/1").then().statusCode(404);
}
}
| PanacheRepositoryBaseTest |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/metrics/RpcMetrics.java | {
"start": 8147,
"end": 8518
} | enum ____"
+ " of java.util.concurrent.TimeUnit. Hence default unit"
+ " {} will be used",
CommonConfigurationKeys.RPC_METRICS_TIME_UNIT, timeunit,
RpcMetrics.DEFAULT_METRIC_TIME_UNIT);
}
}
return metricsTimeUnit;
}
// Public instrumentation methods that could be extracted to an
// abstract | values |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/builditem/LaunchModeBuildItem.java | {
"start": 250,
"end": 2379
} | class ____ extends SimpleBuildItem {
private final LaunchMode launchMode;
private final Optional<DevModeType> devModeType;
private final boolean auxiliaryApplication;
private final Optional<DevModeType> auxiliaryDevModeType;
private final boolean test;
public LaunchModeBuildItem(LaunchMode launchMode, Optional<DevModeType> devModeType, boolean auxiliaryApplication,
Optional<DevModeType> auxiliaryDevModeType, boolean test) {
this.launchMode = launchMode;
this.devModeType = devModeType;
this.auxiliaryApplication = auxiliaryApplication;
this.auxiliaryDevModeType = auxiliaryDevModeType;
this.test = test;
}
public LaunchMode getLaunchMode() {
return launchMode;
}
/**
* The development mode type.
* <p>
* Note that even for NORMAL launch modes this could be generating an application for the local side of remote
* dev mode, so this may be set even for launch mode normal.
*/
public Optional<DevModeType> getDevModeType() {
return devModeType;
}
/**
* Whether the development mode type is not local.
*
* @return true if {@link #getDevModeType()} is not {@link DevModeType#LOCAL}
*/
public boolean isNotLocalDevModeType() {
return devModeType.orElse(null) != DevModeType.LOCAL;
}
/**
* An Auxiliary Application is a second application running in the same JVM as a primary application.
* <p>
* Currently, this is done to allow running tests in dev mode, while the main dev mode process continues to
* run.
*/
public boolean isAuxiliaryApplication() {
return auxiliaryApplication;
}
/**
* The dev mode type of the main application.
*/
public Optional<DevModeType> getAuxiliaryDevModeType() {
return auxiliaryDevModeType;
}
/**
* If this is a test. Dev mode tests don't launch with a launch mode TEST, so this
* can be used to determine if we are in a dev mode test.
*/
public boolean isTest() {
return test;
}
}
| LaunchModeBuildItem |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/utils/TableConfigUtils.java | {
"start": 4447,
"end": 4489
} | class
____ TableConfigUtils() {}
}
| private |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/scheduling/TaskScheduler.java | {
"start": 1973,
"end": 12944
} | interface ____ {
/**
* Return the clock to use for scheduling purposes.
* @since 5.3
* @see Clock#systemDefaultZone()
*/
default Clock getClock() {
return Clock.systemDefaultZone();
}
/**
* Schedule the given {@link Runnable}, invoking it whenever the trigger
* indicates a next execution time.
* <p>Execution will end once the scheduler shuts down or the returned
* {@link ScheduledFuture} gets cancelled.
* @param task the Runnable to execute whenever the trigger fires
* @param trigger an implementation of the {@link Trigger} interface,
* for example, a {@link org.springframework.scheduling.support.CronTrigger} object
* wrapping a cron expression
* @return a {@link ScheduledFuture} representing pending execution of the task,
* or {@code null} if the given Trigger object never fires (i.e. returns
* {@code null} from {@link Trigger#nextExecution})
* @throws org.springframework.core.task.TaskRejectedException if the given task was not accepted
* for internal reasons (for example, a pool overload handling policy or a pool shutdown in progress)
* @see org.springframework.scheduling.support.CronTrigger
*/
@Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger);
/**
* Schedule the given {@link Runnable}, invoking it at the specified execution time.
* <p>Execution will end once the scheduler shuts down or the returned
* {@link ScheduledFuture} gets cancelled.
* @param task the Runnable to execute whenever the trigger fires
* @param startTime the desired execution time for the task
* (if this is in the past, the task will be executed immediately, i.e. as soon as possible)
* @return a {@link ScheduledFuture} representing pending execution of the task
* @throws org.springframework.core.task.TaskRejectedException if the given task was not accepted
* for internal reasons (for example, a pool overload handling policy or a pool shutdown in progress)
* @since 5.0
*/
ScheduledFuture<?> schedule(Runnable task, Instant startTime);
/**
* Schedule the given {@link Runnable}, invoking it at the specified execution time.
* <p>Execution will end once the scheduler shuts down or the returned
* {@link ScheduledFuture} gets cancelled.
* @param task the Runnable to execute whenever the trigger fires
* @param startTime the desired execution time for the task
* (if this is in the past, the task will be executed immediately, i.e. as soon as possible)
* @return a {@link ScheduledFuture} representing pending execution of the task
* @throws org.springframework.core.task.TaskRejectedException if the given task was not accepted
* for internal reasons (for example, a pool overload handling policy or a pool shutdown in progress)
* @deprecated as of 6.0, in favor of {@link #schedule(Runnable, Instant)}
*/
@Deprecated(since = "6.0")
default ScheduledFuture<?> schedule(Runnable task, Date startTime) {
return schedule(task, startTime.toInstant());
}
/**
* Schedule the given {@link Runnable}, invoking it at the specified execution time
* and subsequently with the given period.
* <p>Execution will end once the scheduler shuts down or the returned
* {@link ScheduledFuture} gets cancelled.
* @param task the Runnable to execute whenever the trigger fires
* @param startTime the desired first execution time for the task
* (if this is in the past, the task will be executed immediately, i.e. as soon as possible)
* @param period the interval between successive executions of the task
* @return a {@link ScheduledFuture} representing pending execution of the task
* @throws org.springframework.core.task.TaskRejectedException if the given task was not accepted
* for internal reasons (for example, a pool overload handling policy or a pool shutdown in progress)
* @since 5.0
*/
ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period);
/**
* Schedule the given {@link Runnable}, invoking it at the specified execution time
* and subsequently with the given period.
* <p>Execution will end once the scheduler shuts down or the returned
* {@link ScheduledFuture} gets cancelled.
* @param task the Runnable to execute whenever the trigger fires
* @param startTime the desired first execution time for the task
* (if this is in the past, the task will be executed immediately, i.e. as soon as possible)
* @param period the interval between successive executions of the task (in milliseconds)
* @return a {@link ScheduledFuture} representing pending execution of the task
* @throws org.springframework.core.task.TaskRejectedException if the given task was not accepted
* for internal reasons (for example, a pool overload handling policy or a pool shutdown in progress)
* @deprecated as of 6.0, in favor of {@link #scheduleAtFixedRate(Runnable, Instant, Duration)}
*/
@Deprecated(since = "6.0")
default ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
return scheduleAtFixedRate(task, startTime.toInstant(), Duration.ofMillis(period));
}
/**
* Schedule the given {@link Runnable}, starting as soon as possible and
* invoking it with the given period.
* <p>Execution will end once the scheduler shuts down or the returned
* {@link ScheduledFuture} gets cancelled.
* @param task the Runnable to execute whenever the trigger fires
* @param period the interval between successive executions of the task
* @return a {@link ScheduledFuture} representing pending execution of the task
* @throws org.springframework.core.task.TaskRejectedException if the given task was not accepted
* for internal reasons (for example, a pool overload handling policy or a pool shutdown in progress)
* @since 5.0
*/
ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period);
/**
* Schedule the given {@link Runnable}, starting as soon as possible and
* invoking it with the given period.
* <p>Execution will end once the scheduler shuts down or the returned
* {@link ScheduledFuture} gets cancelled.
* @param task the Runnable to execute whenever the trigger fires
* @param period the interval between successive executions of the task (in milliseconds)
* @return a {@link ScheduledFuture} representing pending execution of the task
* @throws org.springframework.core.task.TaskRejectedException if the given task was not accepted
* for internal reasons (for example, a pool overload handling policy or a pool shutdown in progress)
* @deprecated as of 6.0, in favor of {@link #scheduleAtFixedRate(Runnable, Duration)}
*/
@Deprecated(since = "6.0")
default ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
return scheduleAtFixedRate(task, Duration.ofMillis(period));
}
/**
* Schedule the given {@link Runnable}, invoking it at the specified execution time
* and subsequently with the given delay between the completion of one execution
* and the start of the next.
* <p>Execution will end once the scheduler shuts down or the returned
* {@link ScheduledFuture} gets cancelled.
* @param task the Runnable to execute whenever the trigger fires
* @param startTime the desired first execution time for the task
* (if this is in the past, the task will be executed immediately, i.e. as soon as possible)
* @param delay the delay between the completion of one execution and the start of the next
* @return a {@link ScheduledFuture} representing pending execution of the task
* @throws org.springframework.core.task.TaskRejectedException if the given task was not accepted
* for internal reasons (for example, a pool overload handling policy or a pool shutdown in progress)
* @since 5.0
*/
ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime, Duration delay);
/**
* Schedule the given {@link Runnable}, invoking it at the specified execution time
* and subsequently with the given delay between the completion of one execution
* and the start of the next.
* <p>Execution will end once the scheduler shuts down or the returned
* {@link ScheduledFuture} gets cancelled.
* @param task the Runnable to execute whenever the trigger fires
* @param startTime the desired first execution time for the task
* (if this is in the past, the task will be executed immediately, i.e. as soon as possible)
* @param delay the delay between the completion of one execution and the start of the next
* (in milliseconds)
* @return a {@link ScheduledFuture} representing pending execution of the task
* @throws org.springframework.core.task.TaskRejectedException if the given task was not accepted
* for internal reasons (for example, a pool overload handling policy or a pool shutdown in progress)
* @deprecated as of 6.0, in favor of {@link #scheduleWithFixedDelay(Runnable, Instant, Duration)}
*/
@Deprecated(since = "6.0")
default ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay) {
return scheduleWithFixedDelay(task, startTime.toInstant(), Duration.ofMillis(delay));
}
/**
* Schedule the given {@link Runnable}, starting as soon as possible and invoking it with
* the given delay between the completion of one execution and the start of the next.
* <p>Execution will end once the scheduler shuts down or the returned
* {@link ScheduledFuture} gets cancelled.
* @param task the Runnable to execute whenever the trigger fires
* @param delay the delay between the completion of one execution and the start of the next
* @return a {@link ScheduledFuture} representing pending execution of the task
* @throws org.springframework.core.task.TaskRejectedException if the given task was not accepted
* for internal reasons (for example, a pool overload handling policy or a pool shutdown in progress)
* @since 5.0
*/
ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay);
/**
* Schedule the given {@link Runnable}, starting as soon as possible and invoking it with
* the given delay between the completion of one execution and the start of the next.
* <p>Execution will end once the scheduler shuts down or the returned
* {@link ScheduledFuture} gets cancelled.
* @param task the Runnable to execute whenever the trigger fires
* @param delay the delay between the completion of one execution and the start of the next
* (in milliseconds)
* @return a {@link ScheduledFuture} representing pending execution of the task
* @throws org.springframework.core.task.TaskRejectedException if the given task was not accepted
* for internal reasons (for example, a pool overload handling policy or a pool shutdown in progress)
* @deprecated as of 6.0, in favor of {@link #scheduleWithFixedDelay(Runnable, Duration)}
*/
@Deprecated(since = "6.0")
default ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay) {
return scheduleWithFixedDelay(task, Duration.ofMillis(delay));
}
}
| TaskScheduler |
java | google__guava | guava/src/com/google/common/graph/ForwardingNetwork.java | {
"start": 978,
"end": 3777
} | class ____<N, E> extends AbstractNetwork<N, E> {
abstract Network<N, E> delegate();
@Override
public Set<N> nodes() {
return delegate().nodes();
}
@Override
public Set<E> edges() {
return delegate().edges();
}
@Override
public boolean isDirected() {
return delegate().isDirected();
}
@Override
public boolean allowsParallelEdges() {
return delegate().allowsParallelEdges();
}
@Override
public boolean allowsSelfLoops() {
return delegate().allowsSelfLoops();
}
@Override
public ElementOrder<N> nodeOrder() {
return delegate().nodeOrder();
}
@Override
public ElementOrder<E> edgeOrder() {
return delegate().edgeOrder();
}
@Override
public Set<N> adjacentNodes(N node) {
return delegate().adjacentNodes(node);
}
@Override
public Set<N> predecessors(N node) {
return delegate().predecessors(node);
}
@Override
public Set<N> successors(N node) {
return delegate().successors(node);
}
@Override
public Set<E> incidentEdges(N node) {
return delegate().incidentEdges(node);
}
@Override
public Set<E> inEdges(N node) {
return delegate().inEdges(node);
}
@Override
public Set<E> outEdges(N node) {
return delegate().outEdges(node);
}
@Override
public EndpointPair<N> incidentNodes(E edge) {
return delegate().incidentNodes(edge);
}
@Override
public Set<E> adjacentEdges(E edge) {
return delegate().adjacentEdges(edge);
}
@Override
public int degree(N node) {
return delegate().degree(node);
}
@Override
public int inDegree(N node) {
return delegate().inDegree(node);
}
@Override
public int outDegree(N node) {
return delegate().outDegree(node);
}
@Override
public Set<E> edgesConnecting(N nodeU, N nodeV) {
return delegate().edgesConnecting(nodeU, nodeV);
}
@Override
public Set<E> edgesConnecting(EndpointPair<N> endpoints) {
return delegate().edgesConnecting(endpoints);
}
@Override
public Optional<E> edgeConnecting(N nodeU, N nodeV) {
return delegate().edgeConnecting(nodeU, nodeV);
}
@Override
public Optional<E> edgeConnecting(EndpointPair<N> endpoints) {
return delegate().edgeConnecting(endpoints);
}
@Override
public @Nullable E edgeConnectingOrNull(N nodeU, N nodeV) {
return delegate().edgeConnectingOrNull(nodeU, nodeV);
}
@Override
public @Nullable E edgeConnectingOrNull(EndpointPair<N> endpoints) {
return delegate().edgeConnectingOrNull(endpoints);
}
@Override
public boolean hasEdgeConnecting(N nodeU, N nodeV) {
return delegate().hasEdgeConnecting(nodeU, nodeV);
}
@Override
public boolean hasEdgeConnecting(EndpointPair<N> endpoints) {
return delegate().hasEdgeConnecting(endpoints);
}
}
| ForwardingNetwork |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/rollup/action/PutRollupJobAction.java | {
"start": 1368,
"end": 4207
} | class ____ extends AcknowledgedRequest<Request> implements IndicesRequest, ToXContentObject {
private RollupJobConfig config;
private IndicesOptions indicesOptions = IndicesOptions.fromOptions(false, false, true, false);
public Request(RollupJobConfig config) {
super(TRAPPY_IMPLICIT_DEFAULT_MASTER_NODE_TIMEOUT, DEFAULT_ACK_TIMEOUT);
this.config = config;
}
public Request(StreamInput in) throws IOException {
super(in);
this.config = new RollupJobConfig(in);
}
public Request() {
super(TRAPPY_IMPLICIT_DEFAULT_MASTER_NODE_TIMEOUT, DEFAULT_ACK_TIMEOUT);
}
public static Request fromXContent(final XContentParser parser, final String id) throws IOException {
return new Request(RollupJobConfig.fromXContent(parser, id));
}
public RollupJobConfig getConfig() {
return config;
}
public void setConfig(RollupJobConfig config) {
this.config = config;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
this.config.writeTo(out);
}
public RollupActionRequestValidationException validateMappings(Map<String, Map<String, FieldCapabilities>> fieldCapsResponse) {
RollupActionRequestValidationException validationException = new RollupActionRequestValidationException();
if (fieldCapsResponse.size() == 0) {
validationException.addValidationError("Could not find any fields in the index/index-pattern that were configured in job");
return validationException;
}
config.validateMappings(fieldCapsResponse, validationException);
if (validationException.validationErrors().size() > 0) {
return validationException;
}
return null;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return this.config.toXContent(builder, params);
}
@Override
public String[] indices() {
return this.config.indices();
}
@Override
public IndicesOptions indicesOptions() {
return indicesOptions;
}
@Override
public int hashCode() {
return Objects.hash(config);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Request other = (Request) obj;
return Objects.equals(config, other.config);
}
}
}
| Request |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/type/TimeZoneStorageStrategy.java | {
"start": 447,
"end": 1370
} | enum ____ {
/**
* Stores the time zone via the {@code with time zone} SQL types which retain
* the information.
*/
NATIVE,
/**
* Stores the time zone in a separate column.
*/
COLUMN,
/**
* Does not store the time zone, and instead:
* <ul>
* <li>when persisting to the database, normalizes JDBC timestamps to the
* {@linkplain org.hibernate.cfg.AvailableSettings#JDBC_TIME_ZONE
* configured JDBC time zone}, or to the JVM default time zone
* id no JDBC time zone is configured, or
* <li>when reading back from the database, sets the offset or zone
* of {@code OffsetDateTime}/{@code ZonedDateTime} properties
* to the JVM default time zone.
* </ul>
* <p>
* Provided partly for backward compatibility with older
* versions of Hibernate.
*/
NORMALIZE,
/**
* Doesn't store the time zone, but instead normalizes to UTC.
*/
NORMALIZE_UTC
}
| TimeZoneStorageStrategy |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/index/IndexRequestBuilder.java | {
"start": 1425,
"end": 10720
} | class ____ extends ReplicationRequestBuilder<IndexRequest, DocWriteResponse, IndexRequestBuilder>
implements
WriteRequestBuilder<IndexRequestBuilder> {
private String id = null;
private BytesReference sourceBytesReference;
private XContentType sourceContentType;
private String pipeline;
private Boolean requireAlias;
private Boolean requireDataStream;
private String routing;
private WriteRequest.RefreshPolicy refreshPolicy;
private Long ifSeqNo;
private Long ifPrimaryTerm;
private DocWriteRequest.OpType opType;
private Boolean create;
private Long version;
private VersionType versionType;
public IndexRequestBuilder(ElasticsearchClient client) {
this(client, null);
}
@SuppressWarnings("this-escape")
public IndexRequestBuilder(ElasticsearchClient client, @Nullable String index) {
super(client, TransportIndexAction.TYPE);
setIndex(index);
}
/**
* Sets the id to index the document under. Optional, and if not set, one will be automatically
* generated.
*/
public IndexRequestBuilder setId(String id) {
this.id = id;
return this;
}
/**
* Controls the shard routing of the request. Using this value to hash the shard
* and not the id.
*/
public IndexRequestBuilder setRouting(String routing) {
this.routing = routing;
return this;
}
/**
* Sets the source.
*/
public IndexRequestBuilder setSource(BytesReference source, XContentType xContentType) {
this.sourceBytesReference = source;
this.sourceContentType = xContentType;
return this;
}
/**
* Index the Map as a JSON.
*
* @param source The map to index
*/
public IndexRequestBuilder setSource(Map<String, ?> source) {
return setSource(source, Requests.INDEX_CONTENT_TYPE);
}
/**
* Index the Map as the provided content type.
*
* @param source The map to index
*/
public IndexRequestBuilder setSource(Map<String, ?> source, XContentType contentType) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(contentType);
builder.map(source);
return setSource(builder);
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate", e);
}
}
/**
* Sets the document source to index.
* <p>
* Note, its preferable to either set it using {@link #setSource(org.elasticsearch.xcontent.XContentBuilder)}
* or using the {@link #setSource(byte[], XContentType)}.
*/
public IndexRequestBuilder setSource(String source, XContentType xContentType) {
this.sourceBytesReference = new BytesArray(source);
this.sourceContentType = xContentType;
return this;
}
/**
* Sets the content source to index.
*/
public IndexRequestBuilder setSource(XContentBuilder sourceBuilder) {
this.sourceBytesReference = BytesReference.bytes(sourceBuilder);
this.sourceContentType = sourceBuilder.contentType();
return this;
}
/**
* Sets the document to index in bytes form.
*/
public IndexRequestBuilder setSource(byte[] source, XContentType xContentType) {
return setSource(source, 0, source.length, xContentType);
}
/**
* Sets the document to index in bytes form (assumed to be safe to be used from different
* threads).
*
* @param source The source to index
* @param offset The offset in the byte array
* @param length The length of the data
* @param xContentType The type/format of the source
*/
public IndexRequestBuilder setSource(byte[] source, int offset, int length, XContentType xContentType) {
this.sourceBytesReference = new BytesArray(source, offset, length);
this.sourceContentType = xContentType;
return this;
}
/**
* Constructs a simple document with a field name and value pairs.
* <p>
* <b>Note: the number of objects passed to this method must be an even
* number. Also the first argument in each pair (the field name) must have a
* valid String representation.</b>
* </p>
*/
public IndexRequestBuilder setSource(Object... source) {
return setSource(Requests.INDEX_CONTENT_TYPE, source);
}
/**
* Constructs a simple document with a field name and value pairs.
* <p>
* <b>Note: the number of objects passed as varargs to this method must be an even
* number. Also the first argument in each pair (the field name) must have a
* valid String representation.</b>
* </p>
*/
public IndexRequestBuilder setSource(XContentType xContentType, Object... source) {
return setSource(IndexSource.getXContentBuilder(xContentType, source));
}
/**
* Sets the type of operation to perform.
*/
public IndexRequestBuilder setOpType(DocWriteRequest.OpType opType) {
this.opType = opType;
return this;
}
/**
* Set to {@code true} to force this index to use {@link org.elasticsearch.action.index.IndexRequest.OpType#CREATE}.
*/
public IndexRequestBuilder setCreate(boolean create) {
this.create = create;
return this;
}
/**
* Sets the version, which will cause the index operation to only be performed if a matching
* version exists and no changes happened on the doc since then.
*/
public IndexRequestBuilder setVersion(long version) {
this.version = version;
return this;
}
/**
* Sets the versioning type. Defaults to {@link VersionType#INTERNAL}.
*/
public IndexRequestBuilder setVersionType(VersionType versionType) {
this.versionType = versionType;
return this;
}
/**
* only perform this indexing request if the document was last modification was assigned the given
* sequence number. Must be used in combination with {@link #setIfPrimaryTerm(long)}
*
* If the document last modification was assigned a different sequence number a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
public IndexRequestBuilder setIfSeqNo(long seqNo) {
this.ifSeqNo = seqNo;
return this;
}
/**
* only perform this indexing request if the document was last modification was assigned the given
* primary term. Must be used in combination with {@link #setIfSeqNo(long)}
*
* If the document last modification was assigned a different term a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
public IndexRequestBuilder setIfPrimaryTerm(long term) {
this.ifPrimaryTerm = term;
return this;
}
/**
* Sets the ingest pipeline to be executed before indexing the document
*/
public IndexRequestBuilder setPipeline(String pipeline) {
this.pipeline = pipeline;
return this;
}
/**
* Sets the require_alias flag
*/
public IndexRequestBuilder setRequireAlias(boolean requireAlias) {
this.requireAlias = requireAlias;
return this;
}
/**
* Sets the require_data_stream flag
*/
public IndexRequestBuilder setRequireDataStream(boolean requireDataStream) {
this.requireDataStream = requireDataStream;
return this;
}
public IndexRequestBuilder setRefreshPolicy(WriteRequest.RefreshPolicy refreshPolicy) {
this.refreshPolicy = refreshPolicy;
return this;
}
public IndexRequestBuilder setRefreshPolicy(String refreshPolicy) {
this.refreshPolicy = WriteRequest.RefreshPolicy.parse(refreshPolicy);
return this;
}
@Override
public IndexRequest request() {
IndexRequest request = new IndexRequest();
super.apply(request);
request.id(id);
if (sourceBytesReference != null && sourceContentType != null) {
request.source(sourceBytesReference, sourceContentType);
}
if (pipeline != null) {
request.setPipeline(pipeline);
}
if (routing != null) {
request.routing(routing);
}
if (refreshPolicy != null) {
request.setRefreshPolicy(refreshPolicy);
}
if (ifSeqNo != null) {
request.setIfSeqNo(ifSeqNo);
}
if (ifPrimaryTerm != null) {
request.setIfPrimaryTerm(ifPrimaryTerm);
}
if (pipeline != null) {
request.setPipeline(pipeline);
}
if (requireAlias != null) {
request.setRequireAlias(requireAlias);
}
if (requireDataStream != null) {
request.setRequireDataStream(requireDataStream);
}
if (opType != null) {
request.opType(opType);
}
if (create != null) {
request.create(create);
}
if (version != null) {
request.version(version);
}
if (versionType != null) {
request.versionType(versionType);
}
return request;
}
}
| IndexRequestBuilder |
java | apache__camel | components/camel-infinispan/camel-infinispan-common/src/test/java/org/apache/camel/component/infinispan/InfinispanConsumerTestSupport.java | {
"start": 905,
"end": 1149
} | interface ____ {
String KEY_ONE = "keyOne";
String VALUE_ONE = "valueOne";
String VALUE_TWO = "valueTwo";
BasicCache<Object, Object> getCache();
BasicCache<Object, Object> getCache(String name);
}
| InfinispanConsumerTestSupport |
java | quarkusio__quarkus | independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ObserverInfo.java | {
"start": 1290,
"end": 10720
} | class ____ implements InjectionTargetInfo {
private static final Logger LOGGER = Logger.getLogger(ObserverInfo.class.getName());
static ObserverInfo create(BeanInfo declaringBean, MethodInfo observerMethod, Injection injection, boolean isAsync,
List<ObserverTransformer> transformers, BuildContext buildContext, boolean jtaCapabilities) {
BeanDeployment beanDeployment = declaringBean.getDeployment();
MethodParameterInfo eventParameter = initEventParam(observerMethod, beanDeployment);
AnnotationInstance priorityAnnotation = find(
getParameterAnnotations(beanDeployment, observerMethod, eventParameter.position()),
DotNames.PRIORITY);
Integer priority;
if (priorityAnnotation != null) {
priority = priorityAnnotation.value().asInt();
} else {
priority = ObserverMethod.DEFAULT_PRIORITY;
}
Type observedType = observerMethod.parameterType(eventParameter.position());
if (Types.containsTypeVariable(observedType)) {
Map<String, Type> resolvedTypeVariables = Types
.resolvedTypeVariables(declaringBean.getImplClazz(), beanDeployment)
.getOrDefault(observerMethod.declaringClass(), Collections.emptyMap());
observedType = Types.resolveTypeParam(observedType, resolvedTypeVariables,
beanDeployment.getBeanArchiveIndex());
}
Reception reception = initReception(isAsync, beanDeployment, observerMethod);
if (reception == Reception.IF_EXISTS && BuiltinScope.DEPENDENT.is(declaringBean.getScope())) {
throw new DefinitionException("@Dependent bean must not have a conditional observer method: "
+ observerMethod);
}
if (beanDeployment.hasAnnotation(observerMethod, DotNames.INJECT)) {
throw new DefinitionException("Observer method must not be annotated @Inject: " + observerMethod);
}
if (beanDeployment.hasAnnotation(observerMethod, DotNames.PRODUCES)) {
throw new DefinitionException("Observer method must not be annotated @Produces: " + observerMethod);
}
if (Annotations.hasParameterAnnotation(beanDeployment, observerMethod, DotNames.DISPOSES)) {
throw new DefinitionException("Observer method must not have a @Disposes parameter: " + observerMethod);
}
return create(null, beanDeployment, declaringBean.getTarget().get().asClass().name(), declaringBean,
observerMethod, injection,
eventParameter,
observedType,
initQualifiers(beanDeployment, observerMethod, eventParameter),
reception,
initTransactionPhase(isAsync, beanDeployment, observerMethod), isAsync, priority, transformers,
buildContext, jtaCapabilities, null, Collections.emptyMap(), false);
}
static ObserverInfo create(String userId, BeanDeployment beanDeployment, DotName beanClass, BeanInfo declaringBean,
MethodInfo observerMethod, Injection injection,
MethodParameterInfo eventParameter, Type observedType, Set<AnnotationInstance> qualifiers, Reception reception,
TransactionPhase transactionPhase, boolean isAsync, int priority,
List<ObserverTransformer> transformers, BuildContext buildContext, boolean jtaCapabilities,
Consumer<ObserverConfigurator.NotifyGeneration> notify, Map<String, Object> params,
boolean forceApplicationClass) {
if (!transformers.isEmpty()) {
// Transform attributes if needed
ObserverTransformationContext context = new ObserverTransformationContext(buildContext, observerMethod,
observedType, qualifiers, reception, transactionPhase, priority, isAsync);
for (ObserverTransformer transformer : transformers) {
if (transformer.appliesTo(observedType, qualifiers)) {
transformer.transform(context);
if (context.vetoed) {
String info;
if (observerMethod != null) {
info = String.format("method %s.%s()", observerMethod.declaringClass().name(),
observerMethod.name());
} else {
info = beanClass.toString();
}
LOGGER.debugf("Observer %s vetoed by %s", info, transformer.getClass().getName());
break;
}
}
}
if (context.vetoed) {
// Veto the observer method
return null;
}
qualifiers = context.getQualifiers();
reception = context.getReception();
transactionPhase = context.getTransactionPhase();
priority = context.getPriority();
isAsync = context.isAsync();
}
if (!transactionPhase.equals(TransactionPhase.IN_PROGRESS) && !jtaCapabilities) {
String info;
if (observerMethod != null) {
info = String.format("method %s.%s()", observerMethod.declaringClass().name(),
observerMethod.name());
} else {
info = beanClass.toString();
}
LOGGER.warnf(
"The observer %s makes use of %s transactional observers but no JTA capabilities were detected. Transactional observers will be notified at the same time as other observers.",
info, transactionPhase);
}
return new ObserverInfo(userId, beanDeployment, beanClass, declaringBean, observerMethod, injection, eventParameter,
isAsync, priority, reception, transactionPhase, observedType, qualifiers, notify, params,
forceApplicationClass);
}
private final String identifier;
private final String userId;
private final BeanDeployment beanDeployment;
private final DotName beanClass;
private final BeanInfo declaringBean;
private final MethodInfo observerMethod;
private final Injection injection;
private final MethodParameterInfo eventParameter;
private final int eventMetadataParameterPosition;
private final int priority;
private final boolean isAsync;
private final Reception reception;
private final TransactionPhase transactionPhase;
private final Type observedType;
private final Set<AnnotationInstance> qualifiers;
// Following fields are only used by synthetic observers
private final Consumer<ObserverConfigurator.NotifyGeneration> notify;
private final Map<String, Object> params;
private final boolean forceApplicationClass;
private ObserverInfo(String userId, BeanDeployment beanDeployment, DotName beanClass, BeanInfo declaringBean,
MethodInfo observerMethod,
Injection injection,
MethodParameterInfo eventParameter,
boolean isAsync, int priority, Reception reception, TransactionPhase transactionPhase,
Type observedType, Set<AnnotationInstance> qualifiers, Consumer<ObserverConfigurator.NotifyGeneration> notify,
Map<String, Object> params, boolean forceApplicationClass) {
this.identifier = generateIdentifier(userId, declaringBean, observerMethod, isAsync, priority, transactionPhase,
observedType, qualifiers);
this.userId = userId;
this.beanDeployment = beanDeployment;
this.beanClass = beanClass;
this.declaringBean = declaringBean;
this.observerMethod = observerMethod;
this.injection = injection;
this.eventParameter = eventParameter;
this.eventMetadataParameterPosition = initEventMetadataParam(observerMethod);
this.isAsync = isAsync;
this.priority = priority;
this.reception = reception;
this.transactionPhase = transactionPhase;
this.observedType = observedType;
this.qualifiers = qualifiers;
this.notify = notify;
this.params = params;
this.forceApplicationClass = forceApplicationClass;
}
@Override
public TargetKind kind() {
return TargetKind.OBSERVER;
}
@Override
public ObserverInfo asObserver() {
return this;
}
/**
* A mandatory unique identifier automatically generated for each Observer.
*
* @return the unique identifier
*/
public String getIdentifier() {
return identifier;
}
/**
* A unique user id should be used for multiple synthetic observer methods with the same
* attributes (including the bean class).
*
* @return the optional user id
* @deprecated use {@link #getUserId()} instead
*/
@Deprecated(since = "3.26", forRemoval = true)
public String getId() {
return userId;
}
/**
* A unique user id should be used for multiple synthetic observer methods with the same
* attributes (including the bean class).
*
* @return the optional user id
*/
public String getUserId() {
return userId;
}
BeanDeployment getBeanDeployment() {
return beanDeployment;
}
/**
*
* @return the | ObserverInfo |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/util/introspection/Introspection.java | {
"start": 3157,
"end": 6225
} | class ____ public getter
getter.setAccessible(true);
getter.invoke(target);
} catch (InvocationTargetException ex) {
String message = "Unable to invoke getter %s in %s, exception: %s".formatted(getter.getName(),
target.getClass().getSimpleName(),
ex.getTargetException());
throw new IntrospectionError(message, ex, ex.getTargetException());
} catch (Exception t) {
throw new IntrospectionError(propertyNotFoundErrorMessage("Unable to find property %s in %s", propertyName, target), t);
}
return getter;
}
public static void setExtractBareNamePropertyMethods(boolean bareNamePropertyMethods) {
ConfigurationProvider.loadRegisteredConfiguration();
Introspection.bareNamePropertyMethods = bareNamePropertyMethods;
}
// TODO reduce the visibility of the fields annotated with @VisibleForTesting
public static boolean canExtractBareNamePropertyMethods() {
return bareNamePropertyMethods;
}
private static String propertyNotFoundErrorMessage(String message, String propertyName, Object target) {
String targetTypeName = target.getClass().getName();
String property = quote(propertyName);
return message.formatted(property, targetTypeName);
}
private static Method findGetter(String propertyName, Object target) {
String capitalized = propertyName.substring(0, 1).toUpperCase(ENGLISH) + propertyName.substring(1);
// try to find getProperty
Method getter = findMethod("get" + capitalized, target);
if (isValidGetter(getter)) return getter;
if (bareNamePropertyMethods || target instanceof Record) {
// try to find bare name property
getter = findMethod(propertyName, target);
if (isValidGetter(getter)) return getter;
}
// try to find isProperty for boolean properties
Method isAccessor = findMethod("is" + capitalized, target);
return isValidGetter(isAccessor) ? isAccessor : null;
}
private static boolean isValidGetter(Method method) {
return method != null && !Modifier.isStatic(method.getModifiers()) && !Void.TYPE.equals(method.getReturnType());
}
private static Method findMethod(String name, Object target) {
final MethodKey methodKey = new MethodKey(name, target.getClass());
return METHOD_CACHE.computeIfAbsent(methodKey, Introspection::findMethodByKey).orElse(null);
}
private static Optional<Method> findMethodByKey(MethodKey key) {
// try public methods only
Class<?> clazz = key.clazz;
try {
return Optional.of(clazz.getMethod(key.name));
} catch (NoSuchMethodException | SecurityException ignored) {}
// search all methods
while (clazz != null) {
try {
return Optional.of(clazz.getDeclaredMethod(key.name));
} catch (NoSuchMethodException | SecurityException ignored) {}
clazz = clazz.getSuperclass();
}
return Optional.empty();
}
private static final | with |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/pipes/TestPipeApplication.java | {
"start": 21203,
"end": 22619
} | class ____ implements Progressable {
@Override
public void progress() {
}
}
private File[] cleanTokenPasswordFile() throws Exception {
File[] result = new File[2];
result[0] = new File("./jobTokenPassword");
if (result[0].exists()) {
FileUtil.chmod(result[0].getAbsolutePath(), "700");
assertTrue(result[0].delete());
}
result[1] = new File("./.jobTokenPassword.crc");
if (result[1].exists()) {
FileUtil.chmod(result[1].getAbsolutePath(), "700");
result[1].delete();
}
return result;
}
private File getFileCommand(String clazz) throws Exception {
String classpath = System.getProperty("java.class.path");
File fCommand = new File(workSpace + File.separator + "cache.sh");
fCommand.deleteOnExit();
if (!fCommand.getParentFile().exists()) {
fCommand.getParentFile().mkdirs();
}
fCommand.createNewFile();
OutputStream os = new FileOutputStream(fCommand);
os.write("#!/bin/sh \n".getBytes());
if (clazz == null) {
os.write(("ls ").getBytes());
} else {
// On Java 8 java.home returns "${JAVA_HOME}/jre", but that's good enough for this test
os.write((System.getProperty("java.home") + "/bin/java -cp " + classpath + " " + clazz).getBytes());
}
os.flush();
os.close();
FileUtil.chmod(fCommand.getAbsolutePath(), "700");
return fCommand;
}
private | Progress |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/auth/RoleTestUtils.java | {
"start": 2314,
"end": 2412
} | class ____ testing roles.
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public final | for |
java | netty__netty | transport/src/test/java/io/netty/channel/DefaultChannelPipelineTailTest.java | {
"start": 8220,
"end": 10524
} | class ____ extends AbstractChannel {
private static final ChannelMetadata METADATA = new ChannelMetadata(false);
private final ChannelConfig config = new DefaultChannelConfig(this);
private boolean active;
private boolean closed;
protected MyChannel() {
super(null);
}
@Override
protected DefaultChannelPipeline newChannelPipeline() {
return new MyChannelPipeline(this);
}
@Override
public ChannelConfig config() {
return config;
}
@Override
public boolean isOpen() {
return !closed;
}
@Override
public boolean isActive() {
return isOpen() && active;
}
@Override
public ChannelMetadata metadata() {
return METADATA;
}
@Override
protected AbstractUnsafe newUnsafe() {
return new MyUnsafe();
}
@Override
protected boolean isCompatible(EventLoop loop) {
return true;
}
@Override
protected SocketAddress localAddress0() {
return null;
}
@Override
protected SocketAddress remoteAddress0() {
return null;
}
@Override
protected void doBind(SocketAddress localAddress) {
}
@Override
protected void doDisconnect() {
}
@Override
protected void doClose() {
closed = true;
}
@Override
protected void doBeginRead() {
}
@Override
protected void doWrite(ChannelOutboundBuffer in) throws Exception {
throw new IOException();
}
protected void onUnhandledInboundChannelActive() {
}
protected void onUnhandledInboundChannelInactive() {
}
protected void onUnhandledInboundException(Throwable cause) {
}
protected void onUnhandledInboundMessage(Object msg) {
}
protected void onUnhandledInboundReadComplete() {
}
protected void onUnhandledInboundUserEventTriggered(Object evt) {
}
protected void onUnhandledInboundWritabilityChanged() {
}
private | MyChannel |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java | {
"start": 2105,
"end": 2633
} | class ____ to artificially limit the load produced by a process. As an example consider an application that issues database queries on a
* production system in a background process to gather statistical information. This background processing should not produce so much database load that the
* functionality and the performance of the production system are impacted. Here a {@link TimedSemaphore} could be installed to guarantee that only a given
* number of database queries are issued per second.
* </p>
* <p>
* A thread | is |
java | apache__kafka | clients/src/test/java/org/apache/kafka/clients/producer/internals/ProducerTestUtils.java | {
"start": 957,
"end": 1532
} | class ____ {
private static final int MAX_TRIES = 10;
static void runUntil(
Sender sender,
Supplier<Boolean> condition
) {
runUntil(sender, condition, MAX_TRIES);
}
static void runUntil(
Sender sender,
Supplier<Boolean> condition,
int maxTries
) {
int tries = 0;
while (!condition.get() && tries < maxTries) {
tries++;
sender.runOnce();
}
assertTrue(condition.get(), "Condition not satisfied after " + maxTries + " tries");
}
}
| ProducerTestUtils |
java | playframework__playframework | dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/jackson-config/json-utils/src/main/java/utils/ObjectMapperConfigUtil.java | {
"start": 8722,
"end": 10801
} | enum ____ a given accessor from VisibilityChecker via reflection. */
private static String detectVisibilityLevel(VisibilityChecker<?> vc, String kind) {
if (vc instanceof Std) {
String candidate = switch (kind) {
case "FIELD" -> "_fieldMinLevel";
case "GETTER" -> "_getterMinLevel";
case "IS_GETTER" -> "_isGetterMinLevel";
case "SETTER" -> "_setterMinLevel";
case "CREATOR" -> "_creatorMinLevel";
default -> null;
};
JsonAutoDetect.Visibility v = (JsonAutoDetect.Visibility) tryReadFieldEnum(vc, candidate, JsonAutoDetect.Visibility.class);
if (v != null) return v.name();
}
return "UNKNOWN";
}
private static Object tryReadFieldEnum(Object target, String fieldName, Class<?> enumType) {
try {
var fld = target.getClass().getDeclaredField(fieldName);
fld.setAccessible(true);
Object val = fld.get(target);
if (val != null && enumType.isInstance(val)) return val;
} catch (NoSuchFieldException ignored) {
} catch (Throwable t) {
// Any other reflection issue: keep trying other names
}
return null;
}
private static void putStreamReadConstraints(ObjectNode node, StreamReadConstraints rc) {
ObjectNode readC = node.putObject("streamReadConstraints");
readC.put("maxStringLength", rc.getMaxStringLength());
readC.put("maxNumberLength", rc.getMaxNumberLength());
readC.put("maxNestingDepth", rc.getMaxNestingDepth());
readC.put("maxNameLength", rc.getMaxNameLength());
readC.put("maxDocumentLength", rc.getMaxDocumentLength());
readC.put("maxTokenCount", rc.getMaxTokenCount());
}
private static void putStreamWriteConstraints(ObjectNode node, StreamWriteConstraints wc) {
ObjectNode writeC = node.putObject("streamWriteConstraints");
writeC.put("maxNestingDepth", wc.getMaxNestingDepth());
}
}
| for |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/common/timer/HashedWheelTimerTest.java | {
"start": 1196,
"end": 1399
} | class ____ {
private CountDownLatch tryStopTaskCountDownLatch = new CountDownLatch(1);
private CountDownLatch errorTaskCountDownLatch = new CountDownLatch(1);
private static | HashedWheelTimerTest |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java | {
"start": 6708,
"end": 9618
} | class ____ meant to act as an example on how to write yarn-based
* application masters.
* </p>
*
* <p>
* The ApplicationMaster is started on a container by the
* <code>ResourceManager</code>'s launcher. The first thing that the
* <code>ApplicationMaster</code> needs to do is to connect and register itself
* with the <code>ResourceManager</code>. The registration sets up information
* within the <code>ResourceManager</code> regarding what host:port the
* ApplicationMaster is listening on to provide any form of functionality to a
* client as well as a tracking url that a client can use to keep track of
* status/job history if needed. However, in the distributedshell, trackingurl
* and appMasterHost:appMasterRpcPort are not supported.
* </p>
*
* <p>
* The <code>ApplicationMaster</code> needs to send a heartbeat to the
* <code>ResourceManager</code> at regular intervals to inform the
* <code>ResourceManager</code> that it is up and alive. The
* {@link ApplicationMasterProtocol#allocate} to the <code>ResourceManager</code> from the
* <code>ApplicationMaster</code> acts as a heartbeat.
*
* <p>
* For the actual handling of the job, the <code>ApplicationMaster</code> has to
* request the <code>ResourceManager</code> via {@link AllocateRequest} for the
* required no. of containers using {@link ResourceRequest} with the necessary
* resource specifications such as node location, computational
* (memory/disk/cpu) resource requirements. The <code>ResourceManager</code>
* responds with an {@link AllocateResponse} that informs the
* <code>ApplicationMaster</code> of the set of newly allocated containers,
* completed containers as well as current state of available resources.
* </p>
*
* <p>
* For each allocated container, the <code>ApplicationMaster</code> can then set
* up the necessary launch context via {@link ContainerLaunchContext} to specify
* the allocated container id, local resources required by the executable, the
* environment to be setup for the executable, commands to execute, etc. and
* submit a {@link StartContainerRequest} to the {@link ContainerManagementProtocol} to
* launch and execute the defined commands on the given allocated container.
* </p>
*
* <p>
* The <code>ApplicationMaster</code> can monitor the launched container by
* either querying the <code>ResourceManager</code> using
* {@link ApplicationMasterProtocol#allocate} to get updates on completed containers or via
* the {@link ContainerManagementProtocol} by querying for the status of the allocated
* container's {@link ContainerId}.
*
* <p>
* After the job has been completed, the <code>ApplicationMaster</code> has to
* send a {@link FinishApplicationMasterRequest} to the
* <code>ResourceManager</code> to inform it that the
* <code>ApplicationMaster</code> has been completed.
*/
@InterfaceAudience.Public
@InterfaceStability.Unstable
public | is |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/selfinvocation/NokInterceptor.java | {
"start": 260,
"end": 398
} | class ____ {
@AroundInvoke
Object aroundInvoke(InvocationContext ctx) throws Exception {
return "NOK";
}
}
| NokInterceptor |
java | dropwizard__dropwizard | dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/JacksonMessageBodyProviderTest.java | {
"start": 2176,
"end": 2238
} | interface ____ extends Default {
}
public static | Partial2 |
java | apache__camel | components/camel-jetty/src/test/java/org/apache/camel/component/jetty/ExcludeCipherSuitesTest.java | {
"start": 1268,
"end": 2827
} | class ____ extends BaseJettyTest {
protected final String pwd = "changeit";
private SSLContextParameters createSslContextParameters() {
KeyStoreParameters ksp = new KeyStoreParameters();
ksp.setResource("file://" + this.getClass().getClassLoader().getResource("jsse/localhost.p12").toString());
ksp.setPassword(pwd);
KeyManagersParameters kmp = new KeyManagersParameters();
kmp.setKeyPassword(pwd);
kmp.setKeyStore(ksp);
SSLContextParameters sslContextParameters = new SSLContextParameters();
sslContextParameters.setKeyManagers(kmp);
FilterParameters filter = new FilterParameters();
filter.getExclude().add("^.*_(MD5|SHA|SHA1)$");
sslContextParameters.setCipherSuitesFilter(filter);
return sslContextParameters;
}
@Test
public void testExclude() throws Exception {
getMockEndpoint("mock:a").expectedBodiesReceived(1);
template.sendBody("jetty:https://localhost:" + getPort() + "/test", "Hello World");
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
JettyHttpComponent jetty = getContext().getComponent("jetty", JettyHttpComponent.class);
jetty.setSslContextParameters(createSslContextParameters());
from("jetty:https://localhost:" + getPort() + "/test").to("mock:a");
}
};
}
}
| ExcludeCipherSuitesTest |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/constants/ConfigConstants.java | {
"start": 932,
"end": 1277
} | class ____ {
private ConfigConstants() {}
/**
* System property name for the avro dependency.
* This property is used to configure trusted packages,
* which the avro dependency can use for serialization.
*/
public static final String CONFIG_AVRO_SERIALIZABLE_PACKAGES =
"org.apache.avro.SERIALIZABLE_PACKAGES";
}
| ConfigConstants |
java | redisson__redisson | redisson/src/test/java/org/redisson/RedissonLiveObjectServiceTest.java | {
"start": 6391,
"end": 7561
} | class ____ implements Comparable<TestREntityValueNested>, Serializable {
@RId
private String name;
private TestREntityWithRMap value;
protected TestREntityValueNested() {
}
public TestREntityValueNested(String name) {
this.name = name;
}
public TestREntityValueNested(String name, TestREntityWithRMap value) {
super();
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public TestREntityWithRMap getValue() {
return value;
}
public void setName(String name) {
this.name = name;
}
public void setValue(TestREntityWithRMap value) {
this.value = value;
}
@Override
public int compareTo(TestREntityValueNested o) {
int res = name.compareTo(o.name);
if (res == 0 || value != null || o.value != null) {
return value.compareTo(o.value);
}
return res;
}
}
@REntity
public static | TestREntityValueNested |
java | quarkusio__quarkus | integration-tests/rest-client-reactive-http2/src/main/java/io/quarkus/it/rest/client/http2/multipart/MultipartClient.java | {
"start": 7387,
"end": 7652
} | class ____ {
@FormParam("file")
@PartType(MediaType.APPLICATION_OCTET_STREAM)
public java.nio.file.Path file;
@FormParam("fileName")
@PartType(MediaType.TEXT_PLAIN)
public String fileName;
}
| WithPathAsBinaryFile |
java | apache__maven | compat/maven-builder-support/src/test/java/org/apache/maven/building/FileSourceTest.java | {
"start": 1079,
"end": 2249
} | class ____ {
@Test
void testFileSource() {
NullPointerException e = assertThrows(
NullPointerException.class,
() -> new FileSource((File) null),
"Should fail, since you must specify a file");
assertEquals("file cannot be null", e.getMessage());
}
@Test
void testGetInputStream() throws Exception {
File txtFile = new File("target/test-classes/source.txt");
FileSource source = new FileSource(txtFile);
try (InputStream is = source.getInputStream();
Scanner scanner = new Scanner(is)) {
assertEquals("Hello World!", scanner.nextLine());
}
}
@Test
void testGetLocation() {
File txtFile = new File("target/test-classes/source.txt");
FileSource source = new FileSource(txtFile);
assertEquals(txtFile.getAbsolutePath(), source.getLocation());
}
@Test
void testGetFile() {
File txtFile = new File("target/test-classes/source.txt");
FileSource source = new FileSource(txtFile);
assertEquals(txtFile.getAbsoluteFile(), source.getFile());
}
}
| FileSourceTest |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/Functions.java | {
"start": 2770,
"end": 2817
} | class ____ {
/**
* A functional | Functions |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/util/ASTHelpersTest.java | {
"start": 28839,
"end": 29887
} | class ____ {
@Deprecated public void doIt() {}
void caller() { doIt(); }
}
""");
TestScanner scanner =
new TestScanner() {
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (ASTHelpers.getSymbol(tree).toString().equals("doIt()")) {
setAssertionsComplete();
assertThat(hasAnnotation(tree, Deprecated.class.getName(), state)).isFalse();
}
return super.visitMethodInvocation(tree, state);
}
};
tests.add(scanner);
assertCompiles(scanner);
}
/**
* Test checker to ensure that ASTHelpers.hasDirectAnnotationWithSimpleName() does require the
* annotation symbol to be on the classpath.
*/
@BugPattern(
severity = SeverityLevel.ERROR,
summary =
"Test checker to ensure that ASTHelpers.hasDirectAnnotationWithSimpleName() "
+ "does require the annotation symbol to be on the classpath")
public static | A |
java | apache__camel | components/camel-spring-parent/camel-spring-ai/camel-spring-ai-embeddings/src/main/java/org/apache/camel/component/springai/embeddings/SpringAiEmbeddingsEndpoint.java | {
"start": 1570,
"end": 2752
} | class ____ extends DefaultEndpoint {
@Metadata(required = true)
@UriPath(description = "The id")
private final String embeddingId;
@UriParam
private SpringAiEmbeddingsConfiguration configuration;
public SpringAiEmbeddingsEndpoint(
String endpointUri,
Component component,
String embeddingId,
SpringAiEmbeddingsConfiguration configuration) {
super(endpointUri, component);
this.embeddingId = embeddingId;
this.configuration = configuration;
}
public SpringAiEmbeddingsConfiguration getConfiguration() {
return this.configuration;
}
public String getEmbeddingId() {
return this.embeddingId;
}
@Override
public Producer createProducer() throws Exception {
return new SpringAiEmbeddingsProducer(this);
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("Consumer is not implemented for this component");
}
}
| SpringAiEmbeddingsEndpoint |
java | netty__netty | handler/src/main/java/io/netty/handler/ssl/SslHandler.java | {
"start": 80415,
"end": 110351
} | class ____ implements Runnable {
private final boolean inUnwrap;
private final Runnable runCompleteTask = new Runnable() {
@Override
public void run() {
runComplete();
}
};
SslTasksRunner(boolean inUnwrap) {
this.inUnwrap = inUnwrap;
}
// Handle errors which happened during task processing.
private void taskError(Throwable e) {
if (inUnwrap) {
// As the error happened while the task was scheduled as part of unwrap(...) we also need to ensure
// we fire it through the pipeline as inbound error to be consistent with what we do in decode(...).
//
// This will also ensure we fail the handshake future and flush all produced data.
try {
handleUnwrapThrowable(ctx, e);
} catch (Throwable cause) {
safeExceptionCaught(cause);
}
} else {
setHandshakeFailure(ctx, e);
forceFlush(ctx);
}
}
// Try to call exceptionCaught(...)
private void safeExceptionCaught(Throwable cause) {
try {
exceptionCaught(ctx, wrapIfNeeded(cause));
} catch (Throwable error) {
ctx.fireExceptionCaught(error);
}
}
private Throwable wrapIfNeeded(Throwable cause) {
if (!inUnwrap) {
// If we are not in unwrap(...) we can just rethrow without wrapping at all.
return cause;
}
// As the exception would have been triggered by an inbound operation we will need to wrap it in a
// DecoderException to mimic what a decoder would do when decode(...) throws.
return cause instanceof DecoderException ? cause : new DecoderException(cause);
}
private void tryDecodeAgain() {
try {
channelRead(ctx, Unpooled.EMPTY_BUFFER);
} catch (Throwable cause) {
safeExceptionCaught(cause);
} finally {
// As we called channelRead(...) we also need to call channelReadComplete(...) which
// will ensure we either call ctx.fireChannelReadComplete() or will trigger a ctx.read() if
// more data is needed.
channelReadComplete0(ctx);
}
}
/**
* Executed after the wrapped {@code task} was executed via {@code delegatedTaskExecutor} to resume work
* on the {@link EventExecutor}.
*/
private void resumeOnEventExecutor() {
assert ctx.executor().inEventLoop();
clearState(STATE_PROCESS_TASK);
try {
HandshakeStatus status = engine.getHandshakeStatus();
switch (status) {
// There is another task that needs to be executed and offloaded to the delegatingTaskExecutor as
// a result of this. Let's reschedule....
case NEED_TASK:
executeDelegatedTask(this);
break;
// The handshake finished, lets notify about the completion of it and resume processing.
case FINISHED:
// Not handshaking anymore, lets notify about the completion if not done yet and resume processing.
case NOT_HANDSHAKING:
setHandshakeSuccess(); // NOT_HANDSHAKING -> workaround for android skipping FINISHED state.
try {
// Lets call wrap to ensure we produce the alert if there is any pending and also to
// ensure we flush any queued data..
wrap(ctx, inUnwrap);
} catch (Throwable e) {
taskError(e);
return;
}
if (inUnwrap) {
// If we were in the unwrap call when the task was processed we should also try to unwrap
// non app data first as there may not anything left in the inbound buffer to process.
unwrapNonAppData(ctx);
}
// Flush now as we may have written some data as part of the wrap call.
forceFlush(ctx);
tryDecodeAgain();
break;
// We need more data so lets try to unwrap first and then call decode again which will feed us
// with buffered data (if there is any).
case NEED_UNWRAP:
try {
unwrapNonAppData(ctx);
} catch (SSLException e) {
handleUnwrapThrowable(ctx, e);
return;
}
tryDecodeAgain();
break;
// To make progress we need to call SSLEngine.wrap(...) which may produce more output data
// that will be written to the Channel.
case NEED_WRAP:
try {
if (!wrapNonAppData(ctx, false) && inUnwrap) {
// The handshake finished in wrapNonAppData(...), we need to try call
// unwrapNonAppData(...) as we may have some alert that we should read.
//
// This mimics what we would do when we are calling this method while in unwrap(...).
unwrapNonAppData(ctx);
}
// Flush now as we may have written some data as part of the wrap call.
forceFlush(ctx);
} catch (Throwable e) {
taskError(e);
return;
}
// Now try to feed in more data that we have buffered.
tryDecodeAgain();
break;
default:
// Should never reach here as we handle all cases.
throw new AssertionError();
}
} catch (Throwable cause) {
safeExceptionCaught(cause);
}
}
void runComplete() {
EventExecutor executor = ctx.executor();
// Jump back on the EventExecutor. We do this even if we are already on the EventLoop to guard against
// reentrancy issues. Failing to do so could lead to the situation of tryDecode(...) be called and so
// channelRead(...) while still in the decode loop. In this case channelRead(...) might release the input
// buffer if its empty which would then result in an IllegalReferenceCountException when we try to continue
// decoding.
//
// See https://github.com/netty/netty-tcnative/issues/680
executor.execute(new Runnable() {
@Override
public void run() {
resumeOnEventExecutor();
}
});
}
@Override
public void run() {
try {
Runnable task = engine.getDelegatedTask();
if (task == null) {
// The task was processed in the meantime. Let's just return.
return;
}
if (task instanceof AsyncRunnable) {
AsyncRunnable asyncTask = (AsyncRunnable) task;
asyncTask.run(runCompleteTask);
} else {
task.run();
runComplete();
}
} catch (final Throwable cause) {
handleException(cause);
}
}
private void handleException(final Throwable cause) {
EventExecutor executor = ctx.executor();
if (executor.inEventLoop()) {
clearState(STATE_PROCESS_TASK);
safeExceptionCaught(cause);
} else {
try {
executor.execute(new Runnable() {
@Override
public void run() {
clearState(STATE_PROCESS_TASK);
safeExceptionCaught(cause);
}
});
} catch (RejectedExecutionException ignore) {
clearState(STATE_PROCESS_TASK);
// the context itself will handle the rejected exception when try to schedule the operation so
// ignore the RejectedExecutionException
ctx.fireExceptionCaught(cause);
}
}
}
}
/**
* Notify all the handshake futures about the successfully handshake
* @return {@code true} if {@link #handshakePromise} was set successfully and a {@link SslHandshakeCompletionEvent}
* was fired. {@code false} otherwise.
*/
private boolean setHandshakeSuccess() throws SSLException {
// Our control flow may invoke this method multiple times for a single FINISHED event. For example
// wrapNonAppData may drain pendingUnencryptedWrites in wrap which transitions to handshake from FINISHED to
// NOT_HANDSHAKING which invokes setHandshakeSuccess, and then wrapNonAppData also directly invokes this method.
final SSLSession session = engine.getSession();
if (resumptionController != null && !handshakePromise.isDone()) {
try {
if (resumptionController.validateResumeIfNeeded(engine) && logger.isDebugEnabled()) {
logger.debug("{} Resumed and reauthenticated session", ctx.channel());
}
} catch (CertificateException e) {
SSLHandshakeException exception = new SSLHandshakeException(e.getMessage());
exception.initCause(e);
throw exception;
}
}
final boolean notified = !handshakePromise.isDone() && handshakePromise.trySuccess(ctx.channel());
if (notified) {
if (logger.isDebugEnabled()) {
logger.debug(
"{} HANDSHAKEN: protocol:{} cipher suite:{}",
ctx.channel(),
session.getProtocol(),
session.getCipherSuite());
}
ctx.fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);
}
if (isStateSet(STATE_READ_DURING_HANDSHAKE)) {
clearState(STATE_READ_DURING_HANDSHAKE);
if (!ctx.channel().config().isAutoRead()) {
ctx.read();
}
}
return notified;
}
/**
* Notify all the handshake futures about the failure during the handshake.
*/
private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause) {
setHandshakeFailure(ctx, cause, true, true, false);
}
/**
* Notify all the handshake futures about the failure during the handshake.
*/
private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean closeInbound,
boolean notify, boolean alwaysFlushAndClose) {
try {
// Release all resources such as internal buffers that SSLEngine is managing.
setState(STATE_OUTBOUND_CLOSED);
engine.closeOutbound();
if (closeInbound) {
try {
engine.closeInbound();
} catch (SSLException e) {
if (logger.isDebugEnabled()) {
// only log in debug mode as it most likely harmless and latest chrome still trigger
// this all the time.
//
// See https://github.com/netty/netty/issues/1340
String msg = e.getMessage();
if (msg == null || !(msg.contains("possible truncation attack") ||
msg.contains("closing inbound before receiving peer's close_notify"))) {
logger.debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e);
}
}
}
}
if (handshakePromise.tryFailure(cause) || alwaysFlushAndClose) {
SslUtils.handleHandshakeFailure(ctx, cause, notify);
}
} finally {
// Ensure we remove and fail all pending writes in all cases and so release memory quickly.
releaseAndFailAll(ctx, cause);
}
}
private void setHandshakeFailureTransportFailure(ChannelHandlerContext ctx, Throwable cause) {
// If TLS control frames fail to write we are in an unknown state and may become out of
// sync with our peer. We give up and close the channel. This will also take care of
// cleaning up any outstanding state (e.g. handshake promise, queued unencrypted data).
try {
SSLException transportFailure = new SSLException("failure when writing TLS control frames", cause);
releaseAndFailAll(ctx, transportFailure);
if (handshakePromise.tryFailure(transportFailure)) {
ctx.fireUserEventTriggered(new SslHandshakeCompletionEvent(transportFailure));
}
} finally {
ctx.close();
}
}
private void releaseAndFailAll(ChannelHandlerContext ctx, Throwable cause) {
if (resumptionController != null &&
(!engine.getSession().isValid() || cause instanceof SSLHandshakeException)) {
resumptionController.remove(engine());
}
if (pendingUnencryptedWrites != null) {
pendingUnencryptedWrites.releaseAndFailAll(ctx, cause);
}
}
private void notifyClosePromise(Throwable cause) {
if (cause == null) {
if (sslClosePromise.trySuccess(ctx.channel())) {
ctx.fireUserEventTriggered(SslCloseCompletionEvent.SUCCESS);
}
} else {
if (sslClosePromise.tryFailure(cause)) {
ctx.fireUserEventTriggered(new SslCloseCompletionEvent(cause));
}
}
}
private void closeOutboundAndChannel(
final ChannelHandlerContext ctx, final ChannelPromise promise, boolean disconnect) throws Exception {
setState(STATE_OUTBOUND_CLOSED);
engine.closeOutbound();
if (!ctx.channel().isActive()) {
if (disconnect) {
ctx.disconnect(promise);
} else {
ctx.close(promise);
}
return;
}
ChannelPromise closeNotifyPromise = ctx.newPromise();
try {
flush(ctx, closeNotifyPromise);
} finally {
if (!isStateSet(STATE_CLOSE_NOTIFY)) {
setState(STATE_CLOSE_NOTIFY);
// It's important that we do not pass the original ChannelPromise to safeClose(...) as when flush(....)
// throws an Exception it will be propagated to the AbstractChannelHandlerContext which will try
// to fail the promise because of this. This will then fail as it was already completed by
// safeClose(...). We create a new ChannelPromise and try to notify the original ChannelPromise
// once it is complete. If we fail to do so we just ignore it as in this case it was failed already
// because of a propagated Exception.
//
// See https://github.com/netty/netty/issues/5931
safeClose(ctx, closeNotifyPromise, PromiseNotifier.cascade(false, ctx.newPromise(), promise));
} else {
/// We already handling the close_notify so just attach the promise to the sslClosePromise.
sslClosePromise.addListener(new FutureListener<Channel>() {
@Override
public void operationComplete(Future<Channel> future) {
promise.setSuccess();
}
});
}
}
}
private void flush(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
if (pendingUnencryptedWrites != null) {
pendingUnencryptedWrites.add(Unpooled.EMPTY_BUFFER, promise);
} else {
promise.setFailure(newPendingWritesNullException());
}
flush(ctx);
}
@Override
public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
Channel channel = ctx.channel();
pendingUnencryptedWrites = new SslHandlerCoalescingBufferQueue(channel, 16, engineType.wantsDirectBuffer) {
@Override
protected int wrapDataSize() {
return SslHandler.this.wrapDataSize;
}
};
setOpensslEngineSocketFd(channel);
boolean fastOpen = Boolean.TRUE.equals(channel.config().getOption(ChannelOption.TCP_FASTOPEN_CONNECT));
boolean active = channel.isActive();
if (active || fastOpen) {
// Explicitly flush the handshake only if the channel is already active.
// With TCP Fast Open, we write to the outbound buffer before the TCP connect is established.
// The buffer will then be flushed as part of establishing the connection, saving us a round-trip.
startHandshakeProcessing(active);
// If we weren't able to include client_hello in the TCP SYN (e.g. no token, disabled at the OS) we have to
// flush pending data in the outbound buffer later in channelActive().
final ChannelOutboundBuffer outboundBuffer;
if (fastOpen && ((outboundBuffer = channel.unsafe().outboundBuffer()) == null ||
outboundBuffer.totalPendingWriteBytes() > 0)) {
setState(STATE_NEEDS_FLUSH);
}
}
}
private void startHandshakeProcessing(boolean flushAtEnd) {
if (!isStateSet(STATE_HANDSHAKE_STARTED)) {
setState(STATE_HANDSHAKE_STARTED);
if (engine.getUseClientMode()) {
// Begin the initial handshake.
// channelActive() event has been fired already, which means this.channelActive() will
// not be invoked. We have to initialize here instead.
handshake(flushAtEnd);
}
applyHandshakeTimeout();
} else if (isStateSet(STATE_NEEDS_FLUSH)) {
forceFlush(ctx);
}
}
/**
* Performs TLS renegotiation.
*/
public Future<Channel> renegotiate() {
ChannelHandlerContext ctx = this.ctx;
if (ctx == null) {
throw new IllegalStateException();
}
return renegotiate(ctx.executor().<Channel>newPromise());
}
/**
* Performs TLS renegotiation.
*/
public Future<Channel> renegotiate(final Promise<Channel> promise) {
ObjectUtil.checkNotNull(promise, "promise");
ChannelHandlerContext ctx = this.ctx;
if (ctx == null) {
throw new IllegalStateException();
}
EventExecutor executor = ctx.executor();
if (!executor.inEventLoop()) {
executor.execute(new Runnable() {
@Override
public void run() {
renegotiateOnEventLoop(promise);
}
});
return promise;
}
renegotiateOnEventLoop(promise);
return promise;
}
private void renegotiateOnEventLoop(final Promise<Channel> newHandshakePromise) {
final Promise<Channel> oldHandshakePromise = handshakePromise;
if (!oldHandshakePromise.isDone()) {
// There's no need to handshake because handshake is in progress already.
// Merge the new promise into the old one.
PromiseNotifier.cascade(oldHandshakePromise, newHandshakePromise);
} else {
handshakePromise = newHandshakePromise;
handshake(true);
applyHandshakeTimeout();
}
}
/**
* Performs TLS (re)negotiation.
* @param flushAtEnd Set to {@code true} if the outbound buffer should be flushed (written to the network) at the
* end. Set to {@code false} if the handshake will be flushed later, e.g. as part of TCP Fast Open
* connect.
*/
private void handshake(boolean flushAtEnd) {
if (engine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
// Not all SSLEngine implementations support calling beginHandshake multiple times while a handshake
// is in progress. See https://github.com/netty/netty/issues/4718.
return;
}
if (handshakePromise.isDone()) {
// If the handshake is done already lets just return directly as there is no need to trigger it again.
// This can happen if the handshake(...) was triggered before we called channelActive(...) by a
// flush() that was triggered by a ChannelFutureListener that was added to the ChannelFuture returned
// from the connect(...) method. In this case we will see the flush() happen before we had a chance to
// call fireChannelActive() on the pipeline.
return;
}
// Begin handshake.
final ChannelHandlerContext ctx = this.ctx;
try {
engine.beginHandshake();
wrapNonAppData(ctx, false);
} catch (Throwable e) {
setHandshakeFailure(ctx, e);
} finally {
if (flushAtEnd) {
forceFlush(ctx);
}
}
}
private void applyHandshakeTimeout() {
final Promise<Channel> localHandshakePromise = this.handshakePromise;
// Set timeout if necessary.
final long handshakeTimeoutMillis = this.handshakeTimeoutMillis;
if (handshakeTimeoutMillis <= 0 || localHandshakePromise.isDone()) {
return;
}
final Future<?> timeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
if (localHandshakePromise.isDone()) {
return;
}
SSLException exception =
new SslHandshakeTimeoutException("handshake timed out after " + handshakeTimeoutMillis + "ms");
try {
if (localHandshakePromise.tryFailure(exception)) {
SslUtils.handleHandshakeFailure(ctx, exception, true);
}
} finally {
releaseAndFailAll(ctx, exception);
}
}
}, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
// Cancel the handshake timeout when handshake is finished.
localHandshakePromise.addListener(new FutureListener<Channel>() {
@Override
public void operationComplete(Future<Channel> f) throws Exception {
timeoutFuture.cancel(false);
}
});
}
private void forceFlush(ChannelHandlerContext ctx) {
clearState(STATE_NEEDS_FLUSH);
ctx.flush();
}
private void setOpensslEngineSocketFd(Channel c) {
if (c instanceof UnixChannel && engine instanceof ReferenceCountedOpenSslEngine) {
((ReferenceCountedOpenSslEngine) engine).bioSetFd(((UnixChannel) c).fd().intValue());
}
}
/**
* Issues an initial TLS handshake once connected when used in client-mode
*/
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
setOpensslEngineSocketFd(ctx.channel());
if (!startTls) {
startHandshakeProcessing(true);
}
ctx.fireChannelActive();
}
private void safeClose(
final ChannelHandlerContext ctx, final ChannelFuture flushFuture,
final ChannelPromise promise) {
if (!ctx.channel().isActive()) {
ctx.close(promise);
return;
}
final Future<?> timeoutFuture;
if (!flushFuture.isDone()) {
long closeNotifyTimeout = closeNotifyFlushTimeoutMillis;
if (closeNotifyTimeout > 0) {
// Force-close the connection if close_notify is not fully sent in time.
timeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
// May be done in the meantime as cancel(...) is only best effort.
if (!flushFuture.isDone()) {
logger.warn("{} Last write attempt timed out; force-closing the connection.",
ctx.channel());
addCloseListener(ctx.close(ctx.newPromise()), promise);
}
}
}, closeNotifyTimeout, TimeUnit.MILLISECONDS);
} else {
timeoutFuture = null;
}
} else {
timeoutFuture = null;
}
// Close the connection if close_notify is sent in time.
flushFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f) {
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
final long closeNotifyReadTimeout = closeNotifyReadTimeoutMillis;
if (closeNotifyReadTimeout <= 0) {
// Trigger the close in all cases to make sure the promise is notified
// See https://github.com/netty/netty/issues/2358
addCloseListener(ctx.close(ctx.newPromise()), promise);
} else {
final Future<?> closeNotifyReadTimeoutFuture;
if (!sslClosePromise.isDone()) {
closeNotifyReadTimeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
if (!sslClosePromise.isDone()) {
logger.debug(
"{} did not receive close_notify in {}ms; force-closing the connection.",
ctx.channel(), closeNotifyReadTimeout);
// Do the close now...
addCloseListener(ctx.close(ctx.newPromise()), promise);
}
}
}, closeNotifyReadTimeout, TimeUnit.MILLISECONDS);
} else {
closeNotifyReadTimeoutFuture = null;
}
// Do the close once the we received the close_notify.
sslClosePromise.addListener(new FutureListener<Channel>() {
@Override
public void operationComplete(Future<Channel> future) throws Exception {
if (closeNotifyReadTimeoutFuture != null) {
closeNotifyReadTimeoutFuture.cancel(false);
}
addCloseListener(ctx.close(ctx.newPromise()), promise);
}
});
}
}
});
}
private static void addCloseListener(ChannelFuture future, ChannelPromise promise) {
// We notify the promise in the ChannelPromiseNotifier as there is a "race" where the close(...) call
// by the timeoutFuture and the close call in the flushFuture listener will be called. Because of
// this we need to use trySuccess() and tryFailure(...) as otherwise we can cause an
// IllegalStateException.
// Also we not want to log if the notification happens as this is expected in some cases.
// See https://github.com/netty/netty/issues/5598
PromiseNotifier.cascade(false, future, promise);
}
/**
* Always prefer a direct buffer when it's pooled, so that we reduce the number of memory copies
* in {@link OpenSslEngine}.
*/
private ByteBuf allocate(ChannelHandlerContext ctx, int capacity) {
ByteBufAllocator alloc = ctx.alloc();
if (engineType.wantsDirectBuffer) {
return alloc.directBuffer(capacity);
} else {
return alloc.buffer(capacity);
}
}
/**
* Allocates an outbound network buffer for {@link SSLEngine#wrap(ByteBuffer, ByteBuffer)} which can encrypt
* the specified amount of pending bytes.
*/
private ByteBuf allocateOutNetBuf(ChannelHandlerContext ctx, int pendingBytes, int numComponents) {
return engineType.allocateWrapBuffer(this, ctx.alloc(), pendingBytes, numComponents);
}
private boolean isStateSet(int bit) {
return (state & bit) == bit;
}
private void setState(int bit) {
state |= bit;
}
private void clearState(int bit) {
state &= ~bit;
}
private final | SslTasksRunner |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/keymanytoone/unidir/ondelete/KeyManyToOneCascadeDeleteTest.java | {
"start": 844,
"end": 2578
} | class ____ {
@Test
@JiraKey(value = "HHH-7807")
public void testComponentCascadeRemoval(SessionFactoryScope scope) {
scope.inSession(
session -> {
Customer customer = new Customer( "Lukasz" );
Order order1 = new Order( new Order.Id( customer, 1L ) );
order1.setItem( "laptop" );
Order order2 = new Order( new Order.Id( customer, 2L ) );
order2.setItem( "printer" );
session.getTransaction().begin();
try {
session.persist( customer );
session.persist( order1 );
session.persist( order2 );
session.getTransaction().commit();
}
catch (Exception e) {
if ( session.getTransaction().isActive() ) {
session.getTransaction().rollback();
}
throw e;
}
// Removing customer cascades to associated orders.
session.getTransaction().begin();
try {
customer = session.get( Customer.class, customer.getId() );
session.remove( customer );
session.getTransaction().commit();
}
catch (Exception e) {
if ( session.getTransaction().isActive() ) {
session.getTransaction().rollback();
}
throw e;
}
session.getTransaction().begin();
try {
assertEquals(
"0",
session.createQuery( "select count(*) from Customer" )
.uniqueResult()
.toString()
);
assertEquals(
"0",
session.createQuery( "select count(*) from Order" ).uniqueResult().toString()
);
session.getTransaction().commit();
}
catch (Exception e) {
if ( session.getTransaction().isActive() ) {
session.getTransaction().rollback();
}
throw e;
}
}
);
}
}
| KeyManyToOneCascadeDeleteTest |
java | apache__camel | components/camel-cxf/camel-cxf-soap/src/test/java/org/apache/camel/component/cxf/jaxws/CxfConsumerPayloadXPathTest.java | {
"start": 1641,
"end": 3222
} | class ____ extends CamelTestSupport {
public static final String HEADER_SIZE = "tstsize";
@Test
public void size1XPathStringResultTest() throws Exception {
simpleTest(1, new TestRouteWithXPathStringResultBuilder());
}
@Test
public void size100XPathStringResultTest() throws Exception {
simpleTest(100, new TestRouteWithXPathStringResultBuilder());
}
@Test
public void size1000XPathStringResultTest() throws Exception {
simpleTest(1000, new TestRouteWithXPathStringResultBuilder());
}
@Test
public void size10000XPathStringResultTest() throws Exception {
simpleTest(10000, new TestRouteWithXPathStringResultBuilder());
}
@Test
public void size1XPathTest() throws Exception {
simpleTest(1, new TestRouteWithXPathBuilder());
}
@Test
public void size100XPathTest() throws Exception {
simpleTest(100, new TestRouteWithXPathBuilder());
}
@Test
public void size1000XPathTest() throws Exception {
simpleTest(1000, new TestRouteWithXPathBuilder());
}
@Test
public void size10000XPathTest() throws Exception {
simpleTest(10000, new TestRouteWithXPathBuilder());
}
//the textnode appears to have siblings!
@Test
public void size10000DomTest() throws Exception {
simpleTest(10000, new TestRouteWithDomBuilder());
}
@Test
public void size1000DomFirstTest() throws Exception {
simpleTest(1000, new TestRouteWithDomFirstOneOnlyBuilder());
}
private | CxfConsumerPayloadXPathTest |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableConcatWithSingle.java | {
"start": 1190,
"end": 1645
} | class ____<T> extends AbstractObservableWithUpstream<T, T> {
final SingleSource<? extends T> other;
public ObservableConcatWithSingle(Observable<T> source, SingleSource<? extends T> other) {
super(source);
this.other = other;
}
@Override
protected void subscribeActual(Observer<? super T> observer) {
source.subscribe(new ConcatWithObserver<>(observer, other));
}
static final | ObservableConcatWithSingle |
java | google__guice | extensions/assistedinject/test/com/google/inject/assistedinject/FactoryProvider2Test.java | {
"start": 48193,
"end": 48482
} | class ____ extends AbstractAssisted {
@AssistedInject
ConcreteAssistedWithOverride(@SuppressWarnings("unused") @Assisted String string) {}
@AssistedInject
ConcreteAssistedWithOverride(@SuppressWarnings("unused") @Assisted StringBuilder sb) {}
| ConcreteAssistedWithOverride |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/planner/PlannerUtils.java | {
"start": 4385,
"end": 6523
} | class ____ {
private static final Logger LOGGER = LogManager.getLogger(PlannerUtils.class);
/**
* When the plan contains children like {@code MergeExec} resulted from the planning of commands such as FORK,
* we need to break the plan into sub plans and a main coordinator plan.
* The result pages from each sub plan will be funneled to the main coordinator plan.
* To achieve this, we wire each sub plan with a {@code ExchangeSinkExec} and add a {@code ExchangeSourceExec}
* to the main coordinator plan.
* There is an additional split of each sub plan into a data node plan and coordinator plan.
* This split is not done here, but as part of {@code PlannerUtils#breakPlanBetweenCoordinatorAndDataNode}.
*/
public static Tuple<List<PhysicalPlan>, PhysicalPlan> breakPlanIntoSubPlansAndMainPlan(PhysicalPlan plan) {
var subplans = new Holder<List<PhysicalPlan>>();
PhysicalPlan mainPlan = plan.transformUp(MergeExec.class, me -> {
subplans.set(
me.children()
.stream()
.map(child -> (PhysicalPlan) new ExchangeSinkExec(child.source(), child.output(), false, child))
.toList()
);
return new ExchangeSourceExec(me.source(), me.output(), false);
});
return new Tuple<>(subplans.get(), mainPlan);
}
public static Tuple<PhysicalPlan, PhysicalPlan> breakPlanBetweenCoordinatorAndDataNode(PhysicalPlan plan, Configuration config) {
var dataNodePlan = new Holder<PhysicalPlan>();
// split the given plan when encountering the exchange
PhysicalPlan coordinatorPlan = plan.transformUp(ExchangeExec.class, e -> {
// remember the datanode subplan and wire it to a sink
var subplan = e.child();
dataNodePlan.set(new ExchangeSinkExec(e.source(), e.output(), e.inBetweenAggs(), subplan));
return new ExchangeSourceExec(e.source(), e.output(), e.inBetweenAggs());
});
return new Tuple<>(coordinatorPlan, dataNodePlan.get());
}
public sealed | PlannerUtils |
java | apache__flink | flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/functions/Timestamper.java | {
"start": 1104,
"end": 1181
} | interface ____<T> extends Function {
long timestamp(T element);
}
| Timestamper |
java | quarkusio__quarkus | extensions/hibernate-search-standalone-elasticsearch/runtime/src/main/java/io/quarkus/hibernate/search/standalone/elasticsearch/runtime/mapping/QuarkusHibernateSearchStandaloneMappingConfigurer.java | {
"start": 466,
"end": 1693
} | class ____ implements StandalonePojoMappingConfigurer {
private final MappingStructure structure;
private final Set<Class<?>> rootAnnotationMappedClasses;
public QuarkusHibernateSearchStandaloneMappingConfigurer(MappingStructure structure,
Set<Class<?>> rootAnnotationMappedClasses) {
this.structure = structure;
this.rootAnnotationMappedClasses = rootAnnotationMappedClasses;
}
@Override
public void configure(StandalonePojoMappingConfigurationContext context) {
// Jandex is not available at runtime in Quarkus,
// so Hibernate Search cannot perform classpath scanning on startup.
context.annotationMapping()
.discoverJandexIndexesFromAddedTypes(false)
.buildMissingDiscoveredJandexIndexes(false);
// ... but we do better: we perform classpath scanning during the build,
// and propagate the result here.
context.annotationMapping().add(rootAnnotationMappedClasses);
context.defaultReindexOnUpdate(MappingStructure.DOCUMENT.equals(structure)
? ReindexOnUpdate.SHALLOW
: ReindexOnUpdate.DEFAULT);
}
}
| QuarkusHibernateSearchStandaloneMappingConfigurer |
java | quarkusio__quarkus | test-framework/junit5/src/main/java/io/quarkus/test/junit/main/QuarkusMainTest.java | {
"start": 543,
"end": 649
} | class ____ {@code @Inject} is not supported
* in {@code QuarkusMainTest}.
*
* Methods inside the test | using |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/operator/topn/KeyExtractorForLong.java | {
"start": 2657,
"end": 3223
} | class ____ extends KeyExtractorForLong {
private final LongBlock block;
MinFromAscendingBlock(TopNEncoder encoder, byte nul, byte nonNul, LongBlock block) {
super(encoder, nul, nonNul);
this.block = block;
}
@Override
public int writeKey(BreakingBytesRefBuilder key, int position) {
if (block.isNull(position)) {
return nul(key);
}
return nonNul(key, block.getLong(block.getFirstValueIndex(position)));
}
}
static | MinFromAscendingBlock |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/cache/CacheOnMethodsTest.java | {
"start": 1421,
"end": 1758
} | class ____ {
@Path("with")
@GET
@Cache(maxAge = 100, noStore = true, mustRevalidate = true, isPrivate = true)
public String with() {
return "with";
}
@Path("without")
@GET
public String without() {
return "without";
}
}
}
| ResourceWithCache |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/javaRestTest/java/org/elasticsearch/smoketest/WatcherRestTestCase.java | {
"start": 1100,
"end": 6212
} | class ____ extends ESRestTestCase {
static final String ADMIN_USER = "test_admin";
static final String WATCHER_USER = "watcher_manager";
static final String TEST_PASSWORD = "x-pack-test-password";
static LocalClusterSpecBuilder<ElasticsearchCluster> watcherClusterSpec() {
return ElasticsearchCluster.local()
.module("x-pack-watcher")
.module("x-pack-ilm")
.module("ingest-common")
.module("analysis-common")
.module("lang-mustache")
.setting("xpack.ml.enabled", "false")
.setting("xpack.license.self_generated.type", "trial")
.setting("logger.org.elasticsearch.xpack.watcher", "debug")
.setting("logger.org.elasticsearch.xpack.core.watcher", "debug")
.user(ADMIN_USER, TEST_PASSWORD, "superuser", true);
}
@Override
protected Settings restClientSettings() {
String token = basicAuthHeaderValue(WATCHER_USER, new SecureString(TEST_PASSWORD.toCharArray()));
return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).build();
}
@Override
protected Settings restAdminSettings() {
String token = basicAuthHeaderValue(ADMIN_USER, new SecureString(TEST_PASSWORD.toCharArray()));
return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).build();
}
@Before
public final void startWatcher() throws Exception {
ESTestCase.assertBusy(() -> {
Response response = ESRestTestCase.adminClient().performRequest(new Request("GET", "/_watcher/stats"));
String state = ObjectPath.createFromResponse(response).evaluate("stats.0.watcher_state");
switch (state) {
case "stopped":
Response startResponse = ESRestTestCase.adminClient().performRequest(new Request("POST", "/_watcher/_start"));
boolean isAcknowledged = ObjectPath.createFromResponse(startResponse).evaluate("acknowledged");
assertThat(isAcknowledged, is(true));
throw new AssertionError("waiting until stopped state reached started state");
case "stopping":
throw new AssertionError("waiting until stopping state reached stopped state to start again");
case "starting":
throw new AssertionError("waiting until starting state reached started state");
case "started":
// all good here, we are done
break;
default:
throw new AssertionError("unknown state[" + state + "]");
}
});
}
@After
public final void stopWatcher() throws Exception {
ESTestCase.assertBusy(() -> {
Response response = ESRestTestCase.adminClient().performRequest(new Request("GET", "/_watcher/stats"));
String state = ObjectPath.createFromResponse(response).evaluate("stats.0.watcher_state");
switch (state) {
case "stopped":
// all good here, we are done
break;
case "stopping":
throw new AssertionError("waiting until stopping state reached stopped state");
case "starting":
throw new AssertionError("waiting until starting state reached started state to stop");
case "started":
Response stopResponse = ESRestTestCase.adminClient().performRequest(new Request("POST", "/_watcher/_stop"));
boolean isAcknowledged = ObjectPath.createFromResponse(stopResponse).evaluate("acknowledged");
assertThat(isAcknowledged, is(true));
throw new AssertionError("waiting until started state reached stopped state");
default:
throw new AssertionError("unknown state[" + state + "]");
}
}, 60, TimeUnit.SECONDS);
deleteAllWatcherData();
}
public static void deleteAllWatcherData() throws IOException {
var queryWatchesRequest = new Request("GET", "/_watcher/_query/watches");
var response = ObjectPath.createFromResponse(ESRestTestCase.adminClient().performRequest(queryWatchesRequest));
int totalCount = response.evaluate("count");
List<Map<?, ?>> watches = response.evaluate("watches");
assert watches.size() == totalCount : "number of watches returned is unequal to the total number of watches";
for (Map<?, ?> watch : watches) {
String id = (String) watch.get("_id");
var deleteWatchRequest = new Request("DELETE", "/_watcher/watch/" + id);
assertOK(ESRestTestCase.adminClient().performRequest(deleteWatchRequest));
}
var deleteWatchHistoryRequest = new Request("DELETE", ".watcher-history-*");
deleteWatchHistoryRequest.addParameter("ignore_unavailable", "true");
ESRestTestCase.adminClient().performRequest(deleteWatchHistoryRequest);
}
}
| WatcherRestTestCase |
java | quarkusio__quarkus | extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/typesafe/DataNamespaceValidationTest.java | {
"start": 1403,
"end": 1491
} | class ____ {
@TemplateGlobal
static String item = "Item";
}
}
| Globals |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/RescaleMappings.java | {
"start": 1660,
"end": 6631
} | class ____ implements Serializable {
public static final RescaleMappings SYMMETRIC_IDENTITY =
RescaleMappings.identity(Integer.MAX_VALUE, Integer.MAX_VALUE);
static final int[] EMPTY_TARGETS = new int[0];
private static final long serialVersionUID = -8719670050630674631L;
private final int numberOfSources;
/**
* The mapping from source to multiple targets. In most cases, the targets arrays are of
* different sizes.
*/
private final int[][] mappings;
private final int numberOfTargets;
RescaleMappings(int numberOfSources, int[][] mappings, int numberOfTargets) {
this.numberOfSources = numberOfSources;
this.mappings = checkNotNull(mappings);
this.numberOfTargets = numberOfTargets;
}
public static RescaleMappings identity(int numberOfSources, int numberOfTargets) {
return new IdentityRescaleMappings(numberOfSources, numberOfTargets);
}
public boolean isIdentity() {
return false;
}
public int[] getMappedIndexes(int sourceIndex) {
if (sourceIndex >= mappings.length) {
return EMPTY_TARGETS;
}
return mappings[sourceIndex];
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final RescaleMappings that = (RescaleMappings) o;
return Arrays.deepEquals(mappings, that.mappings);
}
@Override
public int hashCode() {
return Arrays.deepHashCode(mappings);
}
@Override
public String toString() {
return "RescaleMappings{" + "mappings=" + Arrays.deepToString(mappings) + '}';
}
public RescaleMappings invert() {
IntArrayList[] inverted = new IntArrayList[numberOfTargets];
for (int source = 0; source < mappings.length; source++) {
final int[] targets = mappings[source];
for (int target : targets) {
IntArrayList sources = inverted[target];
if (sources == null) {
inverted[target] = sources = new IntArrayList(1);
}
sources.add(source);
}
}
return of(Arrays.stream(inverted).map(RescaleMappings::toSortedArray), numberOfSources);
}
public Set<Integer> getAmbiguousTargets() {
final Set<Integer> ambiguousTargets =
CollectionUtil.newHashSetWithExpectedSize(numberOfTargets);
final BitSet usedTargets = new BitSet(numberOfTargets);
for (int[] targets : mappings) {
for (int target : targets) {
if (usedTargets.get(target)) {
ambiguousTargets.add(target);
} else {
usedTargets.set(target);
}
}
}
return ambiguousTargets;
}
public static RescaleMappings of(Stream<int[]> mappedTargets, int numberOfTargets) {
final int[][] mappings =
mappedTargets
.map(targets -> targets.length == 0 ? EMPTY_TARGETS : targets)
.toArray(int[][]::new);
if (isIdentity(mappings, numberOfTargets)) {
return new IdentityRescaleMappings(mappings.length, numberOfTargets);
}
int lastNonEmpty = mappings.length - 1;
for (; lastNonEmpty >= 0; lastNonEmpty--) {
if (mappings[lastNonEmpty] != EMPTY_TARGETS) {
break;
}
}
int length = lastNonEmpty + 1;
return new RescaleMappings(
mappings.length,
length == mappings.length ? mappings : Arrays.copyOf(mappings, length),
numberOfTargets);
}
private static boolean isIdentity(int[][] mappings, int numberOfTargets) {
if (mappings.length < numberOfTargets) {
return false;
}
for (int source = numberOfTargets; source < mappings.length; source++) {
if (mappings[source] != EMPTY_TARGETS) {
return false;
}
}
for (int source = 0; source < numberOfTargets; source++) {
if (mappings[source].length != 1 || source != mappings[source][0]) {
return false;
}
}
return true;
}
private static int[] toSortedArray(IntArrayList sourceList) {
if (sourceList == null) {
return EMPTY_TARGETS;
}
final int[] sources = sourceList.toArray();
Arrays.sort(sources);
return sources;
}
@VisibleForTesting
int getNumberOfSources() {
return numberOfSources;
}
@VisibleForTesting
int getNumberOfTargets() {
return numberOfTargets;
}
@VisibleForTesting
int[][] getMappings() {
return mappings;
}
private static final | RescaleMappings |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/plan/physical/DissectExecSerializationTests.java | {
"start": 877,
"end": 2655
} | class ____ extends AbstractPhysicalPlanSerializationTests<DissectExec> {
public static DissectExec randomDissectExec(int depth) {
Source source = randomSource();
PhysicalPlan child = randomChild(depth);
Expression inputExpression = FieldAttributeTests.createFieldAttribute(1, false);
Dissect.Parser parser = DissectSerializationTests.randomParser();
List<Attribute> extracted = randomFieldAttributes(0, 4, false);
return new DissectExec(source, child, inputExpression, parser, extracted);
}
@Override
protected DissectExec createTestInstance() {
return randomDissectExec(0);
}
@Override
protected DissectExec mutateInstance(DissectExec instance) throws IOException {
PhysicalPlan child = instance.child();
Expression inputExpression = FieldAttributeTests.createFieldAttribute(1, false);
Dissect.Parser parser = DissectSerializationTests.randomParser();
List<Attribute> extracted = randomFieldAttributes(0, 4, false);
switch (between(0, 3)) {
case 0 -> child = randomValueOtherThan(child, () -> randomChild(0));
case 1 -> inputExpression = randomValueOtherThan(inputExpression, () -> FieldAttributeTests.createFieldAttribute(1, false));
case 2 -> parser = randomValueOtherThan(parser, DissectSerializationTests::randomParser);
case 3 -> extracted = randomValueOtherThan(extracted, () -> randomFieldAttributes(0, 4, false));
default -> throw new IllegalStateException();
}
return new DissectExec(instance.source(), child, inputExpression, parser, extracted);
}
@Override
protected boolean alwaysEmptySource() {
return true;
}
}
| DissectExecSerializationTests |
java | apache__flink | flink-core/src/main/java/org/apache/flink/configuration/GlobalConfiguration.java | {
"start": 1324,
"end": 10538
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(GlobalConfiguration.class);
public static final String FLINK_CONF_FILENAME = "config.yaml";
// key separator character
private static final String KEY_SEPARATOR = ".";
// the keys whose values should be hidden
private static final String[] SENSITIVE_KEYS =
new String[] {
"password",
"secret",
"fs.azure.account.key",
"apikey",
"api-key",
"auth-params",
"service-key",
"token",
"basic-auth",
"jaas.config",
"http-headers"
};
// the hidden content to be displayed
public static final String HIDDEN_CONTENT = "******";
// --------------------------------------------------------------------------------------------
private GlobalConfiguration() {}
// --------------------------------------------------------------------------------------------
/**
* Loads the global configuration from the environment. Fails if an error occurs during loading.
* Returns an empty configuration object if the environment variable is not set. In production
* this variable is set but tests and local execution/debugging don't have this environment
* variable set. That's why we should fail if it is not set.
*
* @return Returns the Configuration
*/
public static Configuration loadConfiguration() {
return loadConfiguration(new Configuration());
}
/**
* Loads the global configuration and adds the given dynamic properties configuration.
*
* @param dynamicProperties The given dynamic properties
* @return Returns the loaded global configuration with dynamic properties
*/
public static Configuration loadConfiguration(Configuration dynamicProperties) {
final String configDir = System.getenv(ConfigConstants.ENV_FLINK_CONF_DIR);
if (configDir == null) {
return new Configuration(dynamicProperties);
}
return loadConfiguration(configDir, dynamicProperties);
}
/**
* Loads the configuration files from the specified directory.
*
* <p>YAML files are supported as configuration files.
*
* @param configDir the directory which contains the configuration files
*/
public static Configuration loadConfiguration(final String configDir) {
return loadConfiguration(configDir, null);
}
/**
* Loads the configuration files from the specified directory. If the dynamic properties
* configuration is not null, then it is added to the loaded configuration.
*
* @param configDir directory to load the configuration from
* @param dynamicProperties configuration file containing the dynamic properties. Null if none.
* @return The configuration loaded from the given configuration directory
*/
public static Configuration loadConfiguration(
final String configDir, @Nullable final Configuration dynamicProperties) {
if (configDir == null) {
throw new IllegalArgumentException(
"Given configuration directory is null, cannot load configuration");
}
final File confDirFile = new File(configDir);
if (!(confDirFile.exists())) {
throw new IllegalConfigurationException(
"The given configuration directory name '"
+ configDir
+ "' ("
+ confDirFile.getAbsolutePath()
+ ") does not describe an existing directory.");
}
// get Flink yaml configuration file
Configuration configuration;
File yamlConfigFile = new File(confDirFile, FLINK_CONF_FILENAME);
if (!yamlConfigFile.exists()) {
throw new IllegalConfigurationException(
"The Flink config file '"
+ yamlConfigFile
+ "' ("
+ yamlConfigFile.getAbsolutePath()
+ ") does not exist.");
} else {
LOG.info(
"Using standard YAML parser to load flink configuration file from {}.",
yamlConfigFile.getAbsolutePath());
configuration = loadYAMLResource(yamlConfigFile);
}
logConfiguration("Loading", configuration);
if (dynamicProperties != null) {
logConfiguration("Loading dynamic", dynamicProperties);
configuration.addAll(dynamicProperties);
}
return configuration;
}
private static void logConfiguration(String prefix, Configuration config) {
config.confData.forEach(
(key, value) ->
LOG.info(
"{} configuration property: {}, {}",
prefix,
key,
isSensitive(key) ? HIDDEN_CONTENT : value));
}
/**
* Flattens a nested configuration map to be only one level deep.
*
* <p>Nested keys are concatinated using the {@code KEY_SEPARATOR} character. So that:
*
* <pre>
* keyA:
* keyB:
* keyC: "hello"
* keyD: "world"
* </pre>
*
* <p>becomes:
*
* <pre>
* keyA.keyB.keyC: "hello"
* keyA.keyB.keyD: "world"
* </pre>
*
* @param config an arbitrarily nested config map
* @param keyPrefix The string to prefix the keys in the current config level
* @param flattenedMap The flattened, 1 level deep map contains all key-value pairs to be
* returned.
*/
@SuppressWarnings("unchecked")
private static void flatten(
Map<String, Object> config, String keyPrefix, Map<String, Object> flattenedMap) {
config.forEach(
(key, value) -> {
String flattenedKey = keyPrefix + key;
if (value instanceof Map) {
Map<String, Object> nestedMap = (Map<String, Object>) value;
flatten(nestedMap, flattenedKey + KEY_SEPARATOR, flattenedMap);
} else {
if (value instanceof List) {
flattenedMap.put(flattenedKey, YamlParserUtils.toYAMLString(value));
} else {
flattenedMap.put(flattenedKey, value);
}
}
});
}
private static Map<String, Object> flatten(Map<String, Object> config) {
// Since we start flattening from the root, keys should not be prefixed with anything.
final Map<String, Object> flattenedMap = new HashMap<>();
flatten(config, "", flattenedMap);
return flattenedMap;
}
/**
* Loads a YAML-file of key-value pairs.
*
* <p>Keys can be expressed either as nested keys or as {@literal KEY_SEPARATOR} separated keys.
* For example, the following configurations are equivalent:
*
* <pre>
* jobmanager.rpc.address: localhost # network address for communication with the job manager
* jobmanager.rpc.port : 6123 # network port to connect to for communication with the job manager
* taskmanager.rpc.port : 6122 # network port the task manager expects incoming IPC connections
* </pre>
*
* <pre>
* jobmanager:
* rpc:
* address: localhost # network address for communication with the job manager
* port: 6123 # network port to connect to for communication with the job manager
* taskmanager:
* rpc:
* port: 6122 # network port the task manager expects incoming IPC connections
* </pre>
*
* @param file the YAML file to read from
* @see <a href="http://www.yaml.org/spec/1.2/spec.html">YAML 1.2 specification</a>
*/
private static Configuration loadYAMLResource(File file) {
final Configuration config = new Configuration();
try {
Map<String, Object> configDocument = flatten(YamlParserUtils.loadYamlFile(file));
configDocument.forEach((k, v) -> config.setValueInternal(k, v, false));
return config;
} catch (Exception e) {
throw new RuntimeException("Error parsing YAML configuration.", e);
}
}
/**
* Check whether the key is a hidden key.
*
* @param key the config key
*/
public static boolean isSensitive(String key) {
Preconditions.checkNotNull(key, "key is null");
final String keyInLower = key.toLowerCase();
for (String hideKey : SENSITIVE_KEYS) {
if (keyInLower.length() >= hideKey.length() && keyInLower.contains(hideKey)) {
return true;
}
}
return false;
}
public static String getFlinkConfFilename() {
return FLINK_CONF_FILENAME;
}
}
| GlobalConfiguration |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/webmonitor/threadinfo/VertexFlameGraph.java | {
"start": 2996,
"end": 4761
} | class ____ {
// These field names are required by the library used in the WebUI.
private static final String FIELD_NAME_NAME = "name";
private static final String FIELD_NAME_VALUE = "value";
private static final String FIELD_NAME_CHILDREN = "children";
@JsonProperty(FIELD_NAME_NAME)
private final String stackTraceLocation;
@JsonProperty(FIELD_NAME_VALUE)
private final int hitCount;
@JsonProperty(FIELD_NAME_CHILDREN)
private final List<Node> children;
@JsonCreator
Node(
@JsonProperty(FIELD_NAME_NAME) String stackTraceLocation,
@JsonProperty(FIELD_NAME_VALUE) int hitCount,
@JsonProperty(FIELD_NAME_CHILDREN) List<Node> children) {
this.stackTraceLocation = stackTraceLocation;
this.hitCount = hitCount;
this.children = children;
}
@JsonIgnore
public String getStackTraceLocation() {
return stackTraceLocation;
}
@JsonIgnore
public int getHitCount() {
return hitCount;
}
@JsonIgnore
public List<Node> getChildren() {
return children;
}
@Override
public String toString() {
return getStackTraceLocation()
+ ": "
+ getHitCount()
+ "\n"
+ "\t"
+ toStringChildren();
}
private String toStringChildren() {
StringBuilder sb = new StringBuilder();
for (Node child : getChildren()) {
sb.append(child.toString());
}
return sb.toString();
}
}
}
| Node |
java | apache__flink | flink-formats/flink-orc/src/main/java/org/apache/flink/orc/OrcColumnarRowSplitReader.java | {
"start": 1312,
"end": 2755
} | class ____<BATCH> extends OrcSplitReader<RowData, BATCH> {
// the vector of rows that is read in a batch
private final VectorizedColumnBatch columnarBatch;
private final ColumnarRowData row;
public OrcColumnarRowSplitReader(
OrcShim<BATCH> shim,
Configuration conf,
TypeDescription schema,
int[] selectedFields,
ColumnBatchGenerator<BATCH> batchGenerator,
List<OrcFilters.Predicate> conjunctPredicates,
int batchSize,
Path path,
long splitStart,
long splitLength)
throws IOException {
super(
shim,
conf,
schema,
selectedFields,
conjunctPredicates,
batchSize,
path,
splitStart,
splitLength);
this.columnarBatch = batchGenerator.generate(rowBatchWrapper.getBatch());
this.row = new ColumnarRowData(columnarBatch);
}
@Override
protected int fillRows() {
int size = rowBatchWrapper.size();
columnarBatch.setNumRows(size);
return size;
}
@Override
public RowData nextRecord(RowData reuse) {
// return the next row
row.setRowId(this.nextRow++);
return row;
}
/** Interface to gen {@link VectorizedColumnBatch}. */
public | OrcColumnarRowSplitReader |
java | resilience4j__resilience4j | resilience4j-micrometer/src/test/java/io/github/resilience4j/micrometer/tagged/TaggedCircuitBreakerMetricsTest.java | {
"start": 1600,
"end": 10209
} | class ____ {
private MeterRegistry meterRegistry;
private CircuitBreaker circuitBreaker;
private CircuitBreakerRegistry circuitBreakerRegistry;
private TaggedCircuitBreakerMetrics taggedCircuitBreakerMetrics;
@Before
public void setUp() {
meterRegistry = new SimpleMeterRegistry();
circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
CircuitBreakerConfig configWithSlowCallThreshold = CircuitBreakerConfig.custom()
.slowCallDurationThreshold(Duration.ofSeconds(1)).build();
circuitBreaker = circuitBreakerRegistry
.circuitBreaker("backendA", configWithSlowCallThreshold);
// record some basic stats
circuitBreaker.onSuccess(0, TimeUnit.NANOSECONDS);
circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("oops"));
// record slow calls
circuitBreaker.onSuccess(2000, TimeUnit.NANOSECONDS);
circuitBreaker.onError(2000, TimeUnit.NANOSECONDS, new RuntimeException("oops"));
taggedCircuitBreakerMetrics = TaggedCircuitBreakerMetrics
.ofCircuitBreakerRegistry(circuitBreakerRegistry);
taggedCircuitBreakerMetrics.bindTo(meterRegistry);
}
@Test
public void shouldAddMetricsForANewlyCreatedCircuitBreaker() {
CircuitBreaker newCircuitBreaker = circuitBreakerRegistry.circuitBreaker("backendB");
newCircuitBreaker.onSuccess(0, TimeUnit.NANOSECONDS);
assertThat(taggedCircuitBreakerMetrics.meterIdMap).containsKeys("backendA", "backendB");
assertThat(taggedCircuitBreakerMetrics.meterIdMap.get("backendA")).hasSize(16);
assertThat(taggedCircuitBreakerMetrics.meterIdMap.get("backendB")).hasSize(16);
List<Meter> meters = meterRegistry.getMeters();
assertThat(meters).hasSize(32);
Collection<Gauge> gauges = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_BUFFERED_CALLS)
.gauges();
Optional<Gauge> successful = MetricsTestHelper
.findMeterByKindAndNameTags(gauges, "successful",
newCircuitBreaker.getName());
assertThat(successful).isPresent();
assertThat(successful.get().value())
.isEqualTo(newCircuitBreaker.getMetrics().getNumberOfSuccessfulCalls());
}
@Test
public void shouldAddCustomTags() {
CircuitBreaker circuitBreakerF = circuitBreakerRegistry.circuitBreaker("backendF", Map.of("key1", "value1"));
circuitBreakerF.onSuccess(0, TimeUnit.NANOSECONDS);
assertThat(taggedCircuitBreakerMetrics.meterIdMap).containsKeys("backendA", "backendF");
assertThat(taggedCircuitBreakerMetrics.meterIdMap.get("backendF")).hasSize(16);
List<Meter> meters = meterRegistry.getMeters();
assertThat(meters).hasSize(32);
final RequiredSearch match = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_BUFFERED_CALLS).tags("key1", "value1");
assertThat(match).isNotNull();
}
@Test
public void shouldRemovedMetricsForRemovedRetry() {
List<Meter> meters = meterRegistry.getMeters();
assertThat(meters).hasSize(16);
assertThat(taggedCircuitBreakerMetrics.meterIdMap).containsKeys("backendA");
circuitBreakerRegistry.remove("backendA");
assertThat(taggedCircuitBreakerMetrics.meterIdMap).isEmpty();
meters = meterRegistry.getMeters();
assertThat(meters).isEmpty();
}
@Test
public void notPermittedCallsCounterReportsCorrespondingValue() {
List<Meter> meters = meterRegistry.getMeters();
assertThat(meters).hasSize(16);
Collection<Counter> counters = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_NOT_PERMITTED_CALLS).counters();
Optional<Counter> notPermitted = findMeterByKindAndNameTags(counters, "not_permitted",
circuitBreaker.getName());
assertThat(notPermitted).isPresent();
assertThat(notPermitted.get().count())
.isEqualTo(circuitBreaker.getMetrics().getNumberOfNotPermittedCalls());
}
@Test
public void failedCallsGaugeReportsCorrespondingValue() {
Collection<Gauge> gauges = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_BUFFERED_CALLS)
.gauges();
Optional<Gauge> failed = MetricsTestHelper.findMeterByKindAndNameTags(gauges, "failed",
circuitBreaker.getName());
assertThat(failed).isPresent();
assertThat(failed.get().value())
.isEqualTo(circuitBreaker.getMetrics().getNumberOfFailedCalls());
}
@Test
public void successfulCallsGaugeReportsCorrespondingValue() {
Collection<Gauge> gauges = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_BUFFERED_CALLS)
.gauges();
Optional<Gauge> successful = MetricsTestHelper
.findMeterByKindAndNameTags(gauges, "successful",
circuitBreaker.getName());
assertThat(successful).isPresent();
assertThat(successful.get().value())
.isEqualTo(circuitBreaker.getMetrics().getNumberOfSuccessfulCalls());
}
@Test
public void slowSuccessfulGaugeReportsCorrespondingValue() {
Collection<Gauge> gauges = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_SLOW_CALLS).gauges();
Optional<Gauge> slow = MetricsTestHelper.findMeterByKindAndNameTags(gauges, "successful",
circuitBreaker.getName());
assertThat(slow).isPresent();
assertThat(slow.get().value())
.isEqualTo(circuitBreaker.getMetrics().getNumberOfSlowCalls());
}
@Test
public void slowFailedCallsGaugeReportsCorrespondingValue() {
Collection<Gauge> gauges = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_SLOW_CALLS).gauges();
Optional<Gauge> slow = MetricsTestHelper.findMeterByKindAndNameTags(gauges, "failed",
circuitBreaker.getName());
assertThat(slow).isPresent();
assertThat(slow.get().value())
.isEqualTo(circuitBreaker.getMetrics().getNumberOfSlowCalls());
}
@Test
public void failureRateGaugeReportsCorrespondingValue() {
Gauge failureRate = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_FAILURE_RATE).gauge();
assertThat(failureRate).isNotNull();
assertThat(failureRate.value()).isEqualTo(circuitBreaker.getMetrics().getFailureRate());
assertThat(failureRate.getId().getTag(TagNames.NAME)).isEqualTo(circuitBreaker.getName());
}
@Test
public void slowCallRateGaugeReportsCorrespondingValue() {
Gauge slowCallRate = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_SLOW_CALL_RATE).gauge();
assertThat(slowCallRate).isNotNull();
assertThat(slowCallRate.value()).isEqualTo(circuitBreaker.getMetrics().getSlowCallRate());
assertThat(slowCallRate.getId().getTag(TagNames.NAME)).isEqualTo(circuitBreaker.getName());
}
@Test
public void stateGaugeReportsCorrespondingValue() {
Gauge state = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_STATE).gauge();
assertThat(state.value()).isEqualTo(circuitBreaker.getState().getOrder());
assertThat(state.getId().getTag(TagNames.NAME)).isEqualTo(circuitBreaker.getName());
}
@Test
public void metricsAreRegisteredWithCustomName() {
MeterRegistry meterRegistry = new SimpleMeterRegistry();
CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
circuitBreakerRegistry.circuitBreaker("backendA");
TaggedCircuitBreakerMetrics.ofCircuitBreakerRegistry(
CircuitBreakerMetricNames.custom()
.callsMetricName("custom_calls")
.notPermittedCallsMetricName("custom_not_permitted_calls")
.stateMetricName("custom_state")
.bufferedCallsMetricName("custom_buffered_calls")
.slowCallsMetricName("custom_slow_calls")
.failureRateMetricName("custom_failure_rate")
.slowCallRateMetricName("custom_slow_call_rate")
.build(),
circuitBreakerRegistry
).bindTo(meterRegistry);
Set<String> metricNames = meterRegistry.getMeters()
.stream()
.map(Meter::getId)
.map(Meter.Id::getName)
.collect(Collectors.toSet());
assertThat(metricNames).hasSameElementsAs(Arrays.asList(
"custom_calls",
"custom_not_permitted_calls",
"custom_state",
"custom_buffered_calls",
"custom_slow_calls",
"custom_failure_rate",
"custom_slow_call_rate"
));
}
}
| TaggedCircuitBreakerMetricsTest |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/diskbalancer/planner/GreedyPlanner.java | {
"start": 1631,
"end": 9513
} | class ____ implements Planner {
public static final long MB = 1024L * 1024L;
public static final long GB = MB * 1024L;
public static final long TB = GB * 1024L;
private static final Logger LOG =
LoggerFactory.getLogger(GreedyPlanner.class);
private final double threshold;
/**
* Constructs a greedy planner.
*
* @param threshold - Disk tolerance that we are ok with
* @param node - node on which this planner is operating upon
*/
public GreedyPlanner(double threshold, DiskBalancerDataNode node) {
this.threshold = threshold;
}
/**
* Computes a node plan for the given node.
*
* @return NodePlan
* @throws Exception
*/
@Override
public NodePlan plan(DiskBalancerDataNode node) throws Exception {
final long startTime = Time.monotonicNow();
NodePlan plan = new NodePlan(node.getDataNodeName(),
node.getDataNodePort());
LOG.info("Starting plan for Node : {}:{}",
node.getDataNodeName(), node.getDataNodePort());
while (node.isBalancingNeeded(this.threshold)) {
for (DiskBalancerVolumeSet vSet : node.getVolumeSets().values()) {
balanceVolumeSet(node, vSet, plan);
}
}
final long endTime = Time.monotonicNow();
LOG.info("Compute Plan for Node : {}:{} took {} ms",
node.getDataNodeName(), node.getDataNodePort(), endTime - startTime);
return plan;
}
/**
* Computes Steps to make a DiskBalancerVolumeSet Balanced.
*
* @param node
* @param vSet - DiskBalancerVolumeSet
* @param plan - NodePlan
*/
public void balanceVolumeSet(DiskBalancerDataNode node,
DiskBalancerVolumeSet vSet, NodePlan plan)
throws Exception {
Preconditions.checkNotNull(vSet);
Preconditions.checkNotNull(plan);
Preconditions.checkNotNull(node);
DiskBalancerVolumeSet currentSet = new DiskBalancerVolumeSet(vSet);
while (currentSet.isBalancingNeeded(this.threshold)) {
removeSkipVolumes(currentSet);
DiskBalancerVolume lowVolume = currentSet.getSortedQueue().first();
DiskBalancerVolume highVolume = currentSet.getSortedQueue().last();
Step nextStep = null;
// ok both volumes bytes used are in the range that we expect
// Then we create a move request.
if (!lowVolume.isSkip() && !highVolume.isSkip()) {
nextStep = computeMove(currentSet, lowVolume, highVolume);
} else {
LOG.debug("Skipping compute move. lowVolume: {} highVolume: {}",
lowVolume.getPath(), highVolume.getPath());
}
applyStep(nextStep, currentSet, lowVolume, highVolume);
if (nextStep != null) {
LOG.debug("Step : {} ", nextStep);
plan.addStep(nextStep);
}
}
LOG.info("Disk Volume set {} - Type : {} plan completed.",
currentSet.getSetID(),
currentSet.getVolumes().get(0).getStorageType());
plan.setNodeName(node.getDataNodeName());
plan.setNodeUUID(node.getDataNodeUUID());
plan.setTimeStamp(Time.now());
plan.setPort(node.getDataNodePort());
}
/**
* Apply steps applies the current step on to a volumeSet so that we can
* compute next steps until we reach the desired goals.
*
* @param nextStep - nextStep or Null
* @param currentSet - Current Disk BalancerVolume Set we are operating upon
* @param lowVolume - volume
* @param highVolume - volume
*/
private void applyStep(Step nextStep, DiskBalancerVolumeSet currentSet,
DiskBalancerVolume lowVolume,
DiskBalancerVolume highVolume) throws Exception {
long used;
if (nextStep != null) {
used = lowVolume.getUsed() + nextStep.getBytesToMove();
lowVolume.setUsed(used);
used = highVolume.getUsed() - nextStep.getBytesToMove();
highVolume.setUsed(used);
}
// since the volume data changed , we need to recompute the DataDensity.
currentSet.computeVolumeDataDensity();
printQueue(currentSet.getSortedQueue());
}
/**
* Computes a data move from the largest disk we have to smallest disk.
*
* @param currentSet - Current Disk Set we are working with
* @param lowVolume - Low Data Capacity Volume
* @param highVolume - High Data Capacity Volume
* @return Step
*/
private Step computeMove(DiskBalancerVolumeSet currentSet,
DiskBalancerVolume lowVolume,
DiskBalancerVolume highVolume) {
// Compute how many bytes we can move. First Compute the maximum that
// low Volume Can receive, then compute maximum high volume can give
// Then take the minimum of those two numbers that is the bytesToMove.
long maxLowVolumeCanReceive = (long) (
(currentSet.getIdealUsed() * lowVolume.computeEffectiveCapacity()) -
lowVolume.getUsed());
// This disk cannot take any more data from any disk.
// Remove it from our computation matrix.
if (maxLowVolumeCanReceive <= 0) {
LOG.debug("{} Skipping disk from computation. Maximum data size " +
"achieved.", lowVolume.getPath());
skipVolume(currentSet, lowVolume);
}
long maxHighVolumeCanGive = highVolume.getUsed() -
(long) (currentSet.getIdealUsed() *
highVolume.computeEffectiveCapacity());
// This volume cannot give any more data, remove it from the
// computation matrix
if (maxHighVolumeCanGive <= 0) {
LOG.debug(" {} Skipping disk from computation. Minimum data size " +
"achieved.", highVolume.getPath());
skipVolume(currentSet, highVolume);
}
long bytesToMove = Math.min(maxLowVolumeCanReceive, maxHighVolumeCanGive);
Step nextStep = null;
if (bytesToMove > 0) {
// Create a new step
nextStep = new MoveStep(highVolume, currentSet.getIdealUsed(), lowVolume,
bytesToMove, currentSet.getSetID());
LOG.debug("Next Step: {}", nextStep);
}
return nextStep;
}
/**
* Skips this volume if needed.
*
* @param currentSet - Current Disk set
* @param volume - Volume
*/
private void skipVolume(DiskBalancerVolumeSet currentSet,
DiskBalancerVolume volume) {
if (LOG.isDebugEnabled()) {
String message =
String.format(
"Skipping volume. Volume : %s " +
"Type : %s Target " +
"Number of bytes : %f lowVolume dfsUsed : %d. Skipping this " +
"volume from all future balancing calls.", volume.getPath(),
volume.getStorageType(),
currentSet.getIdealUsed() * volume.getCapacity(),
volume.getUsed());
LOG.debug(message);
}
volume.setSkip(true);
}
// Removes all volumes which are part of the volumeSet but skip flag is set.
private void removeSkipVolumes(DiskBalancerVolumeSet currentSet) {
List<DiskBalancerVolume> volumeList = currentSet.getVolumes();
Iterator<DiskBalancerVolume> volumeIterator = volumeList.iterator();
while (volumeIterator.hasNext()) {
DiskBalancerVolume vol = volumeIterator.next();
if (vol.isSkip() || vol.isFailed()) {
currentSet.removeVolume(vol);
}
}
currentSet.computeVolumeDataDensity();
printQueue(currentSet.getSortedQueue());
}
/**
* This function is used only for debugging purposes to ensure queue looks
* correct.
*
* @param queue - Queue
*/
private void printQueue(TreeSet<DiskBalancerVolume> queue) {
if (LOG.isDebugEnabled()) {
String format =
String.format(
"First Volume : %s, DataDensity : %f, " +
"Last Volume : %s, DataDensity : %f",
queue.first().getPath(), queue.first().getVolumeDataDensity(),
queue.last().getPath(), queue.last().getVolumeDataDensity());
LOG.debug(format);
}
}
}
| GreedyPlanner |
java | hibernate__hibernate-orm | hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/GaussDBArrayJdbcType.java | {
"start": 925,
"end": 979
} | class ____ based on PostgreSQLArrayJdbcType.
*/
public | is |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/pool/ConfigErrorTest2.java | {
"start": 854,
"end": 1762
} | class ____ extends PoolTestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
super.setUp();
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:wrap-jdbc:jdbc:mock:xxx");
dataSource.setTestOnBorrow(false);
dataSource.setTestOnReturn(false);
dataSource.setTestWhileIdle(false);
}
protected void tearDown() throws Exception {
dataSource.close();
super.tearDown();
}
public void test_connect() throws Exception {
Field field = DruidDataSource.class.getDeclaredField("LOG");
field.setAccessible(true);
Log LOG = (Log) field.get(null);
LOG.resetStat();
assertEquals(0, LOG.getErrorCount());
Connection conn = dataSource.getConnection();
conn.close();
assertTrue(LOG.getErrorCount() >= 1);
}
}
| ConfigErrorTest2 |
java | square__retrofit | retrofit/java-test/src/test/java/retrofit2/RequestFactoryTest.java | {
"start": 6329,
"end": 6898
} | class ____ {
@PATCH("/foo") //
@POST("/foo") //
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessageThat()
.isAnyOf(
"Only one HTTP method is allowed. Found: PATCH and POST.\n for method Example.method",
"Only one HTTP method is allowed. Found: POST and PATCH.\n for method Example.method");
}
}
@Test
public void lackingMethod() {
| Example |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/blob/PermanentBlobCache.java | {
"start": 2271,
"end": 2455
} | class ____ extends AbstractBlobCache implements JobPermanentBlobService {
/** Job reference counters with a time-to-live (TTL). */
@VisibleForTesting
static | PermanentBlobCache |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java | {
"start": 5714,
"end": 6253
} | class ____ extends TypeExcludeFilter {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
AssignableTypeFilter typeFilter = new AssignableTypeFilter(BFirstProperties.class);
return !typeFilter.match(metadataReader, metadataReaderFactory);
}
@Override
public boolean equals(@Nullable Object o) {
return (this == o);
}
@Override
public int hashCode() {
return Objects.hash(42);
}
}
}
| ConfigurationPropertiesTestTypeExcludeFilter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.