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
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/authentication/HttpMessageConverterAuthenticationSuccessHandler.java
{ "start": 3659, "end": 3953 }
class ____ { private final String redirectUrl; private AuthenticationSuccess(String redirectUrl) { this.redirectUrl = redirectUrl; } public String getRedirectUrl() { return this.redirectUrl; } public boolean isAuthenticated() { return true; } } }
AuthenticationSuccess
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedStructWithArrayEmbeddableTest.java
{ "start": 19123, "end": 20084 }
class ____ { @JdbcTypeCode(SqlTypes.ARRAY) private Integer[] integerField; private DoubleNested doubleNested; public SimpleEmbeddable() { } public SimpleEmbeddable(Integer integerField, String leaf) { this.integerField = new Integer[]{ integerField }; this.doubleNested = new DoubleNested( leaf ); } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } SimpleEmbeddable that = (SimpleEmbeddable) o; if ( !Arrays.equals( integerField, that.integerField ) ) { return false; } return Objects.equals( doubleNested, that.doubleNested ); } @Override public int hashCode() { int result = Arrays.hashCode( integerField ); result = 31 * result + ( doubleNested != null ? doubleNested.hashCode() : 0 ); return result; } } @Embeddable @Struct( name = "double_nested") public static
SimpleEmbeddable
java
micronaut-projects__micronaut-core
http-client/src/main/java/io/micronaut/http/client/netty/Http1ResponseHandler.java
{ "start": 3560, "end": 4178 }
class ____<M extends HttpObject> { abstract void read(ChannelHandlerContext ctx, M msg); void channelReadComplete(ChannelHandlerContext ctx) { ctx.read(); } abstract void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); void channelInactive(ChannelHandlerContext ctx) { exceptionCaught(ctx, new ResponseClosedException("Connection closed before response was received")); } void leave(ChannelHandlerContext ctx) { } } /** * Before any response data has been received. */ private final
ReaderState
java
alibaba__nacos
client/src/main/java/com/alibaba/nacos/client/config/impl/YmlChangeParser.java
{ "start": 1331, "end": 4771 }
class ____ extends AbstractConfigChangeParser { private static final String INVALID_CONSTRUCTOR_ERROR_INFO = "could not determine a constructor for the tag"; private static final String CONFIG_TYPE = "yaml"; public YmlChangeParser() { super(CONFIG_TYPE); } @Override public Map<String, ConfigChangeItem> doParse(String oldContent, String newContent, String type) { Map<String, Object> oldMap = Collections.emptyMap(); Map<String, Object> newMap = Collections.emptyMap(); try { Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); if (StringUtils.isNotBlank(oldContent)) { oldMap = yaml.load(oldContent); oldMap = getFlattenedMap(oldMap); } if (StringUtils.isNotBlank(newContent)) { newMap = yaml.load(newContent); newMap = getFlattenedMap(newMap); } } catch (MarkedYAMLException e) { handleYamlException(e); } return filterChangeData(oldMap, newMap); } private void handleYamlException(MarkedYAMLException e) { if (e.getMessage().startsWith(INVALID_CONSTRUCTOR_ERROR_INFO) || e instanceof ComposerException) { throw new NacosRuntimeException(NacosException.INVALID_PARAM, "AbstractConfigChangeListener only support basic java data type for yaml. If you want to listen " + "key changes for custom classes, please use `Listener` to listener whole yaml configuration and parse it by yourself.", e); } throw e; } private Map<String, Object> getFlattenedMap(Map<String, Object> source) { Map<String, Object> result = new LinkedHashMap<>(128); buildFlattenedMap(result, source, null); return result; } private void buildFlattenedMap(Map<String, Object> result, Map<String, Object> source, String path) { for (Iterator<Map.Entry<String, Object>> itr = source.entrySet().iterator(); itr.hasNext(); ) { Map.Entry<String, Object> e = itr.next(); String key = e.getKey(); if (StringUtils.isNotBlank(path)) { if (e.getKey().startsWith("[")) { key = path + key; } else { key = path + '.' + key; } } if (e.getValue() instanceof String) { result.put(key, e.getValue()); } else if (e.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) e.getValue(); buildFlattenedMap(result, map, key); } else if (e.getValue() instanceof Collection) { @SuppressWarnings("unchecked") Collection<Object> collection = (Collection<Object>) e.getValue(); if (collection.isEmpty()) { result.put(key, ""); } else { int count = 0; for (Object object : collection) { buildFlattenedMap(result, Collections.singletonMap("[" + (count++) + "]", object), key); } } } else { result.put(key, (e.getValue() != null ? e.getValue() : "")); } } } }
YmlChangeParser
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/common/chunks/MemoryIndexChunkScorer.java
{ "start": 1091, "end": 1175 }
class ____ scoring pre-determined chunks using an in-memory Lucene index. */ public
for
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/shell/TestCommandFactory.java
{ "start": 1223, "end": 3301 }
class ____ { static CommandFactory factory; static Configuration conf = new Configuration(); static void registerCommands(CommandFactory factory) { } @BeforeEach public void testSetup() { factory = new CommandFactory(conf); assertNotNull(factory); } @Test public void testRegistration() { assertArrayEquals(new String []{}, factory.getNames()); factory.registerCommands(TestRegistrar.class); String [] names = factory.getNames(); assertArrayEquals(new String []{"tc1", "tc2", "tc2.1"}, names); factory.addClass(TestCommand3.class, "tc3"); names = factory.getNames(); assertArrayEquals(new String []{"tc1", "tc2", "tc2.1", "tc3"}, names); factory.addClass(TestCommand4.class, (new TestCommand4()).getName()); names = factory.getNames(); assertArrayEquals(new String[]{"tc1", "tc2", "tc2.1", "tc3", "tc4"}, names); } @Test public void testGetInstances() { factory.registerCommands(TestRegistrar.class); Command instance; instance = factory.getInstance("blarg"); assertNull(instance); instance = factory.getInstance("tc1"); assertNotNull(instance); assertEquals(TestCommand1.class, instance.getClass()); assertEquals("tc1", instance.getCommandName()); instance = factory.getInstance("tc2"); assertNotNull(instance); assertEquals(TestCommand2.class, instance.getClass()); assertEquals("tc2", instance.getCommandName()); instance = factory.getInstance("tc2.1"); assertNotNull(instance); assertEquals(TestCommand2.class, instance.getClass()); assertEquals("tc2.1", instance.getCommandName()); factory.addClass(TestCommand4.class, "tc4"); instance = factory.getInstance("tc4"); assertNotNull(instance); assertEquals(TestCommand4.class, instance.getClass()); assertEquals("tc4", instance.getCommandName()); String usage = instance.getUsage(); assertEquals("-tc4 tc4_usage", usage); assertEquals("tc4_description", instance.getDescription()); } static
TestCommandFactory
java
quarkusio__quarkus
independent-projects/bootstrap/core/src/test/java/io/quarkus/bootstrap/resolver/test/DependenciesOnDifferentVersionsOfAnArtifactTestCase.java
{ "start": 204, "end": 672 }
class ____ extends CollectDependenciesBase { @Override protected void setupDependencies() { final TsArtifact common1 = new TsArtifact("common", "1"); install(common1, true); installAsDep(new TsArtifact("required-dep1") .addDependency(common1)); installAsDep(new TsArtifact("required-dep2") .addDependency(new TsArtifact("common", "2"))); } }
DependenciesOnDifferentVersionsOfAnArtifactTestCase
java
playframework__playframework
documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaBodyParsers.java
{ "start": 2472, "end": 2820 }
class ____<A> implements BodyParser<A> { // Override the method with another abstract method - if the signature changes, we get a compile // error @Override // #body-parser-apply public abstract Accumulator<ByteString, F.Either<Result, A>> apply(RequestHeader request); // #body-parser-apply } public static
BodyParserApply
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/Schema.java
{ "start": 42077, "end": 48982 }
class ____ { final ParseContext context; private final NameValidator validate; private boolean validateDefaults = true; public Parser() { this(NameValidator.UTF_VALIDATOR); } public Parser(final NameValidator validate) { this.validate = validate != null ? validate : NameValidator.NO_VALIDATION; context = new ParseContext(this.validate); } public Parser(final ParseContext context) { this.validate = context.nameValidator; this.context = context; } /** * Adds the provided types to the set of defined, named types known to this * parser. * * @deprecated use addTypes(Iterable<Schema> types) */ @Deprecated public Parser addTypes(Map<String, Schema> types) { return this.addTypes(types.values()); } /** * Adds the provided types to the set of defined, named types known to this * parser. */ public Parser addTypes(Iterable<Schema> types) { for (Schema s : types) context.put(s); return this; } /** Returns the set of defined, named types known to this parser. */ public Map<String, Schema> getTypes() { return context.typesByName(); } /** Enable or disable default value validation. */ public Parser setValidateDefaults(boolean validateDefaults) { this.validateDefaults = validateDefaults; return this; } /** True iff default values are validated. False by default. */ public boolean getValidateDefaults() { return this.validateDefaults; } /** * Parse a schema from the provided file. If named, the schema is added to the * names known to this parser. */ public Schema parse(File file) throws IOException { return parse(FACTORY.createParser(file), false, true); } /** * Parse a schema from the provided stream. If named, the schema is added to the * names known to this parser. The input stream stays open after the parsing. */ public Schema parse(InputStream in) throws IOException { JsonParser parser = FACTORY.createParser(in).disable(JsonParser.Feature.AUTO_CLOSE_SOURCE); return parse(parser, true, true); } /** Read a schema from one or more json strings */ public Schema parse(String s, String... more) { StringBuilder b = new StringBuilder(s); for (String part : more) b.append(part); return parse(b.toString()); } /** * Parse a schema from the provided string. If named, the schema is added to the * names known to this parser. */ public Schema parse(String s) { try { return parse(FACTORY.createParser(s), false, true); } catch (IOException e) { throw new SchemaParseException(e); } } public Schema parseInternal(String s) { try { return parse(FACTORY.createParser(s), false, false); } catch (IOException e) { throw new SchemaParseException(e); } } private Schema parse(JsonParser parser, boolean allowDanglingContent, boolean resolveSchema) throws IOException { NameValidator saved = VALIDATE_NAMES.get(); boolean savedValidateDefaults = VALIDATE_DEFAULTS.get(); try { // This ensured we're using the same validation as the ParseContext. // This is most relevant for field names. VALIDATE_NAMES.set(validate); VALIDATE_DEFAULTS.set(validateDefaults); JsonNode jsonNode = MAPPER.readTree(parser); Schema schema = Schema.parse(jsonNode, context, null); if (resolveSchema) { context.commit(); schema = context.resolve(schema); } if (!allowDanglingContent) { String dangling; StringWriter danglingWriter = new StringWriter(); int numCharsReleased = parser.releaseBuffered(danglingWriter); if (numCharsReleased == -1) { ByteArrayOutputStream danglingOutputStream = new ByteArrayOutputStream(); parser.releaseBuffered(danglingOutputStream); // if input isn't chars above it must be bytes dangling = new String(danglingOutputStream.toByteArray(), StandardCharsets.UTF_8).trim(); } else { dangling = danglingWriter.toString().trim(); } if (!dangling.isEmpty()) { throw new SchemaParseException("dangling content after end of schema: " + dangling); } } return schema; } catch (JsonParseException e) { throw new SchemaParseException(e); } finally { parser.close(); VALIDATE_NAMES.set(saved); VALIDATE_DEFAULTS.set(savedValidateDefaults); } } } /** * Constructs a Schema object from JSON schema file <tt>file</tt>. The contents * of <tt>file</tt> is expected to be in UTF-8 format. * * @param file The file to read the schema from. * @return The freshly built Schema. * @throws IOException if there was trouble reading the contents, or they are * invalid * @deprecated use {@link SchemaParser} instead. */ @Deprecated public static Schema parse(File file) throws IOException { return new Parser().parse(file); } /** * Constructs a Schema object from JSON schema stream <tt>in</tt>. The contents * of <tt>in</tt> is expected to be in UTF-8 format. * * @param in The input stream to read the schema from. * @return The freshly built Schema. * @throws IOException if there was trouble reading the contents, or they are * invalid * @deprecated use {@link SchemaParser} instead. */ @Deprecated public static Schema parse(InputStream in) throws IOException { return new Parser().parse(in); } /** * Construct a schema from <a href="https://json.org/">JSON</a> text. * * @deprecated use {@link SchemaParser} instead. */ @Deprecated public static Schema parse(String jsonSchema) { return new Parser().parse(jsonSchema); } /** * Construct a schema from <a href="https://json.org/">JSON</a> text. * * @param validate true if names should be validated, false if not. * @deprecated use {@link SchemaParser} instead. */ @Deprecated public static Schema parse(String jsonSchema, boolean validate) { final NameValidator validator = validate ? NameValidator.UTF_VALIDATOR : NameValidator.NO_VALIDATION; return new Parser(validator).parse(jsonSchema); } static final Map<String, Type> PRIMITIVES = new HashMap<>(); static { PRIMITIVES.put("string", Type.STRING); PRIMITIVES.put("bytes", Type.BYTES); PRIMITIVES.put("int", Type.INT); PRIMITIVES.put("long", Type.LONG); PRIMITIVES.put("float", Type.FLOAT); PRIMITIVES.put("double", Type.DOUBLE); PRIMITIVES.put("boolean", Type.BOOLEAN); PRIMITIVES.put("null", Type.NULL); } static
Parser
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/join/AttributeJoinWithSingleTableInheritanceTest.java
{ "start": 9309, "end": 9833 }
class ____ { @Id private Integer id; private String name; @Column( name = "disc_col", insertable = false, updatable = false ) private String discCol; public BaseClass() { } public BaseClass(Integer id) { this.id = id; } public Integer getId() { return id; } public String getDiscCol() { return discCol; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity( name = "ChildEntityA" ) public static abstract
BaseClass
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/CombineSequenceFileInputFormat.java
{ "start": 1491, "end": 2214 }
class ____<K,V> extends CombineFileInputFormat<K,V> { @SuppressWarnings({ "rawtypes", "unchecked" }) public RecordReader<K,V> getRecordReader(InputSplit split, JobConf conf, Reporter reporter) throws IOException { return new CombineFileRecordReader(conf, (CombineFileSplit)split, reporter, SequenceFileRecordReaderWrapper.class); } /** * A record reader that may be passed to <code>CombineFileRecordReader</code> * so that it can be used in a <code>CombineFileInputFormat</code>-equivalent * for <code>SequenceFileInputFormat</code>. * * @see CombineFileRecordReader * @see CombineFileInputFormat * @see SequenceFileInputFormat */ private static
CombineSequenceFileInputFormat
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/annotation/ProfileValueUtilsTests.java
{ "start": 10899, "end": 11115 }
interface ____ { } @ProfileValueSourceConfiguration(HardCodedProfileValueSource.class) @IfProfileValue(name = NAME, value = "13") @Retention(RetentionPolicy.RUNTIME) private @
MetaEnabledWithCustomProfileValueSource
java
google__dagger
javatests/dagger/internal/codegen/InjectConstructorFactoryGeneratorTest.java
{ "start": 36671, "end": 37354 }
class ____ {", " @Inject static String s;", "}"); daggerCompiler(file) .withProcessingOptions(ImmutableMap.of("dagger.staticMemberValidation", "WARNING")) .compile( subject -> { subject.hasErrorCount(0); // TODO: Verify warning message when supported // subject.hasWarningCount(1); }); } @Test public void multipleQualifiersOnField() { Source file = CompilerTests.javaSource( "test.MultipleQualifierInjectField", "package test;", "", "import javax.inject.Inject;", "", "
StaticInjectField
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/odps/OdpsSelectTest4.java
{ "start": 737, "end": 1556 }
class ____ extends TestCase { public void test_distribute_by() throws Exception { String sql = "select total_day_cnt * EXP(-datediff(to_date('20150819', 'yyyymmdd'), last_time, 'dd') / 60) from dual"; assertEquals("SELECT total_day_cnt * EXP(-datediff(TO_DATE('20150819', 'yyyymmdd'), last_time, 'dd') / 60)\n" + "FROM dual", SQLUtils.formatOdps(sql)); } public void test_distribute_by_lcase() throws Exception { String sql = "select total_day_cnt * EXP(-datediff(to_date('20150819', 'yyyymmdd'), last_time, 'dd') / 60) from dual"; assertEquals("select total_day_cnt * EXP(-datediff(to_date('20150819', 'yyyymmdd'), last_time, 'dd') / 60)\n" + "from dual", SQLUtils.formatOdps(sql, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); } }
OdpsSelectTest4
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/internal/ForeignKeyNameSource.java
{ "start": 654, "end": 2361 }
class ____ implements ImplicitForeignKeyNameSource { private final List<Identifier> columnNames; private final ForeignKey foreignKey; private final Table table; private final MetadataBuildingContext buildingContext; private List<Identifier> referencedColumnNames; public ForeignKeyNameSource(ForeignKey foreignKey, Table table, MetadataBuildingContext buildingContext) { this.foreignKey = foreignKey; this.table = table; this.buildingContext = buildingContext; columnNames = extractColumnNames( foreignKey.getColumns() ); referencedColumnNames = null; } @Override public Identifier getTableName() { return table.getNameIdentifier(); } @Override public List<Identifier> getColumnNames() { return columnNames; } @Override public Identifier getReferencedTableName() { return foreignKey.getReferencedTable().getNameIdentifier(); } @Override public List<Identifier> getReferencedColumnNames() { if ( referencedColumnNames == null ) { referencedColumnNames = extractColumnNames( foreignKey.getReferencedColumns() ); } return referencedColumnNames; } @Override public Identifier getUserProvidedIdentifier() { String name = foreignKey.getName(); return name != null ? toIdentifier(name) : null; } @Override public MetadataBuildingContext getBuildingContext() { return buildingContext; } private List<Identifier> extractColumnNames(List<Column> columns) { if ( columns == null || columns.isEmpty() ) { return emptyList(); } final List<Identifier> columnNames = arrayList( columns.size() ); for ( Column column : columns ) { columnNames.add( column.getNameIdentifier( buildingContext ) ); } return columnNames; } }
ForeignKeyNameSource
java
spring-projects__spring-boot
module/spring-boot-restclient/src/main/java/org/springframework/boot/restclient/autoconfigure/RestClientAutoConfiguration.java
{ "start": 4519, "end": 4953 }
class ____ { @Bean @ConditionalOnBean(ClientHttpMessageConvertersCustomizer.class) @Order(Ordered.LOWEST_PRECEDENCE) HttpMessageConvertersRestClientCustomizer httpMessageConvertersRestClientCustomizer( ObjectProvider<ClientHttpMessageConvertersCustomizer> customizerProvider) { return new HttpMessageConvertersRestClientCustomizer(customizerProvider.orderedStream().toList()); } } }
HttpMessageConvertersConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatorTypeImpl.java
{ "start": 675, "end": 2009 }
class ____<O> extends ConvertedBasicTypeImpl<O> implements DiscriminatorType<O> { private final JavaType<O> domainJavaType; private final BasicType<?> underlyingJdbcMapping; public DiscriminatorTypeImpl( BasicType<?> underlyingJdbcMapping, DiscriminatorConverter<O,?> discriminatorValueConverter) { super( discriminatorValueConverter.getDiscriminatorName(), "Discriminator type " + discriminatorValueConverter.getDiscriminatorName(), underlyingJdbcMapping.getJdbcType(), discriminatorValueConverter ); assert underlyingJdbcMapping.getJdbcJavaType() == discriminatorValueConverter.getRelationalJavaType(); this.domainJavaType = discriminatorValueConverter.getDomainJavaType(); this.underlyingJdbcMapping = underlyingJdbcMapping; } @Override public BasicType<?> getUnderlyingJdbcMapping() { return underlyingJdbcMapping; } @Override @SuppressWarnings("unchecked") public DiscriminatorConverter<O,?> getValueConverter() { return (DiscriminatorConverter<O,?>) super.getValueConverter(); } @Override public Class<O> getJavaType() { return domainJavaType.getJavaTypeClass(); } @Override public boolean canDoExtraction() { return underlyingJdbcMapping.canDoExtraction(); } @Override public JavaType<O> getExpressibleJavaType() { return domainJavaType; } }
DiscriminatorTypeImpl
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/lucene/spatial/CartesianCentroidCalculatorTests.java
{ "start": 873, "end": 2152 }
class ____ extends CentroidCalculatorTests { protected Point randomPoint() { return ShapeTestUtils.randomPoint(false); } protected MultiPoint randomMultiPoint() { return ShapeTestUtils.randomMultiPoint(false); } protected Line randomLine() { return ShapeTestUtils.randomLine(false); } protected MultiLine randomMultiLine() { return ShapeTestUtils.randomMultiLine(false); } protected Polygon randomPolygon() { return ShapeTestUtils.randomPolygon(false); } protected MultiPolygon randomMultiPolygon() { return ShapeTestUtils.randomMultiPolygon(false); } protected Rectangle randomRectangle() { return ShapeTestUtils.randomRectangle(); } protected double randomY() { return ShapeTestUtils.randomValue(); } protected double randomX() { return ShapeTestUtils.randomValue(); } @Override protected boolean ignoreAreaErrors() { // Tests that calculate polygon areas with very large double values can have very large errors for flat polygons // This would not happen in the tightly bounded case of geo-data, but for cartesian test data it happens a lot. return true; } }
CartesianCentroidCalculatorTests
java
dropwizard__dropwizard
dropwizard-core/src/test/java/io/dropwizard/core/cli/ConfiguredCommandTest.java
{ "start": 612, "end": 940 }
class ____ extends ConfiguredCommand<Configuration> { protected TestCommand() { super("test", "test"); } @Override protected void run(Bootstrap<Configuration> bootstrap, Namespace namespace, Configuration configuration) throws Exception { } } private static
TestCommand
java
apache__dubbo
dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Config.java
{ "start": 905, "end": 2108 }
interface ____ { /** * Returns the default connection address in single registry center. */ default String getConnectionAddress() { return getConnectionAddress1(); } /** * Returns the first connection address in multiple registry center. */ String getConnectionAddress1(); /** * Returns the second connection address in multiple registry center. */ String getConnectionAddress2(); /** * Returns the default connection address key in single registry center. * <h3>How to use</h3> * <pre> * System.getProperty({@link #getConnectionAddressKey()}) * </pre> */ String getConnectionAddressKey(); /** * Returns the first connection address key in multiple registry center. * <h3>How to use</h3> * <pre> * System.getProperty({@link #getConnectionAddressKey1()}) * </pre> */ String getConnectionAddressKey1(); /** * Returns the second connection address key in multiple registry center. * <h3>How to use</h3> * <pre> * System.getProperty({@link #getConnectionAddressKey2()}) * </pre> */ String getConnectionAddressKey2(); }
Config
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/annotation/rsocket/RSocketSecurity.java
{ "start": 10618, "end": 11103 }
class ____ { private RSocketSecurity parent; private AnonymousAuthenticationSpec(RSocketSecurity parent) { this.parent = parent; } protected AnonymousPayloadInterceptor build() { AnonymousPayloadInterceptor result = new AnonymousPayloadInterceptor("anonymousUser"); result.setOrder(PayloadInterceptorOrder.ANONYMOUS.getOrder()); return result; } public void disable() { this.parent.anonymousAuthSpec = null; } } public final
AnonymousAuthenticationSpec
java
apache__flink
flink-table/flink-sql-gateway/src/main/java/org/apache/flink/table/gateway/rest/message/statement/ExecuteStatementResponseBody.java
{ "start": 1211, "end": 1688 }
class ____ implements ResponseBody { private static final String FIELD_OPERATION_HANDLE = "operationHandle"; @JsonProperty(FIELD_OPERATION_HANDLE) private final String operationHandle; public ExecuteStatementResponseBody( @JsonProperty(FIELD_OPERATION_HANDLE) String operationHandle) { this.operationHandle = operationHandle; } public String getOperationHandle() { return operationHandle; } }
ExecuteStatementResponseBody
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/util/ParallelSorter.java
{ "start": 8550, "end": 8785 }
class ____ implements Comparer { private final byte[] a; public ByteComparer(byte[] a) { this.a = a; } @Override public int compare(int i, int j) { return a[i] - a[j]; } } public static
ByteComparer
java
apache__dubbo
dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/FlowControlStreamObserver.java
{ "start": 907, "end": 1668 }
interface ____<T> extends StreamObserver<T> { /** * Requests the peer to produce {@code count} more messages to be delivered to the 'inbound' * {@link StreamObserver}. * * <p>This method is safe to call from multiple threads without external synchronization. * * @param count more messages */ void request(int count); boolean isAutoRequestN(); /** * Swaps to manual flow control where no message will be delivered to {@link * StreamObserver#onNext(Object)} unless it is {@link #request request()}ed. Since {@code * request()} may not be called before the call is started, a number of initial requests may be * specified. */ void disableAutoFlowControl(); }
FlowControlStreamObserver
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/IgnoredSourceFieldMapper.java
{ "start": 2514, "end": 6355 }
class ____ extends MetadataFieldMapper { private final IndexSettings indexSettings; // This factor is used to combine two offsets within the same integer: // - the offset of the end of the parent field within the field name (N / PARENT_OFFSET_IN_NAME_OFFSET) // - the offset of the field value within the encoding string containing the offset (first 4 bytes), the field name and value // (N % PARENT_OFFSET_IN_NAME_OFFSET) private static final int PARENT_OFFSET_IN_NAME_OFFSET = 1 << 16; public static final String NAME = "_ignored_source"; public static final TypeParser PARSER = new FixedTypeParser(context -> new IgnoredSourceFieldMapper(context.getIndexSettings())); static final NodeFeature DONT_EXPAND_DOTS_IN_IGNORED_SOURCE = new NodeFeature("mapper.ignored_source.dont_expand_dots"); static final NodeFeature IGNORED_SOURCE_AS_TOP_LEVEL_METADATA_ARRAY_FIELD = new NodeFeature( "mapper.ignored_source_as_top_level_metadata_array_field" ); static final NodeFeature ALWAYS_STORE_OBJECT_ARRAYS_IN_NESTED_OBJECTS = new NodeFeature( "mapper.ignored_source.always_store_object_arrays_in_nested" ); public static final FeatureFlag COALESCE_IGNORED_SOURCE_ENTRIES = new FeatureFlag("ignored_source_fields_per_entry"); /* Setting to disable encoding and writing values for this field. This is needed to unblock index functionality in case there is a bug on this code path. */ public static final Setting<Boolean> SKIP_IGNORED_SOURCE_WRITE_SETTING = Setting.boolSetting( "index.mapping.synthetic_source.skip_ignored_source_write", false, Setting.Property.Dynamic, Setting.Property.IndexScope ); /* Setting to disable reading and decoding values stored in this field. This is needed to unblock search functionality in case there is a bug on this code path. */ public static final Setting<Boolean> SKIP_IGNORED_SOURCE_READ_SETTING = Setting.boolSetting( "index.mapping.synthetic_source.skip_ignored_source_read", false, Setting.Property.Dynamic, Setting.Property.IndexScope ); /* * Container for the ignored field data: * - the full name * - the offset in the full name indicating the end of the substring matching * the full name of the parent field * - the value, encoded as a byte array */ public record NameValue(String name, int parentOffset, BytesRef value, LuceneDocument doc) { /** * Factory method, for use with fields under the parent object. It doesn't apply to objects at root level. * @param context the parser context, containing a non-null parent * @param name the fully-qualified field name, including the path from root * @param value the value to store */ public static NameValue fromContext(DocumentParserContext context, String name, BytesRef value) { int parentOffset = context.parent() instanceof RootObjectMapper ? 0 : context.parent().fullPath().length() + 1; return new NameValue(name, parentOffset, value, context.doc()); } String getParentFieldName() { // _doc corresponds to the root object return (parentOffset == 0) ? MapperService.SINGLE_MAPPING_NAME : name.substring(0, parentOffset - 1); } String getFieldName() { return parentOffset() == 0 ? name() : name().substring(parentOffset()); } NameValue cloneWithValue(BytesRef value) { assert value() == null; return new NameValue(name, parentOffset, value, doc); } boolean hasValue() { return XContentDataHelper.isDataPresent(value); } } static final
IgnoredSourceFieldMapper
java
google__dagger
hilt-android/main/java/dagger/hilt/internal/TestSingletonComponentManager.java
{ "start": 733, "end": 855 }
interface ____ extends GeneratedComponentManager<Object> { Object earlySingletonComponent(); }
TestSingletonComponentManager
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/builder/BuilderWithUnwrappedSingleArray2608Test.java
{ "start": 1503, "end": 2345 }
class ____ { String v; public POJOValueBuilder subValue(String s) { v = s; return this; } public POJOValue2608 build() { return new POJOValue2608(v); } } } // [databind#2608] @Test public void testDeserializationAndFail() throws Exception { final ObjectMapper mapper = JsonMapper.builder() .enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .build(); // Regular POJO would work: // final String serialized = "{\"value\": {\"subValue\": \"123\"}}"; final String serialized = "{\"value\": [ {\"subValue\": \"123\"} ]}"; final ExamplePOJO2608 result = mapper.readValue(serialized, ExamplePOJO2608.class); assertNotNull(result); } }
POJOValueBuilder
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/internal/BytecodeEnhancementMetadataPojoImpl.java
{ "start": 1964, "end": 11302 }
class ____ implements BytecodeEnhancementMetadata { /** * Static constructor */ public static BytecodeEnhancementMetadataPojoImpl from( PersistentClass persistentClass, Set<String> identifierAttributeNames, CompositeType nonAggregatedCidMapper, boolean collectionsInDefaultFetchGroupEnabled, Metadata metadata) { final Class<?> mappedClass = persistentClass.getMappedClass(); final boolean enhancedForLazyLoading = isPersistentAttributeInterceptableType( mappedClass ); final LazyAttributesMetadata lazyAttributesMetadata = enhancedForLazyLoading ? LazyAttributesMetadata.from( persistentClass, true, collectionsInDefaultFetchGroupEnabled, metadata ) : LazyAttributesMetadata.nonEnhanced( persistentClass.getEntityName() ); return new BytecodeEnhancementMetadataPojoImpl( persistentClass.getEntityName(), mappedClass, identifierAttributeNames, nonAggregatedCidMapper, enhancedForLazyLoading, lazyAttributesMetadata ); } private final String entityName; private final Class<?> entityClass; private final Set<String> identifierAttributeNames; private final CompositeType nonAggregatedCidMapper; private final boolean enhancedForLazyLoading; private final LazyAttributesMetadata lazyAttributesMetadata; private final LazyAttributeLoadingInterceptor.EntityRelatedState lazyAttributeLoadingInterceptorState; private volatile transient EnhancementAsProxyLazinessInterceptor.EntityRelatedState enhancementAsProxyInterceptorState; /* * Used by Hibernate Reactive */ protected BytecodeEnhancementMetadataPojoImpl( String entityName, Class<?> entityClass, Set<String> identifierAttributeNames, CompositeType nonAggregatedCidMapper, boolean enhancedForLazyLoading, LazyAttributesMetadata lazyAttributesMetadata) { this.nonAggregatedCidMapper = nonAggregatedCidMapper; assert identifierAttributeNames != null; assert !identifierAttributeNames.isEmpty(); this.entityName = entityName; this.entityClass = entityClass; this.identifierAttributeNames = identifierAttributeNames; this.enhancedForLazyLoading = enhancedForLazyLoading; this.lazyAttributesMetadata = lazyAttributesMetadata; this.lazyAttributeLoadingInterceptorState = new LazyAttributeLoadingInterceptor.EntityRelatedState( getEntityName(), lazyAttributesMetadata.getLazyAttributeNames() ); } @Override public String getEntityName() { return entityName; } @Override public boolean isEnhancedForLazyLoading() { return enhancedForLazyLoading; } @Override public LazyAttributesMetadata getLazyAttributesMetadata() { return lazyAttributesMetadata; } @Override public boolean hasUnFetchedAttributes(Object entity) { if ( ! enhancedForLazyLoading ) { return false; } final var interceptor = extractLazyInterceptor( entity ); if ( interceptor instanceof LazyAttributeLoadingInterceptor ) { return interceptor.hasAnyUninitializedAttributes(); } //noinspection RedundantIfStatement if ( interceptor instanceof EnhancementAsProxyLazinessInterceptor ) { return true; } return false; } @Override public boolean isAttributeLoaded(Object entity, String attributeName) { if ( ! enhancedForLazyLoading ) { return true; } final BytecodeLazyAttributeInterceptor interceptor = extractLazyInterceptor( entity ); if ( interceptor instanceof LazyAttributeLoadingInterceptor ) { return interceptor.isAttributeLoaded( attributeName ); } return true; } @Override public @Nullable LazyAttributeLoadingInterceptor extractInterceptor(Object entity) throws NotInstrumentedException { return (LazyAttributeLoadingInterceptor) extractLazyInterceptor( entity ); } @Override public PersistentAttributeInterceptable createEnhancedProxy(EntityKey entityKey, boolean addEmptyEntry, SharedSessionContractImplementor session) { final EntityPersister persister = entityKey.getPersister(); final Object identifier = entityKey.getIdentifier(); final PersistenceContext persistenceContext = session.getPersistenceContext(); // first, instantiate the entity instance to use as the proxy final PersistentAttributeInterceptable entity = asPersistentAttributeInterceptable( persister.instantiate( identifier, session ) ); // clear the fields that are marked as dirty in the dirtiness tracker processIfSelfDirtinessTracker( entity, BytecodeEnhancementMetadataPojoImpl::clearDirtyAttributes ); processIfManagedEntity( entity, BytecodeEnhancementMetadataPojoImpl::useTracker ); // add the entity (proxy) instance to the PC persistenceContext.addEnhancedProxy( entityKey, entity ); // if requested, add the "holder entry" to the PC if ( addEmptyEntry ) { EntityHolder entityHolder = persistenceContext.getEntityHolder( entityKey ); EntityEntry entityEntry = persistenceContext.addEntry( entity, Status.MANAGED, // loaded state null, // row-id null, identifier, // version null, LockMode.NONE, // we assume it exists in db true, persister, true ); entityHolder.setEntityEntry( entityEntry ); } // inject the interceptor persister.getBytecodeEnhancementMetadata() .injectEnhancedEntityAsProxyInterceptor( entity, entityKey, session ); return entity; } private static void clearDirtyAttributes(final SelfDirtinessTracker entity) { entity.$$_hibernate_clearDirtyAttributes(); } private static void useTracker(final ManagedEntity entity) { entity.$$_hibernate_setUseTracker( true ); } @Override public LazyAttributeLoadingInterceptor injectInterceptor( Object entity, Object identifier, SharedSessionContractImplementor session) { if ( !enhancedForLazyLoading ) { throw new NotInstrumentedException( "Entity class [" + entityClass.getName() + "] is not enhanced for lazy loading" ); } if ( !entityClass.isInstance( entity ) ) { throw new IllegalArgumentException( String.format( "Passed entity instance [%s] is not of expected type [%s]", entity, getEntityName() ) ); } final LazyAttributeLoadingInterceptor interceptor = new LazyAttributeLoadingInterceptor( this.lazyAttributeLoadingInterceptorState, identifier, session ); injectInterceptor( entity, interceptor, session ); return interceptor; } @Override public void injectEnhancedEntityAsProxyInterceptor( Object entity, EntityKey entityKey, SharedSessionContractImplementor session) { EnhancementAsProxyLazinessInterceptor.EntityRelatedState meta = getEnhancementAsProxyLazinessInterceptorMetastate( session ); injectInterceptor( entity, new EnhancementAsProxyLazinessInterceptor( meta, entityKey, session ), session ); } /* * Used by Hibernate Reactive */ //This state object needs to be lazily initialized as it needs access to the Persister, but once //initialized it can be reused across multiple sessions. public EnhancementAsProxyLazinessInterceptor.EntityRelatedState getEnhancementAsProxyLazinessInterceptorMetastate(SharedSessionContractImplementor session) { EnhancementAsProxyLazinessInterceptor.EntityRelatedState state = this.enhancementAsProxyInterceptorState; if ( state == null ) { final EntityPersister entityPersister = session.getFactory().getMappingMetamodel() .getEntityDescriptor( entityName ); state = new EnhancementAsProxyLazinessInterceptor.EntityRelatedState( entityPersister, nonAggregatedCidMapper, identifierAttributeNames ); this.enhancementAsProxyInterceptorState = state; } return state; } @Override public void injectInterceptor( Object entity, PersistentAttributeInterceptor interceptor, SharedSessionContractImplementor session) { if ( !enhancedForLazyLoading ) { throw new NotInstrumentedException( "Entity class [" + entityClass.getName() + "] is not enhanced for lazy loading" ); } if ( !entityClass.isInstance( entity ) ) { throw new IllegalArgumentException( String.format( "Passed entity instance [%s] is not of expected type [%s]", entity, getEntityName() ) ); } asPersistentAttributeInterceptable( entity ).$$_hibernate_setInterceptor( interceptor ); } @Override public @Nullable BytecodeLazyAttributeInterceptor extractLazyInterceptor(Object entity) throws NotInstrumentedException { if ( !enhancedForLazyLoading ) { throw new NotInstrumentedException( "Entity class [" + entityClass.getName() + "] is not enhanced for lazy loading" ); } if ( !entityClass.isInstance( entity ) ) { throw new IllegalArgumentException( String.format( "Passed entity instance [%s] is not of expected type [%s]", entity, getEntityName() ) ); } final PersistentAttributeInterceptor interceptor = asPersistentAttributeInterceptable( entity ).$$_hibernate_getInterceptor(); if ( interceptor == null ) { return null; } return (BytecodeLazyAttributeInterceptor) interceptor; } /* * Used by Hibernate Reactive */ public Class<?> getEntityClass() { return entityClass; } /* * Used by Hibernate Reactive */ public LazyAttributeLoadingInterceptor.EntityRelatedState getLazyAttributeLoadingInterceptorState() { return lazyAttributeLoadingInterceptorState; } }
BytecodeEnhancementMetadataPojoImpl
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/intarray/IntArrayAssert_isSortedAccordingToComparator_Test.java
{ "start": 1022, "end": 1467 }
class ____ extends IntArrayAssertBaseTest { private Comparator<Integer> comparator = alwaysEqual(); @Override protected IntArrayAssert invoke_api_method() { return assertions.isSortedAccordingTo(comparator); } @Override protected void verify_internal_effects() { verify(arrays).assertIsSortedAccordingToComparator(getInfo(assertions), getActual(assertions), comparator); } }
IntArrayAssert_isSortedAccordingToComparator_Test
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/tck/HideTckTest.java
{ "start": 772, "end": 959 }
class ____ extends BaseTck<Integer> { @Override public Publisher<Integer> createPublisher(long elements) { return Flowable.range(0, (int)elements).hide(); } }
HideTckTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/plugins/ExtensionLoader.java
{ "start": 865, "end": 989 }
class ____ ServiceLoaders * must be loaded by a module with the {@code uses} declaration. Since this * utility
because
java
google__guice
core/test/com/google/inject/ImplicitBindingTest.java
{ "start": 1701, "end": 1780 }
class ____ implements I { @Override public void go() {} } static
IImpl
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/policies/amrmproxy/LocalityMulticastAMRMProxyPolicy.java
{ "start": 27945, "end": 38075 }
class ____ { // the answer being accumulated private Map<SubClusterId, List<ResourceRequest>> answer = new TreeMap<>(); private Map<SubClusterId, Set<Long>> maskForRackDeletion = new HashMap<>(); // stores how many containers we have allocated in each RM for localized // asks, used to correctly "spread" the corresponding ANY private Map<Long, Map<SubClusterId, AtomicLong>> countContainersPerRM = new HashMap<>(); private Map<Long, AtomicLong> totNumLocalizedContainers = new HashMap<>(); // Store the randomly selected subClusterId for unresolved resource requests // keyed by requestId private Map<Long, SubClusterId> unResolvedRequestLocation = new HashMap<>(); private Set<SubClusterId> activeAndEnabledSC = new HashSet<>(); private float totHeadroomMemory = 0; private int totHeadRoomEnabledRMs = 0; private Map<SubClusterId, Float> policyWeights; private float totPolicyWeight = 0; private void reinitialize( Map<SubClusterId, SubClusterInfo> activeSubclusters, Set<SubClusterId> timedOutSubClusters, Configuration pConf) throws YarnException { if (MapUtils.isEmpty(activeSubclusters)) { throw new YarnRuntimeException("null activeSubclusters received"); } // reset data structures answer.clear(); maskForRackDeletion.clear(); countContainersPerRM.clear(); totNumLocalizedContainers.clear(); activeAndEnabledSC.clear(); totHeadroomMemory = 0; totHeadRoomEnabledRMs = 0; // save the reference locally in case the weights get reinitialized // concurrently policyWeights = weights; totPolicyWeight = 0; for (Map.Entry<SubClusterId, Float> entry : policyWeights.entrySet()) { if (entry.getValue() > 0 && activeSubclusters.containsKey(entry.getKey())) { activeAndEnabledSC.add(entry.getKey()); } } // subCluster blacklisting from configuration String blacklistedSubClusters = pConf.get(FEDERATION_BLACKLIST_SUBCLUSTERS, DEFAULT_FEDERATION_BLACKLIST_SUBCLUSTERS); if (blacklistedSubClusters != null) { Collection<String> tempList = StringUtils.getStringCollection(blacklistedSubClusters); for (String item : tempList) { activeAndEnabledSC.remove(SubClusterId.newInstance(item.trim())); } } if (activeAndEnabledSC.size() < 1) { String errorMsg = "None of the subClusters enabled in this Policy (weight > 0) are " + "currently active we cannot forward the ResourceRequest(s)"; if (failOnError) { throw new NoActiveSubclustersException(errorMsg); } else { LOG.error(errorMsg + ", continuing by enabling all active subClusters."); activeAndEnabledSC.addAll(activeSubclusters.keySet()); for (SubClusterId sc : activeSubclusters.keySet()) { policyWeights.put(sc, 1.0f); } } } Set<SubClusterId> tmpSCSet = new HashSet<>(activeAndEnabledSC); tmpSCSet.removeAll(timedOutSubClusters); if (tmpSCSet.size() < 1) { LOG.warn("All active and enabled subclusters have expired last " + "heartbeat time. Ignore the expiry check for this request."); } else { activeAndEnabledSC = tmpSCSet; } LOG.info("{} subcluster active, {} subclusters active and enabled", activeSubclusters.size(), activeAndEnabledSC.size()); // pre-compute the set of subclusters that are both active and enabled by // the policy weights, and accumulate their total weight for (SubClusterId sc : activeAndEnabledSC) { totPolicyWeight += policyWeights.get(sc); } // pre-compute headroom-based weights for active/enabled subclusters for (Map.Entry<SubClusterId, Resource> r : headroom.entrySet()) { if (activeAndEnabledSC.contains(r.getKey())) { totHeadroomMemory += r.getValue().getMemorySize(); totHeadRoomEnabledRMs++; } } } /** * Add to the answer a localized node request, and keeps track of statistics * on a per-allocation-id and per-subcluster bases. */ private void addLocalizedNodeRR(SubClusterId targetId, ResourceRequest rr) { Preconditions .checkArgument(!ResourceRequest.isAnyLocation(rr.getResourceName())); if (rr.getNumContainers() > 0) { if (!countContainersPerRM.containsKey(rr.getAllocationRequestId())) { countContainersPerRM.put(rr.getAllocationRequestId(), new HashMap<>()); } if (!countContainersPerRM.get(rr.getAllocationRequestId()) .containsKey(targetId)) { countContainersPerRM.get(rr.getAllocationRequestId()).put(targetId, new AtomicLong(0)); } countContainersPerRM.get(rr.getAllocationRequestId()).get(targetId) .addAndGet(rr.getNumContainers()); if (!totNumLocalizedContainers .containsKey(rr.getAllocationRequestId())) { totNumLocalizedContainers.put(rr.getAllocationRequestId(), new AtomicLong(0)); } totNumLocalizedContainers.get(rr.getAllocationRequestId()) .addAndGet(rr.getNumContainers()); } internalAddToAnswer(targetId, rr, false); } /** * Add a rack-local request to the final answer. */ private void addRackRR(SubClusterId targetId, ResourceRequest rr) { Preconditions .checkArgument(!ResourceRequest.isAnyLocation(rr.getResourceName())); internalAddToAnswer(targetId, rr, true); } /** * Add an ANY request to the final answer. */ private void addAnyRR(SubClusterId targetId, ResourceRequest rr) { Preconditions .checkArgument(ResourceRequest.isAnyLocation(rr.getResourceName())); internalAddToAnswer(targetId, rr, false); } private void internalAddToAnswer(SubClusterId targetId, ResourceRequest partialRR, boolean isRack) { if (!isRack) { if (!maskForRackDeletion.containsKey(targetId)) { maskForRackDeletion.put(targetId, new HashSet<Long>()); } maskForRackDeletion.get(targetId) .add(partialRR.getAllocationRequestId()); } if (!answer.containsKey(targetId)) { answer.put(targetId, new ArrayList<ResourceRequest>()); } answer.get(targetId).add(partialRR); } /** * For requests whose location cannot be resolved, choose an active and * enabled sub-cluster to forward this requestId to. */ private SubClusterId getSubClusterForUnResolvedRequest(long allocationId) { if (unResolvedRequestLocation.containsKey(allocationId)) { return unResolvedRequestLocation.get(allocationId); } int id = rand.nextInt(activeAndEnabledSC.size()); for (SubClusterId subclusterId : activeAndEnabledSC) { if (id == 0) { unResolvedRequestLocation.put(allocationId, subclusterId); return subclusterId; } id--; } throw new RuntimeException( "Should not be here. activeAndEnabledSC size = " + activeAndEnabledSC.size() + " id = " + id); } /** * Return all known subclusters associated with an allocation id. * * @param allocationId the allocation id considered * * @return the list of {@link SubClusterId}s associated with this allocation * id */ private Set<SubClusterId> getSubClustersForId(long allocationId) { if (countContainersPerRM.get(allocationId) == null) { return null; } return countContainersPerRM.get(allocationId).keySet(); } /** * Return the answer accumulated so far. * * @return the answer */ private Map<SubClusterId, List<ResourceRequest>> getAnswer() { Iterator<Entry<SubClusterId, List<ResourceRequest>>> answerIter = answer.entrySet().iterator(); // Remove redundant rack RR before returning the answer while (answerIter.hasNext()) { Entry<SubClusterId, List<ResourceRequest>> entry = answerIter.next(); SubClusterId scId = entry.getKey(); Set<Long> mask = maskForRackDeletion.get(scId); if (mask != null) { Iterator<ResourceRequest> rrIter = entry.getValue().iterator(); while (rrIter.hasNext()) { ResourceRequest rr = rrIter.next(); if (!mask.contains(rr.getAllocationRequestId())) { rrIter.remove(); } } } if (mask == null || entry.getValue().size() == 0) { answerIter.remove(); LOG.info("removing {} from output because it has only rack RR", scId); } } return answer; } /** * Return the set of sub-clusters that are both active and allowed by our * policy (weight > 0). * * @return a set of active and enabled {@link SubClusterId}s */ private Set<SubClusterId> getActiveAndEnabledSC() { return activeAndEnabledSC; } /** * Return the total number of container coming from localized requests * matching an allocation Id. */ private long getTotNumLocalizedContainers(long allocationId) { AtomicLong c = totNumLocalizedContainers.get(allocationId); return c == null ? 0 : c.get(); } /** * Returns the number of containers matching an allocation Id that are * localized in the targetId subcluster. */ private long getNumLocalizedContainers(long allocationId, SubClusterId targetId) { AtomicLong c = countContainersPerRM.get(allocationId).get(targetId); return c == null ? 0 : c.get(); } /** * Returns true is the subcluster request is both active and enabled. */ private boolean isActiveAndEnabled(SubClusterId targetId) { if (targetId == null) { return false; } else { return getActiveAndEnabledSC().contains(targetId); } } } }
AllocationBookkeeper
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/type/TypeFactory3108Test.java
{ "start": 581, "end": 654 }
class ____ extends HashMap<String, String> {} static
StringStringMap3108
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/exceptionhandling/StaleVersionedObjectMergeTest.java
{ "start": 3614, "end": 3848 }
class ____ { @Id private long id; @Version @Column(name = "ver") private Integer version; public Long getId() { return id; } public void setId(Long id) { this.id = id; } } @Entity(name = "D") public static
C
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/CollectionToArraySafeParameterTest.java
{ "start": 3412, "end": 4594 }
class ____ { private void basicCase() { Collection<String> collection = new ArrayList<String>(); Collection<Integer> collInts = new ArrayList<Integer>(); Object[] intArrayActualNoParam = collInts.toArray(); Integer[] intArrayActual = collInts.toArray(new Integer[collection.size()]); Collection<Object> collectionObjects = new ArrayList<>(); Integer[] intArrayObjects = collectionObjects.toArray(new Integer[collectionObjects.size()]); Integer[] arrayOfInts = new Integer[10]; Integer[] otherArray = collInts.toArray(arrayOfInts); Collection<Collection<Integer>> collectionOfCollection = new ArrayList<Collection<Integer>>(); Collection<Integer>[] collectionOfCollectionArray = collectionOfCollection.toArray(new ArrayList[10]); SomeObject someObject = new SomeObject(); Integer[] someObjectArray = someObject.toArray(new Integer[1]); // test to make sure that when the collection has no explicit type there is no error thrown // when "toArray" is called. Collection someObjects = new ArrayList(); Object[] intArray = someObjects.toArray(new Integer[1]); }
CollectionToArraySafeParameterNegativeCases
java
elastic__elasticsearch
distribution/tools/windows-service-cli/src/test/java/org/elasticsearch/windows/service/WindowsServiceCliTestCase.java
{ "start": 2122, "end": 2340 }
interface ____ { void validate(Map<String, String> env, ProcrunCall procrunCall); } record ProcrunCall(String exe, String command, String serviceId, Map<String, List<String>> args) {}
ProcessValidator
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/nestedresulthandler_association/Account.java
{ "start": 751, "end": 1492 }
class ____ { private String accountUuid; private String accountName; private Date birthDate; private AccountAddress address; public String getAccountUuid() { return accountUuid; } public void setAccountUuid(String accountUuid) { this.accountUuid = accountUuid; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public AccountAddress getAddress() { return address; } public void setAddress(AccountAddress address) { this.address = address; } }
Account
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/util/clusters/EmbeddedConnectCluster.java
{ "start": 8324, "end": 9358 }
class ____ extends EmbeddedConnectBuilder<EmbeddedConnectCluster, Builder> { private String name = UUID.randomUUID().toString(); private int numWorkers = DEFAULT_NUM_WORKERS; public Builder name(String name) { this.name = name; return this; } public Builder numWorkers(int numWorkers) { this.numWorkers = numWorkers; return this; } @Override protected EmbeddedConnectCluster build( int numBrokers, Properties brokerProps, boolean maskExitProcedures, Map<String, String> clientProps, Map<String, String> workerProps ) { return new EmbeddedConnectCluster( numBrokers, brokerProps, maskExitProcedures, clientProps, workerProps, name, numWorkers ); } } }
Builder
java
google__dagger
javatests/dagger/internal/codegen/DuplicateBindingsValidationTest.java
{ "start": 15400, "end": 15972 }
interface ____"); } }); } @Test public void duplicateExplicitBindings_UniqueBindingAndMultibindingDeclaration_Set() { Source component = CompilerTests.javaSource( "test.Outer", "package test;", "", "import dagger.Component;", "import dagger.Module;", "import dagger.Provides;", "import dagger.multibindings.Multibinds;", "import java.util.HashSet;", "import java.util.Set;", "", "final
TestComponent
java
apache__kafka
connect/transforms/src/main/java/org/apache/kafka/connect/transforms/ExtractField.java
{ "start": 1604, "end": 4886 }
class ____<R extends ConnectRecord<R>> implements Transformation<R>, Versioned { public static final String OVERVIEW_DOC = "Extract the specified field from a Struct when schema present, or a Map in the case of schemaless data. " + "Any null values are passed through unmodified." + "<p/>Use the concrete transformation type designed for the record key (<code>" + Key.class.getName() + "</code>) " + "or value (<code>" + Value.class.getName() + "</code>)."; private static final String FIELD_CONFIG = "field"; private static final String REPLACE_NULL_WITH_DEFAULT_CONFIG = "replace.null.with.default"; public static final ConfigDef CONFIG_DEF = FieldSyntaxVersion.appendConfigTo( new ConfigDef() .define( FIELD_CONFIG, ConfigDef.Type.STRING, ConfigDef.NO_DEFAULT_VALUE, ConfigDef.Importance.MEDIUM, "Field name to extract." ) .define(REPLACE_NULL_WITH_DEFAULT_CONFIG, ConfigDef.Type.BOOLEAN, true, ConfigDef.Importance.MEDIUM, "Whether to replace fields that have a default value and that are null to the default value. When set to true, the default value is used, otherwise null is used.")); private static final String PURPOSE = "field extraction"; private SingleFieldPath fieldPath; private String originalPath; private boolean replaceNullWithDefault; @Override public String version() { return AppInfoParser.getVersion(); } @Override public void configure(Map<String, ?> props) { final SimpleConfig config = new SimpleConfig(CONFIG_DEF, props); originalPath = config.getString(FIELD_CONFIG); fieldPath = new SingleFieldPath(originalPath, FieldSyntaxVersion.fromConfig(config)); replaceNullWithDefault = config.getBoolean(REPLACE_NULL_WITH_DEFAULT_CONFIG); } @Override public R apply(R record) { final Schema schema = operatingSchema(record); if (schema == null) { final Map<String, Object> value = requireMapOrNull(operatingValue(record), PURPOSE); return newRecord(record, null, value == null ? null : fieldPath.valueFrom(value)); } else { final Struct value = requireStructOrNull(operatingValue(record), PURPOSE); Field field = fieldPath.fieldFrom(schema); if (field == null) { throw new IllegalArgumentException("Unknown field: " + originalPath); } return newRecord(record, field.schema(), value == null ? null : fieldPath.valueFrom(value, replaceNullWithDefault)); } } @Override public void close() { } @Override public ConfigDef config() { return CONFIG_DEF; } protected abstract Schema operatingSchema(R record); protected abstract Object operatingValue(R record); protected abstract R newRecord(R record, Schema updatedSchema, Object updatedValue); public static
ExtractField
java
spring-projects__spring-boot
loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/IndexedJarStructureTests.java
{ "start": 1382, "end": 8025 }
class ____ { @Test void shouldResolveLibraryEntry() throws IOException { IndexedJarStructure structure = createStructure(); Entry entry = structure.resolve("BOOT-INF/lib/spring-webmvc-6.1.4.jar"); assertThat(entry).isNotNull(); assertThat(entry.location()).isEqualTo("spring-webmvc-6.1.4.jar"); assertThat(entry.originalLocation()).isEqualTo("BOOT-INF/lib/spring-webmvc-6.1.4.jar"); assertThat(entry.type()).isEqualTo(Type.LIBRARY); } @Test void shouldResolveApplicationEntry() throws IOException { IndexedJarStructure structure = createStructure(); Entry entry = structure.resolve("BOOT-INF/classes/application.properties"); assertThat(entry).isNotNull(); assertThat(entry.location()).isEqualTo("application.properties"); assertThat(entry.originalLocation()).isEqualTo("BOOT-INF/classes/application.properties"); assertThat(entry.type()).isEqualTo(Type.APPLICATION_CLASS_OR_RESOURCE); } @Test void shouldResolveLoaderEntry() throws IOException { IndexedJarStructure structure = createStructure(); Entry entry = structure.resolve("org/springframework/boot/loader/launch/JarLauncher"); assertThat(entry).isNotNull(); assertThat(entry.location()).isEqualTo("org/springframework/boot/loader/launch/JarLauncher"); assertThat(entry.originalLocation()).isEqualTo("org/springframework/boot/loader/launch/JarLauncher"); assertThat(entry.type()).isEqualTo(Type.LOADER); } @Test void shouldNotResolveNonExistingLibs() throws IOException { IndexedJarStructure structure = createStructure(); Entry entry = structure.resolve("BOOT-INF/lib/doesnt-exists.jar"); assertThat(entry).isNull(); } @Test void shouldCreateLauncherManifest() throws IOException { IndexedJarStructure structure = createStructure(); Manifest manifest = structure.createLauncherManifest(UnaryOperator.identity()); Map<String, String> attributes = getAttributes(manifest); assertThat(attributes).containsEntry("Manifest-Version", "1.0") .containsEntry("Implementation-Title", "IndexedJarStructureTests") .containsEntry("Spring-Boot-Version", "3.3.0-SNAPSHOT") .containsEntry("Implementation-Version", "0.0.1-SNAPSHOT") .containsEntry("Build-Jdk-Spec", "17") .containsEntry("Class-Path", "spring-webmvc-6.1.4.jar spring-web-6.1.4.jar spring-boot-autoconfigure-3.3.0-SNAPSHOT.jar spring-boot-3.3.0-SNAPSHOT.jar jakarta.annotation-api-2.1.1.jar spring-context-6.1.4.jar spring-aop-6.1.4.jar spring-beans-6.1.4.jar spring-expression-6.1.4.jar spring-core-6.1.4.jar snakeyaml-2.2.jar jackson-datatype-jdk8-2.16.1.jar jackson-datatype-jsr310-2.16.1.jar jackson-module-parameter-names-2.16.1.jar jackson-databind-2.16.1.jar tomcat-embed-websocket-10.1.19.jar tomcat-embed-core-10.1.19.jar tomcat-embed-el-10.1.19.jar micrometer-observation-1.13.0-M1.jar logback-classic-1.4.14.jar log4j-to-slf4j-2.23.0.jar jul-to-slf4j-2.0.12.jar spring-jcl-6.1.4.jar jackson-annotations-2.16.1.jar jackson-core-2.16.1.jar micrometer-commons-1.13.0-M1.jar logback-core-1.4.14.jar slf4j-api-2.0.12.jar log4j-api-2.23.0.jar") .containsEntry("Main-Class", "org.springframework.boot.jarmode.tools.IndexedJarStructureTests") .doesNotContainKeys("Start-Class", "Spring-Boot-Classes", "Spring-Boot-Lib", "Spring-Boot-Classpath-Index", "Spring-Boot-Layers-Index"); } @Test void shouldLoadFromFile(@TempDir File tempDir) throws IOException { File jarFile = new File(tempDir, "test.jar"); try (JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(jarFile), createManifest())) { outputStream.putNextEntry(new ZipEntry("BOOT-INF/classpath.idx")); outputStream.write(createIndexFile().getBytes(StandardCharsets.UTF_8)); outputStream.closeEntry(); } IndexedJarStructure structure = IndexedJarStructure.get(jarFile); assertThat(structure).isNotNull(); assertThat(structure.resolve("BOOT-INF/lib/spring-webmvc-6.1.4.jar")).extracting(Entry::type) .isEqualTo(Type.LIBRARY); assertThat(structure.resolve("BOOT-INF/classes/application.properties")).extracting(Entry::type) .isEqualTo(Type.APPLICATION_CLASS_OR_RESOURCE); } private Map<String, String> getAttributes(Manifest manifest) { Map<String, String> result = new HashMap<>(); manifest.getMainAttributes().forEach((key, value) -> result.put(key.toString(), value.toString())); return result; } private IndexedJarStructure createStructure() throws IOException { return new IndexedJarStructure(createManifest(), createIndexFile()); } private String createIndexFile() { return """ - "BOOT-INF/lib/spring-webmvc-6.1.4.jar" - "BOOT-INF/lib/spring-web-6.1.4.jar" - "BOOT-INF/lib/spring-boot-autoconfigure-3.3.0-SNAPSHOT.jar" - "BOOT-INF/lib/spring-boot-3.3.0-SNAPSHOT.jar" - "BOOT-INF/lib/jakarta.annotation-api-2.1.1.jar" - "BOOT-INF/lib/spring-context-6.1.4.jar" - "BOOT-INF/lib/spring-aop-6.1.4.jar" - "BOOT-INF/lib/spring-beans-6.1.4.jar" - "BOOT-INF/lib/spring-expression-6.1.4.jar" - "BOOT-INF/lib/spring-core-6.1.4.jar" - "BOOT-INF/lib/snakeyaml-2.2.jar" - "BOOT-INF/lib/jackson-datatype-jdk8-2.16.1.jar" - "BOOT-INF/lib/jackson-datatype-jsr310-2.16.1.jar" - "BOOT-INF/lib/jackson-module-parameter-names-2.16.1.jar" - "BOOT-INF/lib/jackson-databind-2.16.1.jar" - "BOOT-INF/lib/tomcat-embed-websocket-10.1.19.jar" - "BOOT-INF/lib/tomcat-embed-core-10.1.19.jar" - "BOOT-INF/lib/tomcat-embed-el-10.1.19.jar" - "BOOT-INF/lib/micrometer-observation-1.13.0-M1.jar" - "BOOT-INF/lib/logback-classic-1.4.14.jar" - "BOOT-INF/lib/log4j-to-slf4j-2.23.0.jar" - "BOOT-INF/lib/jul-to-slf4j-2.0.12.jar" - "BOOT-INF/lib/spring-jcl-6.1.4.jar" - "BOOT-INF/lib/jackson-annotations-2.16.1.jar" - "BOOT-INF/lib/jackson-core-2.16.1.jar" - "BOOT-INF/lib/micrometer-commons-1.13.0-M1.jar" - "BOOT-INF/lib/logback-core-1.4.14.jar" - "BOOT-INF/lib/slf4j-api-2.0.12.jar" - "BOOT-INF/lib/log4j-api-2.23.0.jar" """; } private Manifest createManifest() throws IOException { return new Manifest(new ByteArrayInputStream(""" Manifest-Version: 1.0 Main-Class: org.springframework.boot.loader.launch.JarLauncher Start-Class: org.springframework.boot.jarmode.tools.IndexedJarStructureTests Spring-Boot-Version: 3.3.0-SNAPSHOT Spring-Boot-Classes: BOOT-INF/classes/ Spring-Boot-Lib: BOOT-INF/lib/ Spring-Boot-Classpath-Index: BOOT-INF/classpath.idx Spring-Boot-Layers-Index: BOOT-INF/layers.idx Build-Jdk-Spec: 17 Implementation-Title: IndexedJarStructureTests Implementation-Version: 0.0.1-SNAPSHOT """.getBytes(StandardCharsets.UTF_8))); } }
IndexedJarStructureTests
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java
{ "start": 29602, "end": 30856 }
interface ____<E> { /** * Extract the name. * @param <N> the name type * @param element the source element * @return the extracted name */ <N> N getName(E element); /** * Extract the name. * @param <V> the value type * @param element the source element * @return the extracted value */ <V> V getValue(E element); /** * Factory method to create a {@link PairExtractor} using distinct name and value * extraction functions. * @param <T> the element type * @param nameExtractor the name extractor * @param valueExtractor the value extraction * @return a new {@link PairExtractor} instance */ static <T> PairExtractor<T> of(Function<T, ?> nameExtractor, Function<T, ?> valueExtractor) { Assert.notNull(nameExtractor, "'nameExtractor' must not be null"); Assert.notNull(valueExtractor, "'valueExtractor' must not be null"); return new PairExtractor<>() { @Override @SuppressWarnings("unchecked") public <N> N getName(T instance) { return (N) nameExtractor.apply(instance); } @Override @SuppressWarnings("unchecked") public <V> V getValue(T instance) { return (V) valueExtractor.apply(instance); } }; } } /** * Callback
PairExtractor
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/visitor/SQLServerEvalVisitor.java
{ "start": 991, "end": 3692 }
class ____ extends SQLServerASTVisitorAdapter implements SQLEvalVisitor { private Map<String, Function> functions = new HashMap<String, Function>(); private List<Object> parameters = new ArrayList<Object>(); private int variantIndex = -1; private boolean markVariantIndex = true; public SQLServerEvalVisitor() { this(new ArrayList<Object>(1)); } public SQLServerEvalVisitor(List<Object> parameters) { this.parameters = parameters; } public List<Object> getParameters() { return parameters; } public void setParameters(List<Object> parameters) { this.parameters = parameters; } public boolean visit(SQLCharExpr x) { return SQLEvalVisitorUtils.visit(this, x); } public int incrementAndGetVariantIndex() { return ++variantIndex; } public int getVariantIndex() { return variantIndex; } public boolean visit(SQLVariantRefExpr x) { return SQLEvalVisitorUtils.visit(this, x); } public boolean visit(SQLBinaryOpExpr x) { return SQLEvalVisitorUtils.visit(this, x); } public boolean visit(SQLUnaryExpr x) { return SQLEvalVisitorUtils.visit(this, x); } public boolean visit(SQLIntegerExpr x) { return SQLEvalVisitorUtils.visit(this, x); } public boolean visit(SQLNumberExpr x) { return SQLEvalVisitorUtils.visit(this, x); } @Override public boolean visit(SQLCaseExpr x) { return SQLEvalVisitorUtils.visit(this, x); } @Override public boolean visit(SQLInListExpr x) { return SQLEvalVisitorUtils.visit(this, x); } @Override public boolean visit(SQLNullExpr x) { return SQLEvalVisitorUtils.visit(this, x); } @Override public boolean visit(SQLMethodInvokeExpr x) { return SQLEvalVisitorUtils.visit(this, x); } @Override public boolean visit(SQLQueryExpr x) { return SQLEvalVisitorUtils.visit(this, x); } public boolean isMarkVariantIndex() { return markVariantIndex; } public void setMarkVariantIndex(boolean markVariantIndex) { this.markVariantIndex = markVariantIndex; } @Override public Function getFunction(String funcName) { return functions.get(funcName); } @Override public void registerFunction(String funcName, Function function) { functions.put(funcName, function); } @Override public void unregisterFunction(String funcName) { functions.remove(funcName); } public boolean visit(SQLIdentifierExpr x) { return SQLEvalVisitorUtils.visit(this, x); } }
SQLServerEvalVisitor
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/transaction/manager/LookUpTxMgrViaTransactionManagementConfigurerWithPrimaryTxMgrTests.java
{ "start": 1913, "end": 3053 }
class ____ { @Autowired CallCountingTransactionManager primary; @Autowired @Qualifier("annotationDrivenTransactionManager") CallCountingTransactionManager annotationDriven; @Test void transactionalTest() { assertThat(primary.begun).isEqualTo(0); assertThat(primary.inflight).isEqualTo(0); assertThat(primary.commits).isEqualTo(0); assertThat(primary.rollbacks).isEqualTo(0); assertThat(annotationDriven.begun).isEqualTo(1); assertThat(annotationDriven.inflight).isEqualTo(1); assertThat(annotationDriven.commits).isEqualTo(0); assertThat(annotationDriven.rollbacks).isEqualTo(0); } @AfterTransaction void afterTransaction() { assertThat(primary.begun).isEqualTo(0); assertThat(primary.inflight).isEqualTo(0); assertThat(primary.commits).isEqualTo(0); assertThat(primary.rollbacks).isEqualTo(0); assertThat(annotationDriven.begun).isEqualTo(1); assertThat(annotationDriven.inflight).isEqualTo(0); assertThat(annotationDriven.commits).isEqualTo(0); assertThat(annotationDriven.rollbacks).isEqualTo(1); } @Configuration static
LookUpTxMgrViaTransactionManagementConfigurerWithPrimaryTxMgrTests
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java
{ "start": 13730, "end": 13938 }
class ____ { private @Nullable String number; @Nullable String getNumber() { return this.number; } void setNumber(@Nullable String number) { this.number = number; } } static
ExampleMapValue
java
elastic__elasticsearch
test/framework/src/test/java/org/elasticsearch/test/test/LoggingListenerTests.java
{ "start": 12664, "end": 12854 }
class ____ to create a JUnit suite description that has the {@link TestLogging} annotation. */ @TestLogging(value = "abc:WARN,foo:WARN,foo.bar:ERROR", reason = "testing TestLogging
used
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_uin57.java
{ "start": 2437, "end": 3247 }
class ____ implements Serializable { /** * */ private static final long serialVersionUID = 8755961532274905269L; protected Box[][] boxs = null; private Block block; public GameSnapShot(){ super(); } public GameSnapShot(Box[][] boxs, Block block){ super(); this.boxs = boxs; this.block = block; } public Box[][] getBoxs() { return boxs; } public void setBoxs(Box[][] boxs) { this.boxs = boxs; } public Block getBlock() { return block; } public void setBlock(Block block) { this.block = block; } } public static
GameSnapShot
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/ReadBufferManagerV2.java
{ "start": 2175, "end": 40581 }
class ____ extends ReadBufferManager { // Internal constants private static final ReentrantLock LOCK = new ReentrantLock(); // Thread Pool Configurations private static int minThreadPoolSize; private static int maxThreadPoolSize; private static int cpuMonitoringIntervalInMilliSec; private static double cpuThreshold; private static int threadPoolUpscalePercentage; private static int threadPoolDownscalePercentage; private static int executorServiceKeepAliveTimeInMilliSec; private static final double THREAD_POOL_REQUIREMENT_BUFFER = 1.2; // 20% more threads than the queue size private static boolean isDynamicScalingEnabled; private ScheduledExecutorService cpuMonitorThread; private ThreadPoolExecutor workerPool; private final List<ReadBufferWorker> workerRefs = new ArrayList<>(); // Buffer Pool Configurations private static int minBufferPoolSize; private static int maxBufferPoolSize; private static int memoryMonitoringIntervalInMilliSec; private static double memoryThreshold; private final AtomicInteger numberOfActiveBuffers = new AtomicInteger(0); private byte[][] bufferPool; private final Stack<Integer> removedBufferList = new Stack<>(); private ScheduledExecutorService memoryMonitorThread; // Buffer Manager Structures private static ReadBufferManagerV2 bufferManager; private static AtomicBoolean isConfigured = new AtomicBoolean(false); /** * Private constructor to prevent instantiation as this needs to be singleton. */ private ReadBufferManagerV2() { printTraceLog("Creating Read Buffer Manager V2 with HADOOP-18546 patch"); } static ReadBufferManagerV2 getBufferManager() { if (!isConfigured.get()) { throw new IllegalStateException("ReadBufferManagerV2 is not configured. " + "Please call setReadBufferManagerConfigs() before calling getBufferManager()."); } if (bufferManager == null) { LOCK.lock(); try { if (bufferManager == null) { bufferManager = new ReadBufferManagerV2(); bufferManager.init(); LOGGER.trace("ReadBufferManagerV2 singleton initialized"); } } finally { LOCK.unlock(); } } return bufferManager; } /** * Set the ReadBufferManagerV2 configurations based on the provided before singleton initialization. * @param readAheadBlockSize the read-ahead block size to set for the ReadBufferManagerV2. * @param abfsConfiguration the configuration to set for the ReadBufferManagerV2. */ public static void setReadBufferManagerConfigs(final int readAheadBlockSize, final AbfsConfiguration abfsConfiguration) { // Set Configs only before initializations. if (bufferManager == null && !isConfigured.get()) { LOCK.lock(); try { if (bufferManager == null && !isConfigured.get()) { minThreadPoolSize = abfsConfiguration.getMinReadAheadV2ThreadPoolSize(); maxThreadPoolSize = abfsConfiguration.getMaxReadAheadV2ThreadPoolSize(); cpuMonitoringIntervalInMilliSec = abfsConfiguration.getReadAheadV2CpuMonitoringIntervalMillis(); cpuThreshold = abfsConfiguration.getReadAheadV2CpuUsageThresholdPercent() / HUNDRED_D; threadPoolUpscalePercentage = abfsConfiguration.getReadAheadV2ThreadPoolUpscalePercentage(); threadPoolDownscalePercentage = abfsConfiguration.getReadAheadV2ThreadPoolDownscalePercentage(); executorServiceKeepAliveTimeInMilliSec = abfsConfiguration.getReadAheadExecutorServiceTTLInMillis(); minBufferPoolSize = abfsConfiguration.getMinReadAheadV2BufferPoolSize(); maxBufferPoolSize = abfsConfiguration.getMaxReadAheadV2BufferPoolSize(); memoryMonitoringIntervalInMilliSec = abfsConfiguration.getReadAheadV2MemoryMonitoringIntervalMillis(); memoryThreshold = abfsConfiguration.getReadAheadV2MemoryUsageThresholdPercent() / HUNDRED_D; setThresholdAgeMilliseconds( abfsConfiguration.getReadAheadV2CachedBufferTTLMillis()); isDynamicScalingEnabled = abfsConfiguration.isReadAheadV2DynamicScalingEnabled(); setReadAheadBlockSize(readAheadBlockSize); setIsConfigured(true); } } finally { LOCK.unlock(); } } } /** * Initialize the singleton ReadBufferManagerV2. */ @Override void init() { // Initialize Buffer Pool. Size can never be more than max pool size bufferPool = new byte[maxBufferPoolSize][]; for (int i = 0; i < minBufferPoolSize; i++) { // Start with just minimum number of buffers. bufferPool[i] = new byte[getReadAheadBlockSize()]; // same buffers are reused. The byte array never goes back to GC getFreeList().add(i); numberOfActiveBuffers.getAndIncrement(); } memoryMonitorThread = Executors.newSingleThreadScheduledExecutor( runnable -> { Thread t = new Thread(runnable, "ReadAheadV2-Memory-Monitor"); t.setDaemon(true); return t; }); memoryMonitorThread.scheduleAtFixedRate(this::scheduledEviction, getMemoryMonitoringIntervalInMilliSec(), getMemoryMonitoringIntervalInMilliSec(), TimeUnit.MILLISECONDS); // Initialize a Fixed Size Thread Pool with minThreadPoolSize threads workerPool = new ThreadPoolExecutor( minThreadPoolSize, maxThreadPoolSize, executorServiceKeepAliveTimeInMilliSec, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), workerThreadFactory); workerPool.allowCoreThreadTimeOut(true); for (int i = 0; i < minThreadPoolSize; i++) { ReadBufferWorker worker = new ReadBufferWorker(i, getBufferManager()); workerRefs.add(worker); workerPool.submit(worker); } ReadBufferWorker.UNLEASH_WORKERS.countDown(); if (isDynamicScalingEnabled) { cpuMonitorThread = Executors.newSingleThreadScheduledExecutor( runnable -> { Thread t = new Thread(runnable, "ReadAheadV2-CPU-Monitor"); t.setDaemon(true); return t; }); cpuMonitorThread.scheduleAtFixedRate(this::adjustThreadPool, getCpuMonitoringIntervalInMilliSec(), getCpuMonitoringIntervalInMilliSec(), TimeUnit.MILLISECONDS); } printTraceLog( "ReadBufferManagerV2 initialized with {} buffers and {} worker threads", numberOfActiveBuffers.get(), workerRefs.size()); } /** * {@link AbfsInputStream} calls this method to queueing read-ahead. * @param stream which read-ahead is requested from. * @param requestedOffset The offset in the file which should be read. * @param requestedLength The length to read. */ @Override public void queueReadAhead(final AbfsInputStream stream, final long requestedOffset, final int requestedLength, TracingContext tracingContext) { printTraceLog( "Start Queueing readAhead for file: {}, with eTag: {}, " + "offset: {}, length: {}, triggered by stream: {}", stream.getPath(), stream.getETag(), requestedOffset, requestedLength, stream.hashCode()); ReadBuffer buffer; synchronized (this) { if (isAlreadyQueued(stream.getETag(), requestedOffset)) { // Already queued for this offset, so skip queuing. printTraceLog( "Skipping queuing readAhead for file: {}, with eTag: {}, " + "offset: {}, triggered by stream: {} as it is already queued", stream.getPath(), stream.getETag(), requestedOffset, stream.hashCode()); return; } if (isFreeListEmpty() && !tryMemoryUpscale() && !tryEvict()) { // No buffers are available and more buffers cannot be created. Skip queuing. printTraceLog( "Skipping queuing readAhead for file: {}, with eTag: {}, offset: {}, triggered by stream: {} as no buffers are available", stream.getPath(), stream.getETag(), requestedOffset, stream.hashCode()); return; } // Create a new ReadBuffer to keep the prefetched data and queue. buffer = new ReadBuffer(); buffer.setStream(stream); // To map buffer with stream that requested it buffer.setETag(stream.getETag()); // To map buffer with file it belongs to buffer.setPath(stream.getPath()); buffer.setOffset(requestedOffset); buffer.setLength(0); buffer.setRequestedLength(requestedLength); buffer.setStatus(ReadBufferStatus.NOT_AVAILABLE); buffer.setLatch(new CountDownLatch(1)); buffer.setTracingContext(tracingContext); if (isFreeListEmpty()) { /* * By now there should be at least one buffer available. * This is to double sure that after upscaling or eviction, * we still have free buffer available. If not, we skip queueing. */ return; } Integer bufferIndex = popFromFreeList(); if (bufferIndex > bufferPool.length) { // This should never happen. printTraceLog( "Skipping queuing readAhead for file: {}, with eTag: {}, offset: {}, triggered by stream: {} as invalid buffer index popped from free list", stream.getPath(), stream.getETag(), requestedOffset, stream.hashCode()); return; } buffer.setBuffer(bufferPool[bufferIndex]); buffer.setBufferindex(bufferIndex); getReadAheadQueue().add(buffer); notifyAll(); printTraceLog( "Done q-ing readAhead for file: {}, with eTag:{}, offset: {}, " + "buffer idx: {}, triggered by stream: {}", stream.getPath(), stream.getETag(), requestedOffset, buffer.getBufferindex(), stream.hashCode()); } } /** * {@link AbfsInputStream} calls this method read any bytes already available in a buffer (thereby saving a * remote read). This returns the bytes if the data already exists in buffer. If there is a buffer that is reading * the requested offset, then this method blocks until that read completes. If the data is queued in a read-ahead * but not picked up by a worker thread yet, then it cancels that read-ahead and reports cache miss. This is because * depending on worker thread availability, the read-ahead may take a while - the calling thread can do its own * read to get the data faster (compared to the read waiting in queue for an indeterminate amount of time). * * @param stream of the file to read bytes for * @param position the offset in the file to do a read for * @param length the length to read * @param buffer the buffer to read data into. Note that the buffer will be written into from offset 0. * @return the number of bytes read */ @Override public int getBlock(final AbfsInputStream stream, final long position, final int length, final byte[] buffer) throws IOException { // not synchronized, so have to be careful with locking printTraceLog( "getBlock request for file: {}, with eTag: {}, for position: {} " + "for length: {} received from stream: {}", stream.getPath(), stream.getETag(), position, length, stream.hashCode()); String requestedETag = stream.getETag(); boolean isFirstRead = stream.isFirstRead(); // Wait for any in-progress read to complete. waitForProcess(requestedETag, position, isFirstRead); int bytesRead = 0; synchronized (this) { bytesRead = getBlockFromCompletedQueue(requestedETag, position, length, buffer); } if (bytesRead > 0) { printTraceLog( "Done read from Cache for the file with eTag: {}, position: {}, length: {}, requested by stream: {}", requestedETag, position, bytesRead, stream.hashCode()); return bytesRead; } // otherwise, just say we got nothing - calling thread can do its own read return 0; } /** * {@link ReadBufferWorker} thread calls this to get the next buffer that it should work on. * @return {@link ReadBuffer} * @throws InterruptedException if thread is interrupted */ @Override public ReadBuffer getNextBlockToRead() throws InterruptedException { ReadBuffer buffer = null; synchronized (this) { // Blocking Call to wait for prefetch to be queued. while (getReadAheadQueue().size() == 0) { wait(); } buffer = getReadAheadQueue().remove(); notifyAll(); if (buffer == null) { return null; } buffer.setStatus(ReadBufferStatus.READING_IN_PROGRESS); getInProgressList().add(buffer); } printTraceLog( "ReadBufferWorker picked file: {}, with eTag: {}, for offset: {}, " + "queued by stream: {}", buffer.getPath(), buffer.getETag(), buffer.getOffset(), buffer.getStream().hashCode()); return buffer; } /** * {@link ReadBufferWorker} thread calls this method to post completion. * * @param buffer the buffer whose read was completed * @param result the {@link ReadBufferStatus} after the read operation in the worker thread * @param bytesActuallyRead the number of bytes that the worker thread was actually able to read */ @Override public void doneReading(final ReadBuffer buffer, final ReadBufferStatus result, final int bytesActuallyRead) { printTraceLog( "ReadBufferWorker completed prefetch for file: {} with eTag: {}, for offset: {}, queued by stream: {}, with status: {} and bytes read: {}", buffer.getPath(), buffer.getETag(), buffer.getOffset(), buffer.getStream().hashCode(), result, bytesActuallyRead); synchronized (this) { // If this buffer has already been purged during // close of InputStream then we don't update the lists. if (getInProgressList().contains(buffer)) { getInProgressList().remove(buffer); if (result == ReadBufferStatus.AVAILABLE && bytesActuallyRead > 0) { // Successful read, so update the buffer status and length buffer.setStatus(ReadBufferStatus.AVAILABLE); buffer.setLength(bytesActuallyRead); } else { // Failed read, reuse buffer for next read, this buffer will be // evicted later based on eviction policy. pushToFreeList(buffer.getBufferindex()); } // completed list also contains FAILED read buffers // for sending exception message to clients. buffer.setStatus(result); buffer.setTimeStamp(currentTimeMillis()); getCompletedReadList().add(buffer); } } //outside the synchronized, since anyone receiving a wake-up from the latch must see safe-published results buffer.getLatch().countDown(); // wake up waiting threads (if any) } /** * Purging the buffers associated with an {@link AbfsInputStream} * from {@link ReadBufferManagerV2} when stream is closed. * @param stream input stream. */ public synchronized void purgeBuffersForStream(AbfsInputStream stream) { printDebugLog("Purging stale buffers for AbfsInputStream {} ", stream); getReadAheadQueue().removeIf( readBuffer -> readBuffer.getStream() == stream); purgeList(stream, getCompletedReadList()); } /** * Check if any buffer is already queued for the requested offset. * @param eTag the eTag of the file * @param requestedOffset the requested offset * @return whether any buffer is already queued */ private boolean isAlreadyQueued(final String eTag, final long requestedOffset) { // returns true if any part of the buffer is already queued return (isInList(getReadAheadQueue(), eTag, requestedOffset) || isInList(getInProgressList(), eTag, requestedOffset) || isInList(getCompletedReadList(), eTag, requestedOffset)); } /** * Check if any buffer in the list contains the requested offset. * @param list the list to check * @param eTag the eTag of the file * @param requestedOffset the requested offset * @return whether any buffer in the list contains the requested offset */ private boolean isInList(final Collection<ReadBuffer> list, final String eTag, final long requestedOffset) { return (getFromList(list, eTag, requestedOffset) != null); } /** * Get the buffer from the list that contains the requested offset. * @param list the list to check * @param eTag the eTag of the file * @param requestedOffset the requested offset * @return the buffer if found, null otherwise */ private ReadBuffer getFromList(final Collection<ReadBuffer> list, final String eTag, final long requestedOffset) { for (ReadBuffer buffer : list) { if (eTag.equals(buffer.getETag())) { if (buffer.getStatus() == ReadBufferStatus.AVAILABLE && requestedOffset >= buffer.getOffset() && requestedOffset < buffer.getOffset() + buffer.getLength()) { return buffer; } else if (requestedOffset >= buffer.getOffset() && requestedOffset < buffer.getOffset() + buffer.getRequestedLength()) { return buffer; } } } return null; } /** * If any buffer in the completed list can be reclaimed then reclaim it and return the buffer to free list. * The objective is to find just one buffer - there is no advantage to evicting more than one. * @return whether the eviction succeeded - i.e., were we able to free up one buffer */ private synchronized boolean tryEvict() { ReadBuffer nodeToEvict = null; if (getCompletedReadList().size() <= 0) { return false; // there are no evict-able buffers } long currentTimeInMs = currentTimeMillis(); // first, try buffers where all bytes have been consumed (approximated as first and last bytes consumed) for (ReadBuffer buf : getCompletedReadList()) { if (buf.isFullyConsumed()) { nodeToEvict = buf; break; } } if (nodeToEvict != null) { return manualEviction(nodeToEvict); } // next, try buffers where any bytes have been consumed (maybe a bad idea? have to experiment and see) for (ReadBuffer buf : getCompletedReadList()) { if (buf.isAnyByteConsumed()) { nodeToEvict = buf; break; } } if (nodeToEvict != null) { return manualEviction(nodeToEvict); } // next, try any old nodes that have not been consumed // Failed read buffers (with buffer index=-1) that are older than // thresholdAge should be cleaned up, but at the same time should not // report successful eviction. // Queue logic expects that a buffer is freed up for read ahead when // eviction is successful, whereas a failed ReadBuffer would have released // its buffer when its status was set to READ_FAILED. long earliestBirthday = Long.MAX_VALUE; ArrayList<ReadBuffer> oldFailedBuffers = new ArrayList<>(); for (ReadBuffer buf : getCompletedReadList()) { if ((buf.getBufferindex() != -1) && (buf.getTimeStamp() < earliestBirthday)) { nodeToEvict = buf; earliestBirthday = buf.getTimeStamp(); } else if ((buf.getBufferindex() == -1) && (currentTimeInMs - buf.getTimeStamp()) > getThresholdAgeMilliseconds()) { oldFailedBuffers.add(buf); } } for (ReadBuffer buf : oldFailedBuffers) { manualEviction(buf); } if ((currentTimeInMs - earliestBirthday > getThresholdAgeMilliseconds()) && (nodeToEvict != null)) { return manualEviction(nodeToEvict); } printTraceLog("No buffer eligible for eviction"); // nothing can be evicted return false; } /** * Evict the given buffer. * @param buf the buffer to evict * @return whether the eviction succeeded */ private boolean evict(final ReadBuffer buf) { if (buf.getRefCount() > 0) { // If the buffer is still being read, then we cannot evict it. printTraceLog( "Cannot evict buffer with index: {}, file: {}, with eTag: {}, offset: {} as it is still being read by some input stream", buf.getBufferindex(), buf.getPath(), buf.getETag(), buf.getOffset()); return false; } // As failed ReadBuffers (bufferIndx = -1) are saved in getCompletedReadList(), // avoid adding it to availableBufferList. if (buf.getBufferindex() != -1) { pushToFreeList(buf.getBufferindex()); } getCompletedReadList().remove(buf); buf.setTracingContext(null); printTraceLog( "Eviction of Buffer Completed for BufferIndex: {}, file: {}, with eTag: {}, offset: {}, is fully consumed: {}, is partially consumed: {}", buf.getBufferindex(), buf.getPath(), buf.getETag(), buf.getOffset(), buf.isFullyConsumed(), buf.isAnyByteConsumed()); return true; } /** * Wait for any in-progress read for the requested offset to complete. * @param eTag the eTag of the file * @param position the requested offset * @param isFirstRead whether this is the first read of the stream */ private void waitForProcess(final String eTag, final long position, boolean isFirstRead) { ReadBuffer readBuf; synchronized (this) { readBuf = clearFromReadAheadQueue(eTag, position, isFirstRead); if (readBuf == null) { readBuf = getFromList(getInProgressList(), eTag, position); } } if (readBuf != null) { // if in in-progress queue, then block for it try { printTraceLog( "A relevant read buffer for file: {}, with eTag: {}, offset: {}, " + "queued by stream: {}, having buffer idx: {} is being prefetched, waiting for latch", readBuf.getPath(), readBuf.getETag(), readBuf.getOffset(), readBuf.getStream().hashCode(), readBuf.getBufferindex()); readBuf.getLatch() .await(); // blocking wait on the caller stream's thread // Note on correctness: readBuf gets out of getInProgressList() only in 1 place: after worker thread // is done processing it (in doneReading). There, the latch is set after removing the buffer from // getInProgressList(). So this latch is safe to be outside the synchronized block. // Putting it in synchronized would result in a deadlock, since this thread would be holding the lock // while waiting, so no one will be able to change any state. If this becomes more complex in the future, // then the latch can be removed and replaced with wait/notify whenever getInProgressList() is touched. } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } printTraceLog("Latch done for file: {}, with eTag: {}, for offset: {}, " + "buffer index: {} queued by stream: {}", readBuf.getPath(), readBuf.getETag(), readBuf.getOffset(), readBuf.getBufferindex(), readBuf.getStream().hashCode()); } } /** * Clear the buffer from read-ahead queue if it exists. * @param eTag the eTag of the file * @param requestedOffset the requested offset * @param isFirstRead whether this is the first read of the stream * @return the buffer if found, null otherwise */ private ReadBuffer clearFromReadAheadQueue(final String eTag, final long requestedOffset, boolean isFirstRead) { ReadBuffer buffer = getFromList(getReadAheadQueue(), eTag, requestedOffset); /* * If this prefetch was triggered by first read of this input stream, * we should not remove it from queue and let it complete by backend threads. */ if (buffer != null && isFirstRead) { return buffer; } if (buffer != null) { getReadAheadQueue().remove(buffer); notifyAll(); // lock is held in calling method pushToFreeList(buffer.getBufferindex()); } return null; } /** * Get the block from completed queue if it exists. * @param eTag the eTag of the file * @param position the requested offset * @param length the length to read * @param buffer the buffer to read data into * @return the number of bytes read * @throws IOException if an I/O error occurs */ private int getBlockFromCompletedQueue(final String eTag, final long position, final int length, final byte[] buffer) throws IOException { ReadBuffer buf = getBufferFromCompletedQueue(eTag, position); if (buf == null) { return 0; } buf.startReading(); // atomic increment of refCount. if (buf.getStatus() == ReadBufferStatus.READ_FAILED) { // To prevent new read requests to fail due to old read-ahead attempts, // return exception only from buffers that failed within last getThresholdAgeMilliseconds() if ((currentTimeMillis() - (buf.getTimeStamp()) < getThresholdAgeMilliseconds())) { throw buf.getErrException(); } else { return 0; } } if ((buf.getStatus() != ReadBufferStatus.AVAILABLE) || (position >= buf.getOffset() + buf.getLength())) { return 0; } int cursor = (int) (position - buf.getOffset()); int availableLengthInBuffer = buf.getLength() - cursor; int lengthToCopy = Math.min(length, availableLengthInBuffer); System.arraycopy(buf.getBuffer(), cursor, buffer, 0, lengthToCopy); if (cursor == 0) { buf.setFirstByteConsumed(true); } if (cursor + lengthToCopy == buf.getLength()) { buf.setLastByteConsumed(true); } buf.setAnyByteConsumed(true); buf.endReading(); // atomic decrement of refCount return lengthToCopy; } /** * Get the buffer from completed queue that contains the requested offset. * @param eTag the eTag of the file * @param requestedOffset the requested offset * @return the buffer if found, null otherwise */ private ReadBuffer getBufferFromCompletedQueue(final String eTag, final long requestedOffset) { for (ReadBuffer buffer : getCompletedReadList()) { // Buffer is returned if the requestedOffset is at or above buffer's // offset but less than buffer's length or the actual requestedLength if (eTag.equals(buffer.getETag()) && (requestedOffset >= buffer.getOffset()) && ((requestedOffset < buffer.getOffset() + buffer.getLength()) || (requestedOffset < buffer.getOffset() + buffer.getRequestedLength()))) { return buffer; } } return null; } /** * Try to upscale memory by adding more buffers to the pool if memory usage is below threshold. * @return whether the upscale succeeded */ private synchronized boolean tryMemoryUpscale() { if (!isDynamicScalingEnabled) { printTraceLog("Dynamic scaling is disabled, skipping memory upscale"); return false; // Dynamic scaling is disabled, so no upscaling. } double memoryLoad = getMemoryLoad(); if (memoryLoad < memoryThreshold && getNumBuffers() < maxBufferPoolSize) { // Create and Add more buffers in getFreeList(). int nextIndx = getNumBuffers(); if (removedBufferList.isEmpty() && nextIndx < bufferPool.length) { bufferPool[nextIndx] = new byte[getReadAheadBlockSize()]; pushToFreeList(nextIndx); } else { // Reuse a removed buffer index. int freeIndex = removedBufferList.pop(); if (freeIndex >= bufferPool.length || bufferPool[freeIndex] != null) { printTraceLog("Invalid free index: {}. Current buffer pool size: {}", freeIndex, bufferPool.length); return false; } bufferPool[freeIndex] = new byte[getReadAheadBlockSize()]; pushToFreeList(freeIndex); } incrementActiveBufferCount(); printTraceLog( "Current Memory Load: {}. Incrementing buffer pool size to {}", memoryLoad, getNumBuffers()); return true; } printTraceLog("Could not Upscale memory. Total buffers: {} Memory Load: {}", getNumBuffers(), memoryLoad); return false; } /** * Scheduled Eviction task that runs periodically to evict old buffers. */ private void scheduledEviction() { for (ReadBuffer buf : getCompletedReadList()) { if (currentTimeMillis() - buf.getTimeStamp() > getThresholdAgeMilliseconds()) { // If the buffer is older than thresholdAge, evict it. printTraceLog( "Scheduled Eviction of Buffer Triggered for BufferIndex: {}, " + "file: {}, with eTag: {}, offset: {}, length: {}, queued by stream: {}", buf.getBufferindex(), buf.getPath(), buf.getETag(), buf.getOffset(), buf.getLength(), buf.getStream().hashCode()); evict(buf); } } double memoryLoad = getMemoryLoad(); if (isDynamicScalingEnabled && memoryLoad > memoryThreshold) { synchronized (this) { if (isFreeListEmpty()) { printTraceLog( "No free buffers available. Skipping downscale of buffer pool"); return; // No free buffers available, so cannot downscale. } int freeIndex = popFromFreeList(); if (freeIndex > bufferPool.length || bufferPool[freeIndex] == null) { printTraceLog("Invalid free index: {}. Current buffer pool size: {}", freeIndex, bufferPool.length); return; } bufferPool[freeIndex] = null; removedBufferList.add(freeIndex); decrementActiveBufferCount(); printTraceLog( "Current Memory Load: {}. Decrementing buffer pool size to {}", memoryLoad, getNumBuffers()); } } } /** * Manual Eviction of a buffer. * @param buf the buffer to evict * @return whether the eviction succeeded */ private boolean manualEviction(final ReadBuffer buf) { printTraceLog( "Manual Eviction of Buffer Triggered for BufferIndex: {}, file: {}, with eTag: {}, offset: {}, queued by stream: {}", buf.getBufferindex(), buf.getPath(), buf.getETag(), buf.getOffset(), buf.getStream().hashCode()); return evict(buf); } /** * Adjust the thread pool size based on CPU load and queue size. */ private void adjustThreadPool() { int currentPoolSize = workerRefs.size(); double cpuLoad = getCpuLoad(); int requiredPoolSize = getRequiredThreadPoolSize(); int newThreadPoolSize; printTraceLog( "Current CPU load: {}, Current worker pool size: {}, Current queue size: {}", cpuLoad, currentPoolSize, requiredPoolSize); if (currentPoolSize < requiredPoolSize && cpuLoad < cpuThreshold) { // Submit more background tasks. newThreadPoolSize = Math.min(maxThreadPoolSize, (int) Math.ceil( (currentPoolSize * (HUNDRED_D + threadPoolUpscalePercentage)) / HUNDRED_D)); // Create new Worker Threads for (int i = currentPoolSize; i < newThreadPoolSize; i++) { ReadBufferWorker worker = new ReadBufferWorker(i, getBufferManager()); workerRefs.add(worker); workerPool.submit(worker); } printTraceLog("Increased worker pool size from {} to {}", currentPoolSize, newThreadPoolSize); } else if (cpuLoad > cpuThreshold || currentPoolSize > requiredPoolSize) { newThreadPoolSize = Math.max(minThreadPoolSize, (int) Math.ceil( (currentPoolSize * (HUNDRED_D - threadPoolDownscalePercentage)) / HUNDRED_D)); // Signal the extra workers to stop while (workerRefs.size() > newThreadPoolSize) { ReadBufferWorker worker = workerRefs.remove(workerRefs.size() - 1); worker.stop(); } printTraceLog("Decreased worker pool size from {} to {}", currentPoolSize, newThreadPoolSize); } else { printTraceLog("No change in worker pool size. CPU load: {} Pool size: {}", cpuLoad, currentPoolSize); } } /** * Similar to System.currentTimeMillis, except implemented with System.nanoTime(). * System.currentTimeMillis can go backwards when system clock is changed (e.g., with NTP time synchronization), * making it unsuitable for measuring time intervals. nanotime is strictly monotonically increasing per CPU core. * Note: it is not monotonic across Sockets, and even within a CPU, its only the * more recent parts which share a clock across all cores. * * @return current time in milliseconds */ private long currentTimeMillis() { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); } /** * Purge all buffers associated with the given stream from the given list. * @param stream the stream whose buffers are to be purged * @param list the list to purge from */ private void purgeList(AbfsInputStream stream, LinkedList<ReadBuffer> list) { for (Iterator<ReadBuffer> it = list.iterator(); it.hasNext();) { ReadBuffer readBuffer = it.next(); if (readBuffer.getStream() == stream) { it.remove(); // As failed ReadBuffers (bufferIndex = -1) are already pushed to free // list in doneReading method, we will skip adding those here again. if (readBuffer.getBufferindex() != -1) { pushToFreeList(readBuffer.getBufferindex()); } } } } /** * Test method that can clean up the current state of readAhead buffers and * the lists. Will also trigger a fresh init. */ @VisibleForTesting @Override public void testResetReadBufferManager() { synchronized (this) { ArrayList<ReadBuffer> completedBuffers = new ArrayList<>(); for (ReadBuffer buf : getCompletedReadList()) { if (buf != null) { completedBuffers.add(buf); } } for (ReadBuffer buf : completedBuffers) { manualEviction(buf); } getReadAheadQueue().clear(); getInProgressList().clear(); getCompletedReadList().clear(); getFreeList().clear(); for (int i = 0; i < maxBufferPoolSize; i++) { bufferPool[i] = null; } bufferPool = null; if (cpuMonitorThread != null) { cpuMonitorThread.shutdownNow(); } if (memoryMonitorThread != null) { memoryMonitorThread.shutdownNow(); } if (workerPool != null) { workerPool.shutdownNow(); } resetBufferManager(); } } @VisibleForTesting @Override public void testResetReadBufferManager(int readAheadBlockSize, int thresholdAgeMilliseconds) { setReadAheadBlockSize(readAheadBlockSize); setThresholdAgeMilliseconds(thresholdAgeMilliseconds); testResetReadBufferManager(); } @VisibleForTesting public void callTryEvict() { tryEvict(); } @VisibleForTesting public int getNumBuffers() { return numberOfActiveBuffers.get(); } @Override void resetBufferManager() { setBufferManager(null); // reset the singleton instance setIsConfigured(false); } private static void setBufferManager(ReadBufferManagerV2 manager) { bufferManager = manager; } private static void setIsConfigured(boolean configured) { isConfigured.set(configured); } private final ThreadFactory workerThreadFactory = new ThreadFactory() { private int count = 0; @Override public Thread newThread(Runnable r) { Thread t = new SubjectInheritingThread(r, "ReadAheadV2-WorkerThread-" + count++); t.setDaemon(true); return t; } }; private void printTraceLog(String message, Object... args) { if (LOGGER.isTraceEnabled()) { LOGGER.trace(message, args); } } private void printDebugLog(String message, Object... args) { LOGGER.debug(message, args); } /** * Get the current memory load of the JVM. * @return the memory load as a double value between 0.0 and 1.0 */ @VisibleForTesting double getMemoryLoad() { MemoryMXBean osBean = ManagementFactory.getMemoryMXBean(); MemoryUsage memoryUsage = osBean.getHeapMemoryUsage(); return (double) memoryUsage.getUsed() / memoryUsage.getMax(); } /** * Get the current CPU load of the system. * @return the CPU load as a double value between 0.0 and 1.0 */ @VisibleForTesting public double getCpuLoad() { OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean( OperatingSystemMXBean.class); double cpuLoad = osBean.getSystemCpuLoad(); if (cpuLoad < 0) { // If the CPU load is not available, return 0.0 return 0.0; } return cpuLoad; } @VisibleForTesting synchronized static ReadBufferManagerV2 getInstance() { return bufferManager; } @VisibleForTesting public int getMinBufferPoolSize() { return minBufferPoolSize; } @VisibleForTesting public int getMaxBufferPoolSize() { return maxBufferPoolSize; } @VisibleForTesting public int getCurrentThreadPoolSize() { return workerRefs.size(); } @VisibleForTesting public int getCpuMonitoringIntervalInMilliSec() { return cpuMonitoringIntervalInMilliSec; } @VisibleForTesting public int getMemoryMonitoringIntervalInMilliSec() { return memoryMonitoringIntervalInMilliSec; } @VisibleForTesting public ScheduledExecutorService getCpuMonitoringThread() { return cpuMonitorThread; } public int getRequiredThreadPoolSize() { return (int) Math.ceil(THREAD_POOL_REQUIREMENT_BUFFER * (getReadAheadQueue().size() + getInProgressList().size())); // 20% more for buffer } private boolean isFreeListEmpty() { LOCK.lock(); try { return getFreeList().isEmpty(); } finally { LOCK.unlock(); } } private Integer popFromFreeList() { LOCK.lock(); try { return getFreeList().pop(); } finally { LOCK.unlock(); } } private void pushToFreeList(int idx) { LOCK.lock(); try { getFreeList().push(idx); } finally { LOCK.unlock(); } } private void incrementActiveBufferCount() { numberOfActiveBuffers.getAndIncrement(); } private void decrementActiveBufferCount() { numberOfActiveBuffers.getAndDecrement(); } }
ReadBufferManagerV2
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java
{ "start": 48861, "end": 49658 }
class ____ implements CallableProcessingInterceptor { @Override public <T> void preProcess(NativeWebRequest webRequest, Callable<T> task) { HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); if (request != null) { HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class); initContextHolders(request, buildLocaleContext(request), buildRequestAttributes(request, response, null)); } } @Override public <T> void postProcess(NativeWebRequest webRequest, Callable<T> task, @Nullable Object concurrentResult) { HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); if (request != null) { resetContextHolders(request, null, null); } } } }
RequestBindingInterceptor
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/CopyCommands.java
{ "start": 7976, "end": 9688 }
class ____ extends CopyCommandWithMultiThread { public static final String NAME = "get"; public static final String USAGE = "[-f] [-p] [-crc] [-ignoreCrc] [-t <thread count>]" + " [-q <thread pool queue size>] <src> ... <localdst>"; public static final String DESCRIPTION = "Copy files that match the file pattern <src> to the local name. " + "<src> is kept.\nWhen copying multiple files, the destination" + " must be a directory.\nFlags:\n" + " -p : Preserves timestamps, ownership and the mode.\n" + " -f : Overwrites the destination if it already exists.\n" + " -crc : write CRC checksums for the files downloaded.\n" + " -ignoreCrc : Skip CRC checks on the file(s) downloaded.\n" + " -t <thread count> : Number of threads to be used," + " default is 1.\n" + " -q <thread pool queue size> : Thread pool queue size to be" + " used, default is 1024.\n"; @Override protected void processOptions(LinkedList<String> args) throws IOException { CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE, "crc", "ignoreCrc", "p", "f"); cf.addOptionWithValue("t"); cf.addOptionWithValue("q"); cf.parse(args); setWriteChecksum(cf.getOpt("crc")); setVerifyChecksum(!cf.getOpt("ignoreCrc")); setPreserve(cf.getOpt("p")); setOverwrite(cf.getOpt("f")); setThreadCount(cf.getOptValue("t")); setThreadPoolQueueSize(cf.getOptValue("q")); setRecursive(true); getLocalDestination(args); } } /** * Copy local files to a remote filesystem */ public static
Get
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/eventtime/WatermarkOutputMultiplexerTest.java
{ "start": 1031, "end": 19731 }
class ____ { @Test void singleImmediateWatermark() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput = createImmediateOutput(multiplexer); watermarkOutput.emitWatermark(new Watermark(0)); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(0)); assertThat(underlyingWatermarkOutput.isIdle()).isFalse(); } @Test void singleImmediateIdleness() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput = createImmediateOutput(multiplexer); watermarkOutput.markIdle(); assertThat(underlyingWatermarkOutput.lastWatermark()).isNull(); assertThat(underlyingWatermarkOutput.isIdle()).isTrue(); } @Test void singleImmediateWatermarkAfterIdleness() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput = createImmediateOutput(multiplexer); watermarkOutput.markIdle(); assertThat(underlyingWatermarkOutput.isIdle()).isTrue(); watermarkOutput.emitWatermark(new Watermark(0)); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(0)); assertThat(underlyingWatermarkOutput.isIdle()).isFalse(); } @Test void multipleImmediateWatermark() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput1 = createImmediateOutput(multiplexer); WatermarkOutput watermarkOutput2 = createImmediateOutput(multiplexer); WatermarkOutput watermarkOutput3 = createImmediateOutput(multiplexer); watermarkOutput1.emitWatermark(new Watermark(2)); watermarkOutput2.emitWatermark(new Watermark(5)); watermarkOutput3.markIdle(); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(2)); assertThat(underlyingWatermarkOutput.isIdle()).isFalse(); } @Test void whenImmediateOutputBecomesIdleWatermarkAdvances() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput1 = createImmediateOutput(multiplexer); WatermarkOutput watermarkOutput2 = createImmediateOutput(multiplexer); watermarkOutput1.emitWatermark(new Watermark(2)); watermarkOutput2.emitWatermark(new Watermark(5)); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(2)); watermarkOutput1.markIdle(); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(5)); } @Test void whenAllImmediateOutputsBecomeIdleWatermarkAdvances() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput1 = createImmediateOutput(multiplexer); WatermarkOutput watermarkOutput2 = createImmediateOutput(multiplexer); watermarkOutput1.emitWatermark(new Watermark(5)); watermarkOutput2.emitWatermark(new Watermark(2)); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(2)); assertThat(underlyingWatermarkOutput.isIdle()).isFalse(); // No race condition between watermarkOutput1 and watermarkOutput2. // Even if watermarkOutput1 becomes idle first, the final result is 5. watermarkOutput1.markIdle(); watermarkOutput2.markIdle(); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(5)); assertThat(underlyingWatermarkOutput.isIdle()).isTrue(); } @Test void whenAllDeferredOutputsEmitAndIdleWatermarkAdvances() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput1 = createDeferredOutput(multiplexer); WatermarkOutput watermarkOutput2 = createDeferredOutput(multiplexer); // Both emitting a watermark and becoming idle happen in the same invocation watermarkOutput1.emitWatermark(new Watermark(5)); watermarkOutput1.markIdle(); // Both emitting a watermark and becoming idle happen in the same invocation watermarkOutput2.emitWatermark(new Watermark(2)); watermarkOutput2.markIdle(); assertThat(underlyingWatermarkOutput.lastWatermark()).isNull(); assertThat(underlyingWatermarkOutput.isIdle()).isFalse(); multiplexer.onPeriodicEmit(); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(5)); assertThat(underlyingWatermarkOutput.isIdle()).isTrue(); } @Test void combinedWatermarkDoesNotRegressWhenIdleOutputRegresses() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput1 = createImmediateOutput(multiplexer); WatermarkOutput watermarkOutput2 = createImmediateOutput(multiplexer); watermarkOutput1.emitWatermark(new Watermark(2)); watermarkOutput2.emitWatermark(new Watermark(5)); watermarkOutput1.markIdle(); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(5)); watermarkOutput1.emitWatermark(new Watermark(3)); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(5)); } /** * This test makes sure that we don't output any update if there are zero outputs. Due to how * aggregation of deferred updates in the KafkaConsumer works we had a bug there that caused a * Long.MAX_VALUE watermark to be emitted in case of zero partitions. * * <p>Additionally it verifies that the combined output is not IDLE during the initial phase * when there are no splits assigned and the combined watermark is at its initial value. */ @Test void noCombinedDeferredUpdateWhenWeHaveZeroOutputs() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); multiplexer.onPeriodicEmit(); assertThat(underlyingWatermarkOutput.lastWatermark()).isNull(); assertThat(underlyingWatermarkOutput.isIdle()).isFalse(); } @Test void deferredOutputDoesNotImmediatelyAdvanceWatermark() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput1 = createDeferredOutput(multiplexer); WatermarkOutput watermarkOutput2 = createDeferredOutput(multiplexer); watermarkOutput1.emitWatermark(new Watermark(0)); watermarkOutput2.emitWatermark(new Watermark(1)); assertThat(underlyingWatermarkOutput.lastWatermark()).isNull(); multiplexer.onPeriodicEmit(); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(0)); } @Test void singleDeferredWatermark() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput = createDeferredOutput(multiplexer); watermarkOutput.emitWatermark(new Watermark(0)); multiplexer.onPeriodicEmit(); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(0)); assertThat(underlyingWatermarkOutput.isIdle()).isFalse(); } @Test void singleDeferredIdleness() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput = createDeferredOutput(multiplexer); watermarkOutput.markIdle(); multiplexer.onPeriodicEmit(); assertThat(underlyingWatermarkOutput.lastWatermark()).isNull(); assertThat(underlyingWatermarkOutput.isIdle()).isTrue(); } @Test void singleDeferredWatermarkAfterIdleness() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput = createDeferredOutput(multiplexer); watermarkOutput.markIdle(); multiplexer.onPeriodicEmit(); assertThat(underlyingWatermarkOutput.isIdle()).isTrue(); watermarkOutput.emitWatermark(new Watermark(0)); multiplexer.onPeriodicEmit(); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(0)); assertThat(underlyingWatermarkOutput.isIdle()).isFalse(); } @Test void multipleDeferredWatermark() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput watermarkOutput1 = createDeferredOutput(multiplexer); WatermarkOutput watermarkOutput2 = createDeferredOutput(multiplexer); WatermarkOutput watermarkOutput3 = createDeferredOutput(multiplexer); watermarkOutput1.emitWatermark(new Watermark(2)); watermarkOutput2.emitWatermark(new Watermark(5)); watermarkOutput3.markIdle(); multiplexer.onPeriodicEmit(); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(2)); assertThat(underlyingWatermarkOutput.isIdle()).isFalse(); } @Test void immediateUpdatesTakeDeferredUpdatesIntoAccount() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); WatermarkOutput immediateOutput = createImmediateOutput(multiplexer); WatermarkOutput deferredOutput = createDeferredOutput(multiplexer); deferredOutput.emitWatermark(new Watermark(5)); assertThat(underlyingWatermarkOutput.lastWatermark()).isNull(); immediateOutput.emitWatermark(new Watermark(2)); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(2)); } @Test void immediateUpdateOnSameOutputAsDeferredUpdateDoesNotRegress() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); final String id = "test-id"; multiplexer.registerNewOutput(id); WatermarkOutput immediateOutput = multiplexer.getImmediateOutput(id); WatermarkOutput deferredOutput = multiplexer.getDeferredOutput(id); deferredOutput.emitWatermark(new Watermark(5)); multiplexer.onPeriodicEmit(); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(5)); immediateOutput.emitWatermark(new Watermark(2)); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(5)); multiplexer.onPeriodicEmit(); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(new Watermark(5)); } @Test void lowerImmediateUpdateOnSameOutputDoesNotEmitCombinedUpdate() { TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); final String id = "1234-test"; multiplexer.registerNewOutput(id); WatermarkOutput immediateOutput = multiplexer.getImmediateOutput(id); WatermarkOutput deferredOutput = multiplexer.getDeferredOutput(id); deferredOutput.emitWatermark(new Watermark(5)); immediateOutput.emitWatermark(new Watermark(2)); assertThat(underlyingWatermarkOutput.lastWatermark()).isNull(); } @Test void testRemoveUnblocksWatermarks() { final TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); final WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); final long lowTimestamp = 156765L; final long highTimestamp = lowTimestamp + 10; multiplexer.registerNewOutput("lower"); multiplexer.registerNewOutput("higher"); multiplexer.getImmediateOutput("lower").emitWatermark(new Watermark(lowTimestamp)); multiplexer.unregisterOutput("lower"); multiplexer.getImmediateOutput("higher").emitWatermark(new Watermark(highTimestamp)); assertThat(underlyingWatermarkOutput.lastWatermark().getTimestamp()) .isEqualTo(highTimestamp); } @Test void testRemoveOfLowestDoesNotImmediatelyAdvanceWatermark() { final TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); final WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); final long lowTimestamp = -4343L; final long highTimestamp = lowTimestamp + 10; multiplexer.registerNewOutput("lower"); multiplexer.registerNewOutput("higher"); multiplexer.getImmediateOutput("lower").emitWatermark(new Watermark(lowTimestamp)); multiplexer.getImmediateOutput("higher").emitWatermark(new Watermark(highTimestamp)); multiplexer.unregisterOutput("lower"); assertThat(underlyingWatermarkOutput.lastWatermark().getTimestamp()) .isEqualTo(lowTimestamp); } @Test void testRemoveOfHighestDoesNotRetractWatermark() { final TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); final WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); final long lowTimestamp = 1L; final long highTimestamp = 2L; multiplexer.registerNewOutput("higher"); multiplexer.getImmediateOutput("higher").emitWatermark(new Watermark(highTimestamp)); multiplexer.unregisterOutput("higher"); multiplexer.registerNewOutput("lower"); multiplexer.getImmediateOutput("lower").emitWatermark(new Watermark(lowTimestamp)); assertThat(underlyingWatermarkOutput.lastWatermark().getTimestamp()) .isEqualTo(highTimestamp); } @Test void testRemoveRegisteredReturnValue() { final TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); final WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); multiplexer.registerNewOutput("does-exist"); final boolean unregistered = multiplexer.unregisterOutput("does-exist"); assertThat(unregistered).isTrue(); } @Test void testRemoveNotRegisteredReturnValue() { final TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); final WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); final boolean unregistered = multiplexer.unregisterOutput("does-not-exist"); assertThat(unregistered).isFalse(); } @Test void testNotEmittingIdleAfterAllSplitsRemoved() { final TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput(); final WatermarkOutputMultiplexer multiplexer = new WatermarkOutputMultiplexer(underlyingWatermarkOutput); Watermark emittedWatermark = new Watermark(1); final String id = UUID.randomUUID().toString(); multiplexer.registerNewOutput(id); WatermarkOutput immediateOutput = multiplexer.getImmediateOutput(id); immediateOutput.emitWatermark(emittedWatermark); multiplexer.unregisterOutput(id); multiplexer.onPeriodicEmit(); assertThat(underlyingWatermarkOutput.lastWatermark()).isEqualTo(emittedWatermark); assertThat(underlyingWatermarkOutput.isIdle()).isFalse(); } /** * Convenience method so we don't have to go through the output ID dance when we only want an * immediate output for a given output ID. */ private static WatermarkOutput createImmediateOutput(WatermarkOutputMultiplexer multiplexer) { final String id = UUID.randomUUID().toString(); multiplexer.registerNewOutput(id); return multiplexer.getImmediateOutput(id); } /** * Convenience method so we don't have to go through the output ID dance when we only want an * deferred output for a given output ID. */ private static WatermarkOutput createDeferredOutput(WatermarkOutputMultiplexer multiplexer) { final String id = UUID.randomUUID().toString(); multiplexer.registerNewOutput(id); return multiplexer.getDeferredOutput(id); } private static TestingWatermarkOutput createTestingWatermarkOutput() { return new TestingWatermarkOutput(); } }
WatermarkOutputMultiplexerTest
java
google__dagger
javatests/dagger/functional/producers/subcomponent/ProducerModuleWithSubcomponentsTest.java
{ "start": 1059, "end": 1865 }
class ____ { @Test public void subcomponentFromModules() throws Exception { UsesProducerModuleSubcomponents parent = DaggerUsesProducerModuleSubcomponents.create(); assertThat(parent.strings().get()).containsExactly("from parent"); assertThat(parent.stringsFromChild().get()).containsExactly("from parent", "from child"); } @Test public void subcomponentFromModules_transitively() throws Exception { ParentIncludesProductionSubcomponentTransitively parent = DaggerUsesProducerModuleSubcomponents_ParentIncludesProductionSubcomponentTransitively .create(); assertThat(parent.strings().get()).containsExactly("from parent"); assertThat(parent.stringsFromChild().get()).containsExactly("from parent", "from child"); } }
ProducerModuleWithSubcomponentsTest
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 24414, "end": 24941 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return dialect instanceof MySQLDialect || dialect instanceof H2Dialect || dialect instanceof SQLServerDialect || dialect instanceof PostgreSQLDialect || dialect instanceof GaussDBDialect || dialect instanceof DB2Dialect || dialect instanceof OracleDialect || dialect instanceof SybaseDialect || dialect instanceof DerbyDialect || dialect instanceof HSQLDialect; } } public static
SupportsTruncateTable
java
google__dagger
dagger-runtime/main/java/dagger/Component.java
{ "start": 4460, "end": 4534 }
class ____ extends Parent { * {@literal @}Inject B b; * } * *
Self
java
apache__kafka
trogdor/src/main/java/org/apache/kafka/trogdor/workload/ConsumeBenchWorker.java
{ "start": 13461, "end": 14225 }
class ____ implements Runnable { private final List<Future<Void>> consumeTasks; CloseStatusUpdater(List<Future<Void>> consumeTasks) { this.consumeTasks = consumeTasks; } @Override public void run() { while (!consumeTasks.stream().allMatch(Future::isDone)) { try { Thread.sleep(60000); } catch (InterruptedException e) { log.debug("{} was interrupted. Closing...", this.getClass().getName()); break; // close the thread } } statusUpdaterFuture.cancel(false); statusUpdater.update(); doneFuture.complete(""); } }
CloseStatusUpdater
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/functions/windowing/WindowFunction.java
{ "start": 1421, "end": 2032 }
interface ____<IN, OUT, KEY, W extends Window> extends Function, Serializable { /** * Evaluates the window and outputs none or several elements. * * @param key The key for which this window is evaluated. * @param window The window that is being evaluated. * @param input The elements in the window being evaluated. * @param out A collector for emitting elements. * @throws Exception The function may throw exceptions to fail the program and trigger recovery. */ void apply(KEY key, W window, Iterable<IN> input, Collector<OUT> out) throws Exception; }
WindowFunction
java
spring-projects__spring-security
kerberos/kerberos-core/src/main/java/org/springframework/security/kerberos/authentication/sun/SunJaasKerberosTicketValidator.java
{ "start": 9843, "end": 11346 }
class ____ extends Configuration { private String keyTabLocation; private String servicePrincipalName; private String realmName; private boolean multiTier; private boolean debug; private boolean refreshKrb5Config; private LoginConfig(String keyTabLocation, String servicePrincipalName, String realmName, boolean multiTier, boolean debug, boolean refreshKrb5Config) { this.keyTabLocation = keyTabLocation; this.servicePrincipalName = servicePrincipalName; this.realmName = realmName; this.multiTier = multiTier; this.debug = debug; this.refreshKrb5Config = refreshKrb5Config; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { HashMap<String, String> options = new HashMap<String, String>(); options.put("useKeyTab", "true"); options.put("keyTab", this.keyTabLocation); options.put("principal", this.servicePrincipalName); options.put("storeKey", "true"); options.put("doNotPrompt", "true"); if (this.debug) { options.put("debug", "true"); } if (this.realmName != null) { options.put("realm", this.realmName); } if (this.refreshKrb5Config) { options.put("refreshKrb5Config", "true"); } if (!this.multiTier) { options.put("isInitiator", "false"); } return new AppConfigurationEntry[] { new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options), }; } } }
LoginConfig
java
apache__camel
components/camel-ignite/src/main/java/org/apache/camel/component/ignite/cache/IgniteCacheContinuousQueryConsumer.java
{ "start": 1681, "end": 6082 }
class ____ extends DefaultConsumer { private static final Logger LOG = LoggerFactory.getLogger(IgniteCacheContinuousQueryConsumer.class); private IgniteCacheEndpoint endpoint; private IgniteCache<Object, Object> cache; private QueryCursor<Entry<Object, Object>> cursor; public IgniteCacheContinuousQueryConsumer(IgniteCacheEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; } @Override protected void doStart() throws Exception { super.doStart(); cache = endpoint.obtainCache(); launchContinuousQuery(); LOG.info("Started Ignite Cache Continuous Query consumer for cache {} with query: {}.", cache.getName(), endpoint.getQuery()); maybeFireExistingQueryResults(); } private void maybeFireExistingQueryResults() { if (!endpoint.isFireExistingQueryResults()) { LOG.info("Skipping existing cache results for cache name = {}.", endpoint.getCacheName()); return; } LOG.info("Processing existing cache results for cache name = {}.", endpoint.getCacheName()); for (Entry<Object, Object> entry : cursor) { Exchange exchange = createExchange(entry.getValue()); exchange.getIn().setHeader(IgniteConstants.IGNITE_CACHE_KEY, entry.getKey()); getAsyncProcessor().process(createExchange(entry), new AsyncCallback() { @Override public void done(boolean doneSync) { // do nothing } }); } } private void launchContinuousQuery() { ContinuousQuery<Object, Object> continuousQuery = new ContinuousQuery<>(); if (endpoint.getQuery() != null) { continuousQuery.setInitialQuery(endpoint.getQuery()); } if (endpoint.getRemoteFilter() != null) { continuousQuery.setRemoteFilter(endpoint.getRemoteFilter()); } continuousQuery.setLocalListener(new CacheEntryUpdatedListener<Object, Object>() { @Override public void onUpdated(Iterable<CacheEntryEvent<? extends Object, ? extends Object>> events) throws CacheEntryListenerException { if (LOG.isTraceEnabled()) { LOG.info("Processing Continuous Query event(s): {}.", events); } if (!endpoint.isOneExchangePerUpdate()) { fireGroupedExchange(events); return; } for (CacheEntryEvent<? extends Object, ? extends Object> entry : events) { fireSingleExchange(entry); } } }); continuousQuery.setAutoUnsubscribe(endpoint.isAutoUnsubscribe()); continuousQuery.setPageSize(endpoint.getPageSize()); continuousQuery.setTimeInterval(endpoint.getTimeInterval()); cursor = cache.query(continuousQuery); } @Override protected void doStop() throws Exception { super.doStop(); cursor.close(); LOG.info("Stopped Ignite Cache Continuous Query consumer for cache {} with query: {}.", cache.getName(), endpoint.getQuery()); } private void fireSingleExchange(CacheEntryEvent<? extends Object, ? extends Object> entry) { Exchange exchange = createExchange(entry.getValue()); exchange.getIn().setHeader(IgniteConstants.IGNITE_CACHE_EVENT_TYPE, entry.getEventType()); exchange.getIn().setHeader(IgniteConstants.IGNITE_CACHE_OLD_VALUE, entry.getOldValue()); exchange.getIn().setHeader(IgniteConstants.IGNITE_CACHE_KEY, entry.getKey()); getAsyncProcessor().process(exchange, EmptyAsyncCallback.get()); } private void fireGroupedExchange(Iterable<CacheEntryEvent<? extends Object, ? extends Object>> events) { Exchange exchange = createExchange(events); getAsyncProcessor().process(exchange, EmptyAsyncCallback.get()); } private Exchange createExchange(Object payload) { Exchange exchange = endpoint.createExchange(ExchangePattern.InOnly); Message in = exchange.getIn(); in.setBody(payload); in.setHeader(IgniteConstants.IGNITE_CACHE_NAME, endpoint.getCacheName()); return exchange; } }
IgniteCacheContinuousQueryConsumer
java
apache__flink
flink-python/src/main/java/org/apache/flink/python/env/embedded/EmbeddedPythonEnvironmentManager.java
{ "start": 1252, "end": 1426 }
class ____ python environment manager which is used to create the PythonEnvironment * object. It's used to run python UDF in embedded Python environment. */ @Internal public
of
java
apache__flink
flink-table/flink-sql-gateway/src/main/java/org/apache/flink/table/gateway/rest/serde/ResultInfoDeserializer.java
{ "start": 2536, "end": 6198 }
class ____ extends StdDeserializer<ResultInfo> { private static final long serialVersionUID = 1L; public ResultInfoDeserializer() { super(ResultInfo.class); } private static final JsonToRowDataConverters TO_ROW_DATA_CONVERTERS = new JsonToRowDataConverters(false, false, TimestampFormat.ISO_8601); @Override public ResultInfo deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException { JsonNode node = jsonParser.getCodec().readTree(jsonParser); // deserialize ColumnInfos List<ColumnInfo> columnInfos = Arrays.asList( jsonParser .getCodec() .treeToValue( node.get(FIELD_NAME_COLUMN_INFOS), ColumnInfo[].class)); // deserialize RowFormat RowFormat rowFormat = RowFormat.valueOf(node.get(FIELD_NAME_ROW_FORMAT).asText().toUpperCase()); // deserialize rows List<RowData> data = deserializeData((ArrayNode) node.get(FIELD_NAME_DATA), columnInfos, rowFormat); return new ResultInfo(columnInfos, data, rowFormat); } private List<RowData> deserializeData( ArrayNode serializedRows, List<ColumnInfo> columnInfos, RowFormat rowFormat) { // generate converters for all fields of each row List<JsonToRowDataConverters.JsonToRowDataConverter> converters = buildToRowDataConverters(columnInfos, rowFormat); List<RowData> data = new ArrayList<>(); serializedRows.forEach(rowDataNode -> data.add(convertToRowData(rowDataNode, converters))); return data; } private List<JsonToRowDataConverters.JsonToRowDataConverter> buildToRowDataConverters( List<ColumnInfo> columnInfos, RowFormat rowFormat) { if (rowFormat == RowFormat.JSON) { return columnInfos.stream() .map(ColumnInfo::getLogicalType) .map(TO_ROW_DATA_CONVERTERS::createConverter) .collect(Collectors.toList()); } else if (rowFormat == RowFormat.PLAIN_TEXT) { return IntStream.range(0, columnInfos.size()) .mapToObj( i -> (JsonToRowDataConverters.JsonToRowDataConverter) jsonNode -> jsonNode.isNull() ? null : StringData.fromString( jsonNode.asText())) .collect(Collectors.toList()); } else { throw new UnsupportedOperationException( String.format("Unknown row format: %s.", rowFormat)); } } private GenericRowData convertToRowData( JsonNode serializedRow, List<JsonToRowDataConverters.JsonToRowDataConverter> converters) { ArrayNode fieldsArrayNode = (ArrayNode) serializedRow.get(FIELD_NAME_FIELDS); List<JsonNode> fieldNodes = CollectionUtil.iteratorToList(fieldsArrayNode.iterator()); return GenericRowData.ofKind( RowKind.valueOf(serializedRow.get(FIELD_NAME_KIND).asText()), IntStream.range(0, fieldNodes.size()) .mapToObj(i -> converters.get(i).convert(fieldNodes.get(i))) .toArray()); } }
ResultInfoDeserializer
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/presentation/RotatingQueue_Test.java
{ "start": 1206, "end": 4990 }
class ____ { private final Random random = new Random(); @Test void should_not_be_able_to_offer_zero_capacity_queue() { // GIVEN Queue<Integer> rotating = new RotatingQueue<>(0); // WHEN boolean actual = rotating.offer(random.nextInt()); // THEN then(actual).isFalse(); then(rotating.isEmpty()).isTrue(); } @Test void should_not_be_able_to_add_to_zero_capacity_queue() { // GIVEN Queue<Integer> rotating = new RotatingQueue<>(0); // WHEN IllegalStateException exception = catchThrowableOfType(IllegalStateException.class, () -> rotating.add(random.nextInt())); // THEN then(exception).hasMessageContaining("full"); } @ParameterizedTest @MethodSource("should_rotate_old_elements_source") void should_rotate_old_elements_with_offer( int capacity, List<Integer> toAdd, List<Integer> expected) { // GIVEN Queue<Integer> rotating = new RotatingQueue<>(capacity); // WHEN for (int i : toAdd) rotating.offer(i); // THEN then(rotating).containsExactlyElementsOf(expected); } @ParameterizedTest @MethodSource("should_rotate_old_elements_source") void should_rotate_old_elements_with_add( int capacity, List<Integer> toAdd, List<Integer> expected) { // GIVEN Queue<Integer> rotating = new RotatingQueue<>(capacity); // WHEN for (int i : toAdd) { rotating.add(i); } // THEN then(rotating).containsExactlyElementsOf(expected); } static Stream<Arguments> should_rotate_old_elements_source() { return Stream.of(Arguments.of(1, ImmutableList.of(1), ImmutableList.of(1)), Arguments.of(2, ImmutableList.of(1), ImmutableList.of(1)), Arguments.of(2, ImmutableList.of(1, 2), ImmutableList.of(1, 2)), Arguments.of(2, ImmutableList.of(1, 2, 3), ImmutableList.of(2, 3)), Arguments.of(3, ImmutableList.of(1, 2, 3, 4, 5), ImmutableList.of(3, 4, 5))); } @Test void should_allow_null() { // GIVEN Queue<Integer> rotating = new RotatingQueue<>(3); // WHEN rotating.offer(null); // THEN then(rotating).containsExactly((Integer) null); } @Test void should_be_able_to_peek_at_empty_queue() { // GIVEN Queue<Integer> rotating = new RotatingQueue<>(1); // WHEN Integer actual = rotating.peek(); // THEN then(actual).isNull(); } @Test void should_be_able_to_peek_at_non_empty_queue() { // GIVEN Queue<Integer> rotating = new RotatingQueue<>(3); Integer first = random.nextInt(); rotating.add(first); rotating.add(random.nextInt()); // WHEN Integer actual = rotating.peek(); // THEN then(actual).isEqualTo(first); } @Test void should_be_able_to_poll_empty_queue() { // GIVEN Queue<Integer> rotating = new RotatingQueue<>(1); // WHEN Integer actual = rotating.poll(); // THEN then(actual).isNull(); } @Test void should_be_able_to_poll_non_empty_queue() { // GIVEN Queue<Integer> rotating = new RotatingQueue<>(3); Integer first = random.nextInt(); rotating.add(first); Integer second = random.nextInt(); rotating.add(second); // WHEN Integer actual = rotating.poll(); // THEN then(actual).isEqualTo(first); then(rotating).containsExactly(second); } @Test void should_not_be_able_to_be_created_with_a_negative_capacity() { // WHEN IllegalArgumentException exception = catchIllegalArgumentException(() -> new RotatingQueue<>(-1)); // THEN then(exception).hasMessageContainingAll("non-negative", "-1"); } }
RotatingQueue_Test
java
google__dagger
javatests/dagger/internal/codegen/XMethodElementsTest.java
{ "start": 1513, "end": 1715 }
class ____ {", " void method() {}", "}"); Source javaChild = javaSource( "test.JavaChild", "package test;", "", "
JavaBase
java
apache__flink
flink-core/src/main/java/org/apache/flink/core/classloading/ComponentClassLoader.java
{ "start": 10043, "end": 11655 }
class ____<T> implements Enumeration<T> { private final Iterator<T> backingIterator; public IteratorBackedEnumeration(Iterator<T> backingIterator) { this.backingIterator = backingIterator; } @Override public boolean hasMoreElements() { return backingIterator.hasNext(); } @Override public T nextElement() { return backingIterator.next(); } } // ---------------------------------------------------------------------------------------------- // Utils // ---------------------------------------------------------------------------------------------- private static String[] convertPackagePrefixesToPathPrefixes(String[] packagePrefixes) { return Arrays.stream(packagePrefixes) .map(packageName -> packageName.replace('.', '/')) .toArray(String[]::new); } static { ClassLoader platformLoader = null; try { platformLoader = (ClassLoader) ClassLoader.class.getMethod("getPlatformClassLoader").invoke(null); } catch (NoSuchMethodException e) { // on Java 8 this method does not exist, but using null indicates the bootstrap // loader that we want to have } catch (Exception e) { throw new IllegalStateException("Cannot retrieve platform classloader on Java 9+", e); } PLATFORM_OR_BOOTSTRAP_LOADER = platformLoader; ClassLoader.registerAsParallelCapable(); } }
IteratorBackedEnumeration
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractShortAssert.java
{ "start": 1489, "end": 22362 }
class ____<SELF extends AbstractShortAssert<SELF>> extends AbstractComparableAssert<SELF, Short> implements NumberAssert<SELF, Short> { // TODO reduce the visibility of the fields annotated with @VisibleForTesting Shorts shorts = Shorts.instance(); protected AbstractShortAssert(Short actual, Class<?> selfType) { super(actual, selfType); } /** * Verifies that the actual value is equal to the given one. * <p> * Example: * <pre><code class='java'> // assertion will pass: * assertThat(Short.valueOf(&quot;1&quot;)).isEqualTo((short) 1); * * // assertion will fail: * assertThat(Short.valueOf(&quot;-1&quot;)).isEqualTo((short) 1);</code></pre> * * @param expected the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is not equal to the given one. */ public SELF isEqualTo(short expected) { shorts.assertEqual(info, actual, expected); return myself; } /** * Verifies that the actual value is not equal to the given one. * <p> * Example: * <pre><code class='java'> // assertion will pass: * assertThat(Short.valueOf((&quot;-1&quot;)).isNotEqualTo((short) 1); * * // assertion will fail: * assertThat(Short.valueOf(&quot;1&quot;)).isNotEqualTo((short) 1);</code></pre> * * @param other the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is equal to the given one. */ public SELF isNotEqualTo(short other) { shorts.assertNotEqual(info, actual, other); return myself; } /** {@inheritDoc} */ @Override public SELF isZero() { shorts.assertIsZero(info, actual); return myself; } /** {@inheritDoc} */ @Override public SELF isNotZero() { shorts.assertIsNotZero(info, actual); return myself; } /** {@inheritDoc} */ @Override public SELF isOne() { shorts.assertIsOne(info, actual); return myself; } /** {@inheritDoc} */ @Override public SELF isPositive() { shorts.assertIsPositive(info, actual); return myself; } /** {@inheritDoc} */ @Override public SELF isNegative() { shorts.assertIsNegative(info, actual); return myself; } /** {@inheritDoc} */ @Override public SELF isNotNegative() { shorts.assertIsNotNegative(info, actual); return myself; } /** {@inheritDoc} */ @Override public SELF isNotPositive() { shorts.assertIsNotPositive(info, actual); return myself; } /** * Verifies that the actual value is even. * <p> * Example: * <pre><code class='java'> // assertions will pass * assertThat((short) 12).isEven(); * assertThat((short) -46).isEven(); * * // assertions will fail * assertThat((short) 3).isEven(); * assertThat((short) 15).isEven();</code></pre> * * @return this assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is not positive. * @since 3.17.0 */ public SELF isEven() { shorts.assertIsEven(info, actual); return myself; } /** * Verifies that the actual value is odd. * <p> * Example: * <pre><code class='java'> // assertions will pass * assertThat((short) 3).isOdd(); * assertThat((short) -17).isOdd(); * * // assertions will fail * assertThat((short) 2).isOdd(); * assertThat((short) -24).isOdd();</code></pre> * * @return this assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is not positive. * @since 3.17.0 */ public SELF isOdd() { shorts.assertIsOdd(info, actual); return myself; } /** * Verifies that the actual value is less than the given one. * <p> * Example: * <pre><code class='java'> // assertion will pass: * assertThat(Short.valueOf(&quot;1&quot;)).isLessThan((short) 2); * * // assertion will fail: * assertThat(Short.valueOf(&quot;1&quot;)).isLessThan((short) 0); * assertThat(Short.valueOf(&quot;1&quot;)).isLessThan((short) 1);</code></pre> * * @param other the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is equal to or greater than the given one. */ public SELF isLessThan(short other) { shorts.assertLessThan(info, actual, other); return myself; } /** * Verifies that the actual value is less than or equal to the given one. * <p> * Example: * <pre><code class='java'> // assertion will pass: * assertThat(Short.valueOf(&quot;1&quot;)).isLessThanOrEqualTo((short) 1); * * // assertion will fail: * assertThat(Short.valueOf(&quot;1&quot;)).isLessThanOrEqualTo((short) 0);</code></pre> * * @param other the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is greater than the given one. */ public SELF isLessThanOrEqualTo(short other) { shorts.assertLessThanOrEqualTo(info, actual, other); return myself; } /** * Verifies that the actual value is greater than the given one. * <p> * Example: * <pre><code class='java'> // assertion will pass: * assertThat(Short.valueOf(&quot;1&quot;)).isGreaterThan((short) 0); * * // assertions will fail: * assertThat(Short.valueOf(&quot;0&quot;)).isGreaterThan((short) 1); * assertThat(Short.valueOf(&quot;0&quot;)).isGreaterThan((short) 0);</code></pre> * * @param other the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is equal to or less than the given one. */ public SELF isGreaterThan(short other) { shorts.assertGreaterThan(info, actual, other); return myself; } /** * Verifies that the actual value is greater than or equal to the given one. * <p> * Example: * <pre><code class='java'> // assertion will pass: * assertThat(Short.valueOf(&quot;1&quot;)).isGreaterThanOrEqualTo((short) 1); * * // assertion will fail: * assertThat(Short.valueOf(&quot;0&quot;)).isGreaterThanOrEqualTo((short) 1);</code></pre> * * @param other the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is less than the given one. */ public SELF isGreaterThanOrEqualTo(short other) { shorts.assertGreaterThanOrEqualTo(info, actual, other); return myself; } /** * Verifies that the actual value is in [start, end] range (start included, end included). * * <p> * Example: * <pre><code class='java'> // assertions will pass * assertThat((short) 1).isBetween((short) -1, (short) 2); * assertThat((short) 1).isBetween((short) 1, (short) 2); * assertThat((short) 1).isBetween((short) 0, (short) 1); * * // assertion will fail * assertThat((short) 1).isBetween((short) 2, (short) 3);</code></pre> */ @Override public SELF isBetween(Short start, Short end) { shorts.assertIsBetween(info, actual, start, end); return myself; } /** * Verifies that the actual value is in ]start, end[ range (start excluded, end excluded). * * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat((short) 1).isStrictlyBetween((short) -1, (short) 2); * * // assertions will fail * assertThat((short) 1).isStrictlyBetween((short) 1, (short) 2); * assertThat((short) 1).isStrictlyBetween((short) 0, (short) 1); * assertThat((short) 1).isStrictlyBetween((short) 2, (short) 3);</code></pre> */ @Override public SELF isStrictlyBetween(Short start, Short end) { shorts.assertIsStrictlyBetween(info, actual, start, end); return myself; } /** * Verifies that the actual number is close to the given one within the given offset value. * <p> * When <i>abs(actual - expected) == offset value</i>, the assertion: * <ul> * <li><b>succeeds</b> when using {@link Assertions#within(Short)}</li> * <li><b>fails</b> when using {@link Assertions#byLessThan(Short)} or {@link Offset#strictOffset(Number)}</li> * </ul> * <p> * <b>Breaking change</b> since 2.9.0/3.9.0: using {@link Assertions#byLessThan(Short)} implies a <b>strict</b> comparison, * use {@link Assertions#within(Short)} to get the old behavior. * <p> * Examples: * <pre><code class='java'> // assertions will pass: * assertThat((short) 5).isCloseTo((short) 7, within((short) 3)); * assertThat((short) 5).isCloseTo((short) 7, byLessThan((short) 3)); * * // if difference is exactly equals to the offset, it's ok ... * assertThat((short) 5).isCloseTo((short) 7, within((short) 2)); * // ... but not with byLessThan which implies a strict comparison * assertThat((short) 5).isCloseTo((short) 7, byLessThan((short) 2)); // FAIL * * // assertions will fail * assertThat((short) 5).isCloseTo((short) 7, within((short) 1)); * assertThat((short) 5).isCloseTo((short) 7, byLessThan((short) 1)); * assertThat((short) 5).isCloseTo((short) 7, byLessThan((short) 2));</code></pre> * * @param expected the given int to compare the actual value to. * @param offset the given positive offset. * @return {@code this} assertion object. * @throws NullPointerException if the given offset is {@code null}. * @throws AssertionError if the actual value is not close enough to the given one. */ public SELF isCloseTo(short expected, Offset<Short> offset) { shorts.assertIsCloseTo(info, actual, expected, offset); return myself; } /** * Verifies that the actual number is not close to the given one by less than the given offset.<br> * <p> * When <i>abs(actual - expected) == offset value</i>, the assertion: * <ul> * <li><b>succeeds</b> when using {@link Assertions#byLessThan(Short)} or {@link Offset#strictOffset(Number)}</li> * <li><b>fails</b> when using {@link Assertions#within(Short)}</li> * </ul> * <p> * <b>Breaking change</b> since 2.9.0/3.9.0: using {@link Assertions#byLessThan(Short)} implies a <b>strict</b> comparison, * use {@link Assertions#within(Short)} to get the old behavior. * <p> * Examples: * <pre><code class='java'> // assertions will pass: * assertThat((short) 5).isNotCloseTo((short) 7, byLessThan((short) 1)); * assertThat((short) 5).isNotCloseTo((short) 7, within((short) 1)); * // diff == offset but isNotCloseTo succeeds as we use byLessThan * assertThat((short) 5).isNotCloseTo((short) 7, byLessThan((short) 2)); * * // assertions will fail * assertThat((short) 5).isNotCloseTo((short) 7, within((short) 2)); * assertThat((short) 5).isNotCloseTo((short) 7, byLessThan((short) 3));</code></pre> * * @param expected the given int to compare the actual value to. * @param offset the given positive offset. * @return {@code this} assertion object. * @throws NullPointerException if the given offset is {@code null}. * @throws AssertionError if the actual value is close to the given one. * @see Assertions#byLessThan(Short) * @since 2.6.0 / 3.6.0 */ public SELF isNotCloseTo(short expected, Offset<Short> offset) { shorts.assertIsNotCloseTo(info, actual, expected, offset); return myself; } /** * Verifies that the actual number is close to the given one within the given offset value. * <p> * When <i>abs(actual - expected) == offset value</i>, the assertion: * <ul> * <li><b>succeeds</b> when using {@link Assertions#within(Short)}</li> * <li><b>fails</b> when using {@link Assertions#byLessThan(Short)} or {@link Offset#strictOffset(Number)}</li> * </ul> * <p> * <b>Breaking change</b> since 2.9.0/3.9.0: using {@link Assertions#byLessThan(Short)} implies a <b>strict</b> comparison, * use {@link Assertions#within(Short)} to get the old behavior. * <p> * Examples: * <pre><code class='java'> // assertions will pass: * assertThat((short) 5).isCloseTo((short) 7, within((short) 3)); * assertThat((short) 5).isCloseTo((short) 7, byLessThan((short) 3)); * * // if difference is exactly equals to the offset, it's ok ... * assertThat((short) 5).isCloseTo((short) 7, within((short) 2)); * // ... but not with byLessThan which implies a strict comparison * assertThat((short) 5).isCloseTo((short) 7, byLessThan((short) 2)); // FAIL * * // assertions will fail * assertThat((short) 5).isCloseTo((short) 7, within((short) 1)); * assertThat((short) 5).isCloseTo((short) 7, byLessThan((short) 1)); * assertThat((short) 5).isCloseTo((short) 7, byLessThan((short) 2));</code></pre> * * @param expected the given int to compare the actual value to. * @param offset the given positive offset. * @return {@code this} assertion object. * @throws NullPointerException if the given offset is {@code null}. * @throws AssertionError if the actual value is not close enough to the given one. */ @Override public SELF isCloseTo(Short expected, Offset<Short> offset) { shorts.assertIsCloseTo(info, actual, expected, offset); return myself; } /** * Verifies that the actual number is not close to the given one by less than the given offset.<br> * <p> * When <i>abs(actual - expected) == offset value</i>, the assertion: * <ul> * <li><b>succeeds</b> when using {@link Assertions#byLessThan(Short)} or {@link Offset#strictOffset(Number)}</li> * <li><b>fails</b> when using {@link Assertions#within(Short)}</li> * </ul> * <p> * <b>Breaking change</b> since 2.9.0/3.9.0: using {@link Assertions#byLessThan(Short)} implies a <b>strict</b> comparison, * use {@link Assertions#within(Short)} to get the old behavior. * <p> * Examples: * <pre><code class='java'> // assertions will pass: * assertThat((short) 5).isNotCloseTo((short) 7, byLessThan((short) 1)); * assertThat((short) 5).isNotCloseTo((short) 7, within((short) 1)); * // diff == offset but isNotCloseTo succeeds as we use byLessThan * assertThat((short) 5).isNotCloseTo((short) 7, byLessThan((short) 2)); * * // assertions will fail * assertThat((short) 5).isNotCloseTo((short) 7, within((short) 2)); * assertThat((short) 5).isNotCloseTo((short) 7, byLessThan((short) 3));</code></pre> * * @param expected the given int to compare the actual value to. * @param offset the given positive offset. * @return {@code this} assertion object. * @throws NullPointerException if the given offset is {@code null}. * @throws AssertionError if the actual value is close to the given one. * @see Assertions#byLessThan(Short) * @since 2.6.0 / 3.6.0 */ @Override public SELF isNotCloseTo(Short expected, Offset<Short> offset) { shorts.assertIsNotCloseTo(info, actual, expected, offset); return myself; } /** * Verifies that the actual number is close to the given one within the given percentage.<br> * If difference is equal to the percentage value, assertion is considered valid. * <p> * Example with short: * <pre><code class='java'> // assertions will pass: * assertThat((short) 11).isCloseTo(Short.valueOf(10), withinPercentage((short) 20)); * * // if difference is exactly equals to the computed offset (1), it's ok * assertThat((short) 11).isCloseTo(Short.valueOf(10), withinPercentage((short) 10)); * * // assertion will fail * assertThat((short) 11).isCloseTo(Short.valueOf(10), withinPercentage((short) 5));</code></pre> * * @param expected the given number to compare the actual value to. * @param percentage the given positive percentage. * @return {@code this} assertion object. * @throws NullPointerException if the given offset is {@code null}. * @throws NullPointerException if the expected number is {@code null}. * @throws AssertionError if the actual value is not close to the given one. */ @Override public SELF isCloseTo(Short expected, Percentage percentage) { shorts.assertIsCloseToPercentage(info, actual, expected, percentage); return myself; } /** * Verifies that the actual number is not close to the given one within the given percentage.<br> * If difference is equal to the percentage value, the assertion fails. * <p> * Example with short: * <pre><code class='java'> // assertion will pass: * assertThat((short) 11).isNotCloseTo(Short.valueOf(10), withinPercentage((short) 5)); * * // assertions will fail * assertThat((short) 11).isNotCloseTo(Short.valueOf(10), withinPercentage((short) 10)); * assertThat((short) 11).isNotCloseTo(Short.valueOf(10), withinPercentage((short) 20));</code></pre> * * @param expected the given number to compare the actual value to. * @param percentage the given positive percentage. * @return {@code this} assertion object. * @throws NullPointerException if the given offset is {@code null}. * @throws NullPointerException if the expected number is {@code null}. * @throws AssertionError if the actual value is close to the given one. * @since 2.6.0 / 3.6.0 */ @Override public SELF isNotCloseTo(Short expected, Percentage percentage) { shorts.assertIsNotCloseToPercentage(info, actual, expected, percentage); return myself; } /** * Verifies that the actual number is close to the given one within the given percentage.<br> * If difference is equal to the percentage value, assertion is considered valid. * <p> * Example with short: * <pre><code class='java'> // assertions will pass: * assertThat((short) 11).isCloseTo((short) 10, withinPercentage((short) 20)); * * // if difference is exactly equals to the computed offset (1), it's ok * assertThat((short) 11).isCloseTo((short) 10, withinPercentage((short) 10)); * * // assertion will fail * assertThat((short) 11).isCloseTo((short) 10, withinPercentage((short) 5));</code></pre> * * @param expected the given number to compare the actual value to. * @param percentage the given positive percentage. * @return {@code this} assertion object. * @throws NullPointerException if the given offset is {@code null}. * @throws NullPointerException if the expected number is {@code null}. * @throws AssertionError if the actual value is not close to the given one. */ public SELF isCloseTo(short expected, Percentage percentage) { shorts.assertIsCloseToPercentage(info, actual, expected, percentage); return myself; } /** * Verifies that the actual number is not close to the given one within the given percentage.<br> * If difference is equal to the percentage value, the assertion fails. * <p> * Example with short: * <pre><code class='java'> // assertion will pass: * assertThat((short) 11).isNotCloseTo((short) 10, withinPercentage((short) 5)); * * // assertions will fail * assertThat((short) 11).isNotCloseTo((short) 10, withinPercentage((short) 10)); * assertThat((short) 11).isNotCloseTo((short) 10, withinPercentage((short) 20));</code></pre> * * @param expected the given number to compare the actual value to. * @param percentage the given positive percentage. * @return {@code this} assertion object. * @throws NullPointerException if the given offset is {@code null}. * @throws NullPointerException if the expected number is {@code null}. * @throws AssertionError if the actual value is close to the given one. * @since 2.6.0 / 3.6.0 */ public SELF isNotCloseTo(short expected, Percentage percentage) { shorts.assertIsNotCloseToPercentage(info, actual, expected, percentage); return myself; } @Override @CheckReturnValue public SELF usingComparator(Comparator<? super Short> customComparator) { return usingComparator(customComparator, null); } @Override @CheckReturnValue public SELF usingComparator(Comparator<? super Short> customComparator, String customComparatorDescription) { shorts = new Shorts(new ComparatorBasedComparisonStrategy(customComparator, customComparatorDescription)); return super.usingComparator(customComparator, customComparatorDescription); } @Override @CheckReturnValue public SELF usingDefaultComparator() { shorts = Shorts.instance(); return super.usingDefaultComparator(); } }
AbstractShortAssert
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/jdk/MapWithGenericValuesDeserTest.java
{ "start": 1062, "end": 1249 }
class ____ should behave like {@link MapSubClass}, but by * using annotations. */ @JsonDeserialize(keyAs=StringWrapper.class, contentAs=BooleanWrapper.class) static
that
java
apache__rocketmq
store/src/test/java/org/apache/rocketmq/store/FlushDiskWatcherTest.java
{ "start": 1011, "end": 3146 }
class ____ { private final long timeoutMill = 5000; @Test public void testTimeout() throws Exception { FlushDiskWatcher flushDiskWatcher = new FlushDiskWatcher(); flushDiskWatcher.setDaemon(true); flushDiskWatcher.start(); int count = 100; List<GroupCommitRequest> requestList = new LinkedList<>(); for (int i = 0; i < count; i++) { GroupCommitRequest groupCommitRequest = new GroupCommitRequest(0, timeoutMill); requestList.add(groupCommitRequest); flushDiskWatcher.add(groupCommitRequest); } Thread.sleep(2 * timeoutMill); for (GroupCommitRequest request : requestList) { request.wakeupCustomer(PutMessageStatus.PUT_OK); } for (GroupCommitRequest request : requestList) { Assert.assertTrue(request.future().isDone()); Assert.assertEquals(request.future().get(), PutMessageStatus.FLUSH_DISK_TIMEOUT); } Assert.assertEquals(flushDiskWatcher.queueSize(), 0); flushDiskWatcher.shutdown(); } @Test public void testWatcher() throws Exception { FlushDiskWatcher flushDiskWatcher = new FlushDiskWatcher(); flushDiskWatcher.setDaemon(true); flushDiskWatcher.start(); int count = 100; List<GroupCommitRequest> requestList = new LinkedList<>(); for (int i = 0; i < count; i++) { GroupCommitRequest groupCommitRequest = new GroupCommitRequest(0, timeoutMill); requestList.add(groupCommitRequest); flushDiskWatcher.add(groupCommitRequest); groupCommitRequest.wakeupCustomer(PutMessageStatus.PUT_OK); } Thread.sleep((timeoutMill << 20) / 1000000); for (GroupCommitRequest request : requestList) { Assert.assertTrue(request.future().isDone()); Assert.assertEquals(request.future().get(), PutMessageStatus.PUT_OK); } Assert.assertEquals(flushDiskWatcher.queueSize(), 0); flushDiskWatcher.shutdown(); } }
FlushDiskWatcherTest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/seda/SedaConcurrentConsumersTest.java
{ "start": 1069, "end": 1896 }
class ____ extends ContextTestSupport { @Override protected Registry createCamelRegistry() throws Exception { Registry jndi = super.createCamelRegistry(); jndi.bind("count", "5"); return jndi; } @Test public void testSendToSeda() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World"); template.sendBody("seda:foo?concurrentConsumers=5", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("seda:foo?concurrentConsumers=#count").to("mock:result"); } }; } }
SedaConcurrentConsumersTest
java
netty__netty
pkitesting/src/main/java/io/netty/pkitesting/CertificateBuilder.java
{ "start": 36552, "end": 36678 }
enum ____ both the key type, key generation parameters, and the signature * algorithm to use. */ public
encapsulates
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/injection/guice/internal/Scoping.java
{ "start": 919, "end": 1210 }
enum ____ { /** * No scoping annotation has been applied. Note that this is different from {@code * in(Scopes.NO_SCOPE)}, where the 'NO_SCOPE' has been explicitly applied. */ UNSCOPED, /** * One instance per {@link Injector}. */ EAGER_SINGLETON }
Scoping
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/pubsub/RedisPubSubListener.java
{ "start": 916, "end": 2860 }
interface ____<K, V> { /** * Message received from a channel subscription. * * @param channel Channel. * @param message Message. */ void message(K channel, V message); /** * Message received from a pattern subscription. * * @param pattern Pattern * @param channel Channel * @param message Message */ void message(K pattern, K channel, V message); /** * Subscribed to a channel. * * @param channel Channel * @param count Subscription count. */ void subscribed(K channel, long count); /** * Subscribed to a pattern. * * @param pattern Pattern. * @param count Subscription count. */ void psubscribed(K pattern, long count); /** * Unsubscribed from a channel. * * @param channel Channel * @param count Subscription count. */ void unsubscribed(K channel, long count); /** * Unsubscribed from a pattern. * * @param pattern Channel * @param count Subscription count. */ void punsubscribed(K pattern, long count); /** * Subscribed to a Shard channel. * * @param shardChannel Shard channel * @param count Subscription count. * @since 6.4 */ default void ssubscribed(K shardChannel, long count) { subscribed(shardChannel, count); } /** * Unsubscribed from a shard channel. * * @param shardChannel Channel * @param count Subscription count. * @since 6.4 */ default void sunsubscribed(K shardChannel, long count) { unsubscribed(shardChannel, count); } /** * Message received from a shard channel subscription. * * @param shardChannel shard channel. * @param message Message. * @since 6.4 */ default void smessage(K shardChannel, V message) { message(shardChannel, message); } }
RedisPubSubListener
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverterTests.java
{ "start": 12765, "end": 13158 }
class ____ { private MyCustomElement element; public MyRootElement() { } public MyRootElement(MyCustomElement element) { this.element = element; } @XmlJavaTypeAdapter(MyCustomElementAdapter.class) public MyCustomElement getElement() { return element; } public void setElement(MyCustomElement element) { this.element = element; } } public static
MyRootElement
java
apache__camel
components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/SecurityConstraintMapping.java
{ "start": 1756, "end": 4607 }
class ____ implements SecurityConstraint { // url -> roles private Map<String, String> inclusions; // url private Set<String> exclusions; @Override public String restricted(String url) { // check excluded first if (excludedUrl(url)) { return null; } // is the url restricted? String constraint = includedUrl(url); if (constraint == null) { return null; } // is there any roles for the restricted url? String roles = inclusions != null ? inclusions.get(constraint) : null; if (roles == null) { // use wildcard to indicate any role is accepted return "*"; } else { return roles; } } private String includedUrl(String url) { String candidate = null; if (inclusions != null && !inclusions.isEmpty()) { for (String constraint : inclusions.keySet()) { if (PatternHelper.matchPattern(url, constraint)) { if (candidate == null) { candidate = constraint; } else if (constraint.length() > candidate.length()) { // we want the constraint that has the longest context-path matching as its // the most explicit for the target url candidate = constraint; } } } return candidate; } // by default if no included has been configured then everything is restricted return "*"; } private boolean excludedUrl(String url) { if (exclusions != null && !exclusions.isEmpty()) { for (String constraint : exclusions) { if (PatternHelper.matchPattern(url, constraint)) { // force not matches if this was an exclusion return true; } } } return false; } public void addInclusion(String constraint) { if (inclusions == null) { inclusions = new java.util.LinkedHashMap<>(); } inclusions.put(constraint, null); } public void addInclusion(String constraint, String roles) { if (inclusions == null) { inclusions = new java.util.LinkedHashMap<>(); } inclusions.put(constraint, roles); } public void addExclusion(String constraint) { if (exclusions == null) { exclusions = new LinkedHashSet<>(); } exclusions.add(constraint); } public void setInclusions(Map<String, String> inclusions) { this.inclusions = inclusions; } public void setExclusions(Set<String> exclusions) { this.exclusions = exclusions; } }
SecurityConstraintMapping
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/monitor/fs/FsHealthService.java
{ "start": 5680, "end": 8641 }
class ____ extends AbstractRunnable { // Exposed for testing static final String TEMP_FILE_NAME = ".es_temp_file"; private final byte[] bytesToWrite = UUIDs.randomBase64UUID().getBytes(StandardCharsets.UTF_8); @Override public void onFailure(Exception e) { logger.error("health check failed", e); } @Override public void onRejection(Exception e) { if (e instanceof EsRejectedExecutionException esre && esre.isExecutorShutdown()) { logger.debug("health check skipped (executor shut down)", e); } else { onFailure(e); assert false : e; } } @Override public void doRun() { if (enabled) { monitorFSHealth(); logger.debug("health check completed"); } } private void monitorFSHealth() { Set<Path> currentUnhealthyPaths = null; final Path[] paths; try { paths = nodeEnv.nodeDataPaths(); } catch (IllegalStateException e) { logger.error("health check failed", e); brokenLock = true; return; } for (Path path : paths) { final long executionStartTime = currentTimeMillisSupplier.getAsLong(); try { if (Files.exists(path)) { final Path tempDataPath = path.resolve(TEMP_FILE_NAME); Files.deleteIfExists(tempDataPath); try (OutputStream os = Files.newOutputStream(tempDataPath, StandardOpenOption.CREATE_NEW)) { os.write(bytesToWrite); IOUtils.fsync(tempDataPath, false); } Files.delete(tempDataPath); final long elapsedTime = currentTimeMillisSupplier.getAsLong() - executionStartTime; if (elapsedTime > slowPathLoggingThreshold.millis()) { logger.warn( "health check of [{}] took [{}ms] which is above the warn threshold of [{}]", path, elapsedTime, slowPathLoggingThreshold ); } } } catch (Exception ex) { logger.error(() -> "health check of [" + path + "] failed", ex); if (currentUnhealthyPaths == null) { currentUnhealthyPaths = Sets.newHashSetWithExpectedSize(1); } currentUnhealthyPaths.add(path); } } unhealthyPaths = currentUnhealthyPaths; brokenLock = false; } } }
FsHealthMonitor
java
quarkusio__quarkus
extensions/hibernate-reactive/deployment/src/test/java/io/quarkus/hibernate/reactive/validation/MyEntity.java
{ "start": 425, "end": 1273 }
class ____ { public static final String ENTITY_NAME_TOO_LONG = "entity name too long"; public static final String ENTITY_NAME_CANNOT_BE_EMPTY = "entity name cannot be empty"; private long id; @NotNull @NotEmpty(message = ENTITY_NAME_CANNOT_BE_EMPTY) @Size(max = 50, message = ENTITY_NAME_TOO_LONG) private String name; public MyEntity() { } public MyEntity(String name) { this.name = name; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "MyEntity:" + name; } }
MyEntity
java
quarkusio__quarkus
extensions/smallrye-openapi/deployment/src/main/java/io/quarkus/smallrye/openapi/deployment/MediaTypeConfigSource.java
{ "start": 236, "end": 1243 }
class ____ implements ConfigSource { private final Map<String, String> mediaTypes = new HashMap<>(); public MediaTypeConfigSource() { mediaTypes.put(SmallRyeOASConfig.DEFAULT_PRODUCES_STREAMING, "application/octet-stream"); mediaTypes.put(SmallRyeOASConfig.DEFAULT_CONSUMES_STREAMING, "application/octet-stream"); mediaTypes.put(SmallRyeOASConfig.DEFAULT_PRODUCES, "application/json"); mediaTypes.put(SmallRyeOASConfig.DEFAULT_CONSUMES, "application/json"); mediaTypes.put(SmallRyeOASConfig.DEFAULT_PRODUCES_PRIMITIVES, "text/plain"); mediaTypes.put(SmallRyeOASConfig.DEFAULT_CONSUMES_PRIMITIVES, "text/plain"); } @Override public Set<String> getPropertyNames() { return mediaTypes.keySet(); } @Override public String getValue(String propertyName) { return mediaTypes.get(propertyName); } @Override public String getName() { return getClass().getSimpleName(); } }
MediaTypeConfigSource
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/TestMapGenerator.java
{ "start": 947, "end": 1168 }
interface ____<K extends @Nullable Object, V extends @Nullable Object> extends TestContainerGenerator<Map<K, V>, Map.Entry<K, V>> { K[] createKeyArray(int length); V[] createValueArray(int length); }
TestMapGenerator
java
apache__camel
components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/HazelcastOperation.java
{ "start": 857, "end": 2717 }
enum ____ { // actions PUT("put"), DELETE("delete"), GET("get"), UPDATE("update"), QUERY("query"), GET_ALL("getAll"), CLEAR("clear"), PUT_IF_ABSENT("putIfAbsent"), ADD_ALL("addAll"), REMOVE_ALL("removeAll"), RETAIN_ALL("retainAll"), EVICT("evict"), EVICT_ALL("evictAll"), VALUE_COUNT("valueCount"), CONTAINS_KEY("containsKey"), CONTAINS_VALUE("containsValue"), GET_KEYS("getKeys"), // multimap REMOVE_VALUE("removeValue"), // atomic numbers INCREMENT("increment"), DECREMENT("decrement"), SET_VALUE("setValue"), DESTROY("destroy"), COMPARE_AND_SET("compareAndSet"), GET_AND_ADD("getAndAdd"), // queue ADD("add"), OFFER("offer"), PEEK("peek"), POLL("poll"), REMAINING_CAPACITY("remainingCapacity"), DRAIN_TO("drainTo"), REMOVE_IF("removeIf"), TAKE("take"), // topic PUBLISH("publish"), // ring_buffer READ_ONCE_HEAD("readOnceHead"), READ_ONCE_TAIL("readOnceTail"), CAPACITY("capacity"); private static final HazelcastOperation[] VALUES = values(); private final String operation; HazelcastOperation(String operation) { this.operation = operation; } public static HazelcastOperation getHazelcastOperation(String name) { if (name == null) { return null; } for (HazelcastOperation hazelcastOperation : VALUES) { if (hazelcastOperation.toString().equalsIgnoreCase(name) || hazelcastOperation.name().equalsIgnoreCase(name)) { return hazelcastOperation; } } throw new IllegalArgumentException(String.format("Operation '%s' is not supported by this component.", name)); } @Override public String toString() { return operation; } }
HazelcastOperation
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/jdbc/Expectation.java
{ "start": 6684, "end": 8059 }
class ____ implements Expectation { @Override public final void verifyOutcome(int rowCount, PreparedStatement statement, int batchPosition, String sql) { final int result; try { result = toCallableStatement( statement ).getInt( parameterIndex() ); } catch ( SQLException sqle ) { sqlExceptionHelper.logExceptions( sqle, "Could not extract row count from CallableStatement" ); throw new GenericJDBCException( "Could not extract row count from CallableStatement", sqle ); } if ( batchPosition < 0 ) { checkNonBatched( expectedRowCount(), result, sql ); } else { checkBatched( expectedRowCount(), result, batchPosition, sql ); } } @Override public void validate(boolean callable) throws MappingException { if ( !callable ) { throw new MappingException( "Expectation.OutParameter operates exclusively on CallableStatements" ); } } @Override public int getNumberOfParametersUsed() { return 1; } @Override public int prepare(PreparedStatement statement) throws SQLException, HibernateException { toCallableStatement( statement ).registerOutParameter( parameterIndex(), Types.NUMERIC ); return 1; } @Override public boolean canBeBatched() { return false; } protected int parameterIndex() { return 1; } protected int expectedRowCount() { return 1; } } }
OutParameter
java
netty__netty
common/src/main/java/io/netty/util/internal/CleanerJava6.java
{ "start": 5735, "end": 6155 }
class ____ implements CleanableDirectBuffer { private final ByteBuffer buffer; private CleanableDirectBufferImpl(ByteBuffer buffer) { this.buffer = buffer; } @Override public ByteBuffer buffer() { return buffer; } @Override public void clean() { freeDirectBufferStatic(buffer); } } }
CleanableDirectBufferImpl
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxPeekFuseable.java
{ "start": 2941, "end": 9507 }
class ____<T> implements InnerOperator<T, T>, QueueSubscription<T> { final CoreSubscriber<? super T> actual; final SignalPeek<T> parent; @SuppressWarnings("NotNullFieldNotInitialized") // initialized in onSubscribe QueueSubscription<T> s; int sourceMode; volatile boolean done; @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.PARENT) return s; if (key == Attr.TERMINATED) return done; if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return InnerOperator.super.scanUnsafe(key); } PeekFuseableSubscriber(CoreSubscriber<? super T> actual, SignalPeek<T> parent) { this.actual = actual; this.parent = parent; } @Override public Context currentContext() { Context c = actual.currentContext(); final Consumer<? super Context> contextHook = parent.onCurrentContextCall(); if(!c.isEmpty() && contextHook != null) { contextHook.accept(c); } return c; } @Override public void request(long n) { final LongConsumer requestHook = parent.onRequestCall(); if (requestHook != null) { try { requestHook.accept(n); } catch (Throwable e) { Operators.onOperatorError(e, actual.currentContext()); } } s.request(n); } @Override public void cancel() { final Runnable cancelHook = parent.onCancelCall(); if (cancelHook != null) { try { cancelHook.run(); } catch (Throwable e) { onError(Operators.onOperatorError(s, e, actual.currentContext())); return; } } s.cancel(); } @SuppressWarnings("unchecked") @Override public void onSubscribe(Subscription s) { if(Operators.validate(this.s, s)) { final Consumer<? super Subscription> subscribeHook = parent.onSubscribeCall(); if (subscribeHook != null) { try { subscribeHook.accept(s); } catch (Throwable e) { Operators.error(actual, Operators.onOperatorError(s, e, actual.currentContext())); return; } } this.s = (QueueSubscription<T>) s; actual.onSubscribe(this); } } @SuppressWarnings("DataFlowIssue") // fusion passes nulls via onNext @Override public void onNext(T t) { if (sourceMode == ASYNC) { actual.onNext(null); } else { if (done) { Operators.onNextDropped(t, actual.currentContext()); return; } final Consumer<? super T> nextHook = parent.onNextCall(); if (nextHook != null) { try { nextHook.accept(t); } catch (Throwable e) { Throwable e_ = Operators.onNextError(t, e, actual.currentContext(), s); if (e_ == null) { request(1); return; } else { onError(e_); return; } } } actual.onNext(t); } } @Override public void onError(Throwable t) { if (done) { Operators.onErrorDropped(t, actual.currentContext()); return; } done = true; final Consumer<? super Throwable> errorHook = parent.onErrorCall(); if (errorHook != null) { Exceptions.throwIfFatal(t); try { errorHook.accept(t); } catch (Throwable e) { //this performs a throwIfFatal or suppresses t in e t = Operators.onOperatorError(null, e, t, actual.currentContext()); } } try { actual.onError(t); } catch (UnsupportedOperationException use) { if (errorHook == null || !Exceptions.isErrorCallbackNotImplemented(use) && use.getCause() != t) { throw use; } } final Runnable afterTerminateHook = parent.onAfterTerminateCall(); if (afterTerminateHook != null) { try { afterTerminateHook.run(); } catch (Throwable e) { FluxPeek.afterErrorWithFailure(parent, e, t, actual.currentContext()); } } } @Override public void onComplete() { if (done) { return; } if (sourceMode == ASYNC) { done = true; actual.onComplete(); } else { final Runnable completeHook = parent.onCompleteCall(); if (completeHook != null) { try { completeHook.run(); } catch (Throwable e) { onError(Operators.onOperatorError(s, e, actual.currentContext())); return; } } done = true; actual.onComplete(); final Runnable afterTerminateHook = parent.onAfterTerminateCall(); if (afterTerminateHook != null) { try { afterTerminateHook.run(); } catch (Throwable e) { FluxPeek.afterCompleteWithFailure(parent, e, actual.currentContext()); } } } } @Override public CoreSubscriber<? super T> actual() { return actual; } @Override public @Nullable T poll() { boolean d = done; T v; try { v = s.poll(); } catch (Throwable e) { final Consumer<? super Throwable> errorHook = parent.onErrorCall(); if (errorHook != null) { try { errorHook.accept(e); } catch (Throwable errorCallbackError) { throw Exceptions.propagate(Operators.onOperatorError(s, errorCallbackError, e, actual.currentContext())); } } Runnable afterTerminateHook = parent.onAfterTerminateCall(); if (afterTerminateHook != null) { try { afterTerminateHook.run(); } catch (Throwable afterTerminateCallbackError) { throw Exceptions.propagate(Operators.onOperatorError(s, afterTerminateCallbackError, e, actual.currentContext())); } } throw Exceptions.propagate(Operators.onOperatorError(s, e, actual.currentContext())); } final Consumer<? super T> nextHook = parent.onNextCall(); if (v != null && nextHook != null) { try { nextHook.accept(v); } catch (Throwable e) { Throwable e_ = Operators.onNextError(v, e, actual.currentContext(), s); if (e_ == null) { return poll(); } else { throw Exceptions.propagate(e_); } } } if (v == null && (d || sourceMode == SYNC)) { Runnable call = parent.onCompleteCall(); if (call != null) { call.run(); } call = parent.onAfterTerminateCall(); if (call != null) { call.run(); } } return v; } @Override public boolean isEmpty() { return s.isEmpty(); } @Override public void clear() { s.clear(); } @Override public int requestFusion(int requestedMode) { int m; if ((requestedMode & Fuseable.THREAD_BARRIER) != 0) { return Fuseable.NONE; } else { m = s.requestFusion(requestedMode); } sourceMode = m; return m; } @Override public int size() { return s.size(); } } static final
PeekFuseableSubscriber
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/log/LogFilterTest3.java
{ "start": 263, "end": 1180 }
class ____ extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { System.setProperty("druid.log.stmt.executableSql", "true"); dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:derby:classpath:petstore-db"); dataSource.setFilters("log4j,slf4j"); } public void test_select() throws Exception { Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM ITEM WHERE LISTPRICE > ?"); stmt.setInt(1, 10); for (int i = 0; i < 10; ++i) { ResultSet rs = stmt.executeQuery(); rs.close(); } stmt.close(); conn.close(); } protected void tearDown() throws Exception { JdbcUtils.close(dataSource); System.clearProperty("druid.log.stmt.executableSql"); } }
LogFilterTest3
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/completable/CompletableAmb.java
{ "start": 3399, "end": 4474 }
class ____ implements CompletableObserver { final AtomicBoolean once; final CompositeDisposable set; final CompletableObserver downstream; Disposable upstream; Amb(AtomicBoolean once, CompositeDisposable set, CompletableObserver observer) { this.once = once; this.set = set; this.downstream = observer; } @Override public void onComplete() { if (once.compareAndSet(false, true)) { set.delete(upstream); set.dispose(); downstream.onComplete(); } } @Override public void onError(Throwable e) { if (once.compareAndSet(false, true)) { set.delete(upstream); set.dispose(); downstream.onError(e); } else { RxJavaPlugins.onError(e); } } @Override public void onSubscribe(Disposable d) { upstream = d; set.add(d); } } }
Amb
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/SessionFactoryObserverTest.java
{ "start": 697, "end": 1359 }
class ____ { @Test public void testSessionFactoryObserverProperty() { Map<String, Object> settings = ServiceRegistryUtil.createBaseSettings(); settings.put( AvailableSettings.SESSION_FACTORY_OBSERVER, GoofySessionFactoryObserver.class.getName() ); EntityManagerFactoryBuilder builder = Bootstrap.getEntityManagerFactoryBuilder( new PersistenceUnitInfoAdapter(), settings ); try { final EntityManagerFactory entityManagerFactory = builder.build(); entityManagerFactory.close(); Assertions.fail( "GoofyException should have been thrown" ); } catch ( GoofyException e ) { //success } } public static
SessionFactoryObserverTest
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/service/GetServiceAccountAction.java
{ "start": 369, "end": 697 }
class ____ extends ActionType<GetServiceAccountResponse> { public static final String NAME = "cluster:admin/xpack/security/service_account/get"; public static final GetServiceAccountAction INSTANCE = new GetServiceAccountAction(); public GetServiceAccountAction() { super(NAME); } }
GetServiceAccountAction
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/ProgrammaticExtensionRegistrationTests.java
{ "start": 20452, "end": 20643 }
class ____ extends AbstractTestCase { @RegisterExtension Extension field = new ExplosiveExtension(new RuntimeException("boom")); } static
InstanceLevelExplosiveUncheckedExceptionTestCase
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/cluster/RedisReactiveClusterClientIntegrationTests.java
{ "start": 885, "end": 3849 }
class ____ extends TestSupport { private final RedisAdvancedClusterCommands<String, String> sync; private final RedisAdvancedClusterReactiveCommands<String, String> reactive; @Inject RedisReactiveClusterClientIntegrationTests(StatefulRedisClusterConnection<String, String> connection) { this.sync = connection.sync(); this.reactive = connection.reactive(); } @Test void testClusterCommandRedirection() { // Command on node within the default connection StepVerifier.create(reactive.set(ClusterTestSettings.KEY_B, "myValue1")).expectNext("OK").verifyComplete(); // gets redirection to node 3 StepVerifier.create(reactive.set(ClusterTestSettings.KEY_A, "myValue1")).expectNext("OK").verifyComplete(); } @Test void getKeysInSlot() { sync.flushall(); sync.set(ClusterTestSettings.KEY_A, value); sync.set(ClusterTestSettings.KEY_B, value); StepVerifier.create(reactive.clusterGetKeysInSlot(ClusterTestSettings.SLOT_A, 10)).expectNext(ClusterTestSettings.KEY_A) .verifyComplete(); StepVerifier.create(reactive.clusterGetKeysInSlot(ClusterTestSettings.SLOT_B, 10)).expectNext(ClusterTestSettings.KEY_B) .verifyComplete(); } @Test void countKeysInSlot() { sync.flushall(); sync.set(ClusterTestSettings.KEY_A, value); sync.set(ClusterTestSettings.KEY_B, value); StepVerifier.create(reactive.clusterCountKeysInSlot(ClusterTestSettings.SLOT_A)).expectNext(1L).verifyComplete(); StepVerifier.create(reactive.clusterCountKeysInSlot(ClusterTestSettings.SLOT_B)).expectNext(1L).verifyComplete(); int slotZZZ = SlotHash.getSlot("ZZZ".getBytes()); StepVerifier.create(reactive.clusterCountKeysInSlot(slotZZZ)).expectNext(0L).verifyComplete(); } @Test void testClusterCountFailureReports() { RedisClusterNode ownPartition = getOwnPartition(sync); StepVerifier.create(reactive.clusterCountFailureReports(ownPartition.getNodeId())).consumeNextWith(actual -> { assertThat(actual).isGreaterThanOrEqualTo(0); }).verifyComplete(); } @Test void testClusterKeyslot() { StepVerifier.create(reactive.clusterKeyslot(ClusterTestSettings.KEY_A)).expectNext((long) ClusterTestSettings.SLOT_A) .verifyComplete(); assertThat(SlotHash.getSlot(ClusterTestSettings.KEY_A)).isEqualTo(ClusterTestSettings.SLOT_A); } @Test void testClusterSaveconfig() { StepVerifier.create(reactive.clusterSaveconfig()).expectNext("OK").verifyComplete(); } @Test void testClusterSetConfigEpoch() { StepVerifier.create(reactive.clusterSetConfigEpoch(1L)).consumeErrorWith(e -> { assertThat(e).hasMessageContaining("ERR The user can assign a config epoch only"); }).verify(); } }
RedisReactiveClusterClientIntegrationTests
java
apache__spark
core/src/main/java/org/apache/spark/util/collection/unsafe/sort/UnsafeExternalSorter.java
{ "start": 24057, "end": 31602 }
class ____ extends UnsafeSorterIterator { private UnsafeSorterIterator upstream; private MemoryBlock lastPage = null; private boolean loaded = false; private int numRecords; private Object currentBaseObject; private long currentBaseOffset; private int currentRecordLength; private long currentKeyPrefix; SpillableIterator(UnsafeSorterIterator inMemIterator) { this.upstream = inMemIterator; this.numRecords = inMemIterator.getNumRecords(); } @Override public int getNumRecords() { return numRecords; } @Override public long getCurrentPageNumber() { throw new UnsupportedOperationException(); } public long spill() throws IOException { UnsafeInMemorySorter inMemSorterToFree = null; List<MemoryBlock> pagesToFree = new LinkedList<>(); try { synchronized (this) { if (inMemSorter == null) { return 0L; } long currentPageNumber = upstream.getCurrentPageNumber(); ShuffleWriteMetrics writeMetrics = new ShuffleWriteMetrics(); if (numRecords > 0) { // Iterate over the records that have not been returned and spill them. final UnsafeSorterSpillWriter spillWriter = new UnsafeSorterSpillWriter( blockManager, fileBufferSizeBytes, writeMetrics, numRecords); spillIterator(upstream, spillWriter); spillWriters.add(spillWriter); upstream = spillWriter.getReader(serializerManager); } else { // Nothing to spill as all records have been read already, but do not return yet, as the // memory still has to be freed. upstream = null; } long released = 0L; synchronized (UnsafeExternalSorter.this) { // release the pages except the one that is used. There can still be a caller that // is accessing the current record. We free this page in that caller's next loadNext() // call. for (MemoryBlock page : allocatedPages) { if (!loaded || page.pageNumber != currentPageNumber) { released += page.size(); // Do not free the page, while we are locking `SpillableIterator`. The `freePage` // method locks the `TaskMemoryManager`, and it's not a good idea to lock 2 objects // in sequence. We may hit dead lock if another thread locks `TaskMemoryManager` // and `SpillableIterator` in sequence, which may happen in // `TaskMemoryManager.acquireExecutionMemory`. pagesToFree.add(page); } else { lastPage = page; } } allocatedPages.clear(); if (lastPage != null) { // Add the last page back to the list of allocated pages to make sure it gets freed in // case loadNext() never gets called again. allocatedPages.add(lastPage); } } // in-memory sorter will not be used after spilling assert (inMemSorter != null); released += inMemSorter.getMemoryUsage(); totalSortTimeNanos += inMemSorter.getSortTimeNanos(); // Do not free the sorter while we are locking `SpillableIterator`, // as this can cause a deadlock. inMemSorterToFree = inMemSorter; inMemSorter = null; taskContext.taskMetrics().incMemoryBytesSpilled(released); taskContext.taskMetrics().incDiskBytesSpilled(writeMetrics.bytesWritten()); totalSpillBytes += released; return released; } } finally { for (MemoryBlock pageToFree : pagesToFree) { freePage(pageToFree); } if (inMemSorterToFree != null) { inMemSorterToFree.freeMemory(); } } } @Override public boolean hasNext() { return numRecords > 0; } @Override public void loadNext() throws IOException { assert upstream != null; MemoryBlock pageToFree = null; try { synchronized (this) { loaded = true; // Just consumed the last record from the in-memory iterator. if (lastPage != null) { // Do not free the page here, while we are locking `SpillableIterator`. The `freePage` // method locks the `TaskMemoryManager`, and it's a bad idea to lock 2 objects in // sequence. We may hit dead lock if another thread locks `TaskMemoryManager` and // `SpillableIterator` in sequence, which may happen in // `TaskMemoryManager.acquireExecutionMemory`. pageToFree = lastPage; allocatedPages.clear(); lastPage = null; } numRecords--; upstream.loadNext(); // Keep track of the current base object, base offset, record length, and key prefix, // so that the current record can still be read in case a spill is triggered and we // switch to the spill writer's iterator. currentBaseObject = upstream.getBaseObject(); currentBaseOffset = upstream.getBaseOffset(); currentRecordLength = upstream.getRecordLength(); currentKeyPrefix = upstream.getKeyPrefix(); } } finally { if (pageToFree != null) { freePage(pageToFree); } } } @Override public Object getBaseObject() { return currentBaseObject; } @Override public long getBaseOffset() { return currentBaseOffset; } @Override public int getRecordLength() { return currentRecordLength; } @Override public long getKeyPrefix() { return currentKeyPrefix; } } /** * Returns an iterator starts from startIndex, which will return the rows in the order as * inserted. * * It is the caller's responsibility to call `cleanupResources()` * after consuming this iterator. * * TODO: support forced spilling */ public UnsafeSorterIterator getIterator(int startIndex) throws IOException { if (spillWriters.isEmpty()) { assert(inMemSorter != null); UnsafeSorterIterator iter = inMemSorter.getSortedIterator(); moveOver(iter, startIndex); return iter; } else { LinkedList<UnsafeSorterIterator> queue = new LinkedList<>(); int i = 0; for (UnsafeSorterSpillWriter spillWriter : spillWriters) { if (i + spillWriter.recordsSpilled() > startIndex) { UnsafeSorterIterator iter = spillWriter.getReader(serializerManager); moveOver(iter, startIndex - i); queue.add(iter); } i += spillWriter.recordsSpilled(); } if (inMemSorter != null && inMemSorter.numRecords() > 0) { UnsafeSorterIterator iter = inMemSorter.getSortedIterator(); moveOver(iter, startIndex - i); queue.add(iter); } return new ChainedIterator(queue); } } private void moveOver(UnsafeSorterIterator iter, int steps) throws IOException { if (steps > 0) { for (int i = 0; i < steps; i++) { if (iter.hasNext()) { iter.loadNext(); } else { throw new ArrayIndexOutOfBoundsException("Failed to move the iterator " + steps + " steps forward"); } } } } /** * Chain multiple UnsafeSorterIterator together as single one. */ static
SpillableIterator
java
quarkusio__quarkus
devtools/gradle/gradle-model/src/main/java/io/quarkus/gradle/tooling/DefaultProjectDescriptor.java
{ "start": 186, "end": 1012 }
class ____ implements Serializable, ProjectDescriptor { private static final long serialVersionUID = 1L; private WorkspaceModule.Mutable module; public DefaultProjectDescriptor(WorkspaceModule.Mutable module) { this.module = module; } @Override public WorkspaceModule.Mutable getWorkspaceModule() { return module; } public void setWorkspaceModule(WorkspaceModule.Mutable module) { this.module = module; } @Override public WorkspaceModule.Mutable getWorkspaceModuleOrNull(WorkspaceModuleId moduleId) { return module.getId().equals(moduleId) ? module : null; } @Override public String toString() { return "DefaultProjectDescriptor{" + "\nmodule=" + module + "\n}"; } }
DefaultProjectDescriptor
java
quarkusio__quarkus
devtools/maven/src/test/java/io/quarkus/maven/ConditionalDependencyTreeMojoTest.java
{ "start": 135, "end": 1489 }
class ____ extends DependencyTreeMojoTestBase { @Override protected String mode() { return "prod"; } @Override protected void initRepo() { final TsQuarkusExt coreExt = new TsQuarkusExt("test-core-ext"); var tomatoExt = new TsQuarkusExt("quarkus-tomato").addDependency(coreExt); var mozzarellaExt = new TsQuarkusExt("quarkus-mozzarella").addDependency(coreExt); var basilExt = new TsQuarkusExt("quarkus-basil").addDependency(coreExt); var oilJar = TsArtifact.jar("quarkus-oil"); var capreseExt = new TsQuarkusExt("quarkus-caprese") .setDependencyCondition(tomatoExt, mozzarellaExt, basilExt) .addDependency(coreExt); capreseExt.getDeployment().addDependency(oilJar); capreseExt.install(repoBuilder); var saladExt = new TsQuarkusExt("quarkus-salad") .setConditionalDeps(capreseExt) .addDependency(coreExt); app = TsArtifact.jar("app-with-conditional-deps") .addDependency(tomatoExt) .addDependency(mozzarellaExt) .addDependency(basilExt) .addDependency(saladExt) .addDependency(oilJar); appModel = app.getPomModel(); app.install(repoBuilder); } }
ConditionalDependencyTreeMojoTest
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/ltr/LearningToRankRescorerBuilderRewriteTests.java
{ "start": 2629, "end": 13216 }
class ____ extends AbstractBuilderTestCase { public void testMustRewrite() { LearningToRankService learningToRankService = learningToRankServiceMock(); LearningToRankRescorerBuilder rescorerBuilder = new LearningToRankRescorerBuilder( GOOD_MODEL, randomLearningToRankConfig(), null, learningToRankService ); SearchExecutionContext context = createSearchExecutionContext(); LearningToRankRescorerContext rescorerContext = rescorerBuilder.innerBuildContext(randomIntBetween(1, 30), context); IllegalStateException e = expectThrows( IllegalStateException.class, () -> rescorerContext.rescorer() .rescore( new TopDocs(new TotalHits(10, TotalHits.Relation.EQUAL_TO), new ScoreDoc[10]), mock(IndexSearcher.class), rescorerContext ) ); assertEquals("local model reference is null, missing rewriteAndFetch before rescore phase?", e.getMessage()); } public void testRewriteOnCoordinator() throws IOException { LearningToRankService learningToRankService = learningToRankServiceMock(); LearningToRankRescorerBuilder rescorerBuilder = new LearningToRankRescorerBuilder(GOOD_MODEL, null, learningToRankService); rescorerBuilder.windowSize(4); CoordinatorRewriteContext context = createCoordinatorRewriteContext( new DateFieldMapper.DateFieldType("@timestamp"), randomIntBetween(0, 1_100_000), randomIntBetween(1_500_000, Integer.MAX_VALUE) ); LearningToRankRescorerBuilder rewritten = rewriteAndFetch(rescorerBuilder, context); assertThat(rewritten.learningToRankConfig(), not(nullValue())); assertThat(rewritten.learningToRankConfig().getNumTopFeatureImportanceValues(), equalTo(2)); assertThat( "feature_1", is( in( rewritten.learningToRankConfig() .getFeatureExtractorBuilders() .stream() .map(LearningToRankFeatureExtractorBuilder::featureName) .toList() ) ) ); assertThat(rewritten.windowSize(), equalTo(4)); } public void testRewriteOnCoordinatorWithBadModel() throws IOException { LearningToRankService learningToRankService = learningToRankServiceMock(); LearningToRankRescorerBuilder rescorerBuilder = new LearningToRankRescorerBuilder(BAD_MODEL, null, learningToRankService); CoordinatorRewriteContext context = createCoordinatorRewriteContext( new DateFieldMapper.DateFieldType("@timestamp"), randomIntBetween(0, 1_100_000), randomIntBetween(1_500_000, Integer.MAX_VALUE) ); ElasticsearchStatusException ex = expectThrows(ElasticsearchStatusException.class, () -> rewriteAndFetch(rescorerBuilder, context)); assertThat(ex.status(), equalTo(RestStatus.BAD_REQUEST)); } public void testRewriteOnCoordinatorWithMissingModel() { LearningToRankService learningToRankService = learningToRankServiceMock(); LearningToRankRescorerBuilder rescorerBuilder = new LearningToRankRescorerBuilder("missing_model", null, learningToRankService); CoordinatorRewriteContext context = createCoordinatorRewriteContext( new DateFieldMapper.DateFieldType("@timestamp"), randomIntBetween(0, 1_100_000), randomIntBetween(1_500_000, Integer.MAX_VALUE) ); expectThrows(ResourceNotFoundException.class, () -> rewriteAndFetch(rescorerBuilder, context)); } public void testRewriteOnShard() throws IOException { LocalModel localModel = mock(LocalModel.class); when(localModel.getModelId()).thenReturn(GOOD_MODEL); LearningToRankService learningToRankService = learningToRankServiceMock(); LearningToRankRescorerBuilder rescorerBuilder = new LearningToRankRescorerBuilder( localModel, (LearningToRankConfig) GOOD_MODEL_CONFIG.getInferenceConfig(), null, learningToRankService ); SearchExecutionContext searchExecutionContext = createSearchExecutionContext(); LearningToRankRescorerBuilder rewritten = (LearningToRankRescorerBuilder) rescorerBuilder.rewrite(createSearchExecutionContext()); assertFalse(searchExecutionContext.hasAsyncActions()); assertSame(localModel, rewritten.localModel()); assertEquals(localModel.getModelId(), rewritten.modelId()); } public void testRewriteAndFetchOnDataNode() throws IOException { LearningToRankService learningToRankService = learningToRankServiceMock(); LearningToRankRescorerBuilder rescorerBuilder = new LearningToRankRescorerBuilder( GOOD_MODEL, randomLearningToRankConfig(), null, learningToRankService ); boolean setWindowSize = randomBoolean(); if (setWindowSize) { rescorerBuilder.windowSize(42); } DataRewriteContext rewriteContext = dataRewriteContext(); LearningToRankRescorerBuilder rewritten = (LearningToRankRescorerBuilder) rescorerBuilder.rewrite(rewriteContext); assertNotSame(rescorerBuilder, rewritten); assertTrue(rewriteContext.hasAsyncActions()); if (setWindowSize) { assertThat(rewritten.windowSize(), equalTo(42)); } } @SuppressWarnings("unchecked") private static LearningToRankService learningToRankServiceMock() { LearningToRankService learningToRankService = mock(LearningToRankService.class); doAnswer(invocation -> { String modelId = invocation.getArgument(0); ActionListener<InferenceConfig> l = invocation.getArgument(2, ActionListener.class); if (modelId.equals(GOOD_MODEL)) { l.onResponse(GOOD_MODEL_CONFIG.getInferenceConfig()); } else if (modelId.equals(BAD_MODEL)) { l.onFailure(new ElasticsearchStatusException("bad model", RestStatus.BAD_REQUEST)); } else { l.onFailure(new ResourceNotFoundException("missing model")); } return null; }).when(learningToRankService).loadLearningToRankConfig(anyString(), any(), any()); doAnswer(invocation -> { ActionListener<LocalModel> l = invocation.getArgument(1, ActionListener.class); l.onResponse(mock(LocalModel.class)); return null; }).when(learningToRankService).loadLocalModel(anyString(), any()); return learningToRankService; } public void testBuildContext() throws Exception { LocalModel localModel = mock(LocalModel.class); when(localModel.inputFields()).thenReturn(GOOD_MODEL_CONFIG.getInput().getFieldNames()); IndexSearcher searcher = mock(IndexSearcher.class); doAnswer(invocation -> invocation.getArgument(0)).when(searcher).rewrite(any(Query.class)); SearchExecutionContext context = createSearchExecutionContext(searcher); LearningToRankRescorerBuilder rescorerBuilder = new LearningToRankRescorerBuilder( localModel, (LearningToRankConfig) GOOD_MODEL_CONFIG.getInferenceConfig(), null, mock(LearningToRankService.class) ); LearningToRankRescorerContext rescoreContext = rescorerBuilder.innerBuildContext(20, context); assertNotNull(rescoreContext); assertThat(rescoreContext.getWindowSize(), equalTo(20)); List<FeatureExtractor> featureExtractors = rescoreContext.buildFeatureExtractors(context.searcher()); assertThat(featureExtractors, hasSize(1)); FeatureExtractor queryExtractor = featureExtractors.get(0); assertThat(queryExtractor, instanceOf(QueryFeatureExtractor.class)); assertThat(queryExtractor.featureNames(), hasSize(2)); assertThat(queryExtractor.featureNames(), containsInAnyOrder("feature_1", "feature_2")); } public void testLegacyFieldValueExtractorBuildContext() throws Exception { // Models created before 8.15 have been saved with input fields. // We check field value extractors are created and the deduplication is done correctly. LocalModel localModel = mock(LocalModel.class); when(localModel.inputFields()).thenReturn(List.of("feature_1", "field_1", "field_2")); IndexSearcher searcher = mock(IndexSearcher.class); doAnswer(invocation -> invocation.getArgument(0)).when(searcher).rewrite(any(Query.class)); SearchExecutionContext context = createSearchExecutionContext(searcher); LearningToRankRescorerBuilder rescorerBuilder = new LearningToRankRescorerBuilder( localModel, (LearningToRankConfig) GOOD_MODEL_CONFIG.getInferenceConfig(), null, mock(LearningToRankService.class) ); LearningToRankRescorerContext rescoreContext = rescorerBuilder.innerBuildContext(20, context); assertNotNull(rescoreContext); assertThat(rescoreContext.getWindowSize(), equalTo(20)); List<FeatureExtractor> featureExtractors = rescoreContext.buildFeatureExtractors(context.searcher()); assertThat(featureExtractors, hasSize(2)); FeatureExtractor queryExtractor = featureExtractors.stream().filter(fe -> fe instanceof QueryFeatureExtractor).findFirst().get(); assertThat(queryExtractor.featureNames(), hasSize(2)); assertThat(queryExtractor.featureNames(), containsInAnyOrder("feature_1", "feature_2")); FeatureExtractor fieldValueExtractor = featureExtractors.stream() .filter(fe -> fe instanceof FieldValueFeatureExtractor) .findFirst() .get(); assertThat(fieldValueExtractor.featureNames(), hasSize(2)); assertThat(fieldValueExtractor.featureNames(), containsInAnyOrder("field_1", "field_2")); } private LearningToRankRescorerBuilder rewriteAndFetch( RescorerBuilder<LearningToRankRescorerBuilder> builder, QueryRewriteContext context ) { PlainActionFuture<RescorerBuilder<LearningToRankRescorerBuilder>> future = new PlainActionFuture<>(); Rewriteable.rewriteAndFetch(builder, context, future); return (LearningToRankRescorerBuilder) future.actionGet(); } }
LearningToRankRescorerBuilderRewriteTests
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/TestTypeNames.java
{ "start": 6142, "end": 6279 }
class ____ extends Cat { public Persian() { super(); } protected Persian(String n, boolean p) { super(n, p); } }
Persian
java
google__dagger
javatests/dagger/functional/producers/ProvidesInProducerTest.java
{ "start": 1291, "end": 1388 }
interface ____ { ListenableFuture<String> string(); } @ProducerModule static
TestComponent
java
apache__flink
flink-table/flink-table-api-java-bridge/src/main/java/org/apache/flink/connector/datagen/table/DataGenConnectorOptions.java
{ "start": 2180, "end": 6974 }
class ____ { public static final ConfigOption<Long> ROWS_PER_SECOND = ConfigOptions.key("rows-per-second") .longType() .defaultValue(ROWS_PER_SECOND_DEFAULT_VALUE) .withDescription("Rows per second to control the emit rate."); public static final ConfigOption<Long> NUMBER_OF_ROWS = ConfigOptions.key("number-of-rows") .longType() .noDefaultValue() .withDescription( "Total number of rows to emit. By default, the source is unbounded."); public static final ConfigOption<Integer> SOURCE_PARALLELISM = FactoryUtil.SOURCE_PARALLELISM; // -------------------------------------------------------------------------------------------- // Placeholder options // -------------------------------------------------------------------------------------------- /** Placeholder {@link ConfigOption}. Not used for retrieving values. */ public static final ConfigOption<String> FIELD_KIND = ConfigOptions.key(String.format("%s.#.%s", FIELDS, KIND)) .stringType() .defaultValue("random") .withDescription("Generator of this '#' field. Can be 'sequence' or 'random'."); /** Placeholder {@link ConfigOption}. Not used for retrieving values. */ public static final ConfigOption<String> FIELD_MIN = ConfigOptions.key(String.format("%s.#.%s", FIELDS, MIN)) .stringType() .noDefaultValue() .withDescription( "Minimum value to generate for fields of kind 'random'. Minimum value possible for the type of the field."); /** Placeholder {@link ConfigOption}. Not used for retrieving values. */ public static final ConfigOption<String> FIELD_MAX = ConfigOptions.key(String.format("%s.#.%s", FIELDS, MAX)) .stringType() .noDefaultValue() .withDescription( "Maximum value to generate for fields of kind 'random'. Maximum value possible for the type of the field."); /** Placeholder {@link ConfigOption}. Not used for retrieving values. */ public static final ConfigOption<Duration> FIELD_MAX_PAST = ConfigOptions.key(String.format("%s.#.%s", FIELDS, MAX_PAST)) .durationType() .noDefaultValue() .withDescription( "Maximum past relative to the current timestamp of the local machine to generate for timestamp fields of kind 'random'."); /** Placeholder {@link ConfigOption}. Not used for retrieving values. */ public static final ConfigOption<Integer> FIELD_LENGTH = ConfigOptions.key(String.format("%s.#.%s", FIELDS, LENGTH)) .intType() .defaultValue(100) .withDescription( "Size or length of the collection for generating char/varchar/string/array/map/multiset types."); /** Placeholder {@link ConfigOption}. Not used for retrieving values. */ public static final ConfigOption<String> FIELD_START = ConfigOptions.key(String.format("%s.#.%s", FIELDS, START)) .stringType() .noDefaultValue() .withDescription("Start value of sequence generator."); /** Placeholder {@link ConfigOption}. Not used for retrieving values. */ public static final ConfigOption<String> FIELD_END = ConfigOptions.key(String.format("%s.#.%s", FIELDS, END)) .stringType() .noDefaultValue() .withDescription("End value of sequence generator."); /** Placeholder {@link ConfigOption}. Not used for retrieving values. */ public static final ConfigOption<Float> FIELD_NULL_RATE = ConfigOptions.key(String.format("%s.#.%s", FIELDS, NULL_RATE)) .floatType() .defaultValue(0f) .withDescription("The proportion of null values."); /** Placeholder {@link ConfigOption}. Not used for retrieving values. */ public static final ConfigOption<Boolean> FIELD_VAR_LEN = ConfigOptions.key(String.format("%s.#.%s", FIELDS, VAR_LEN)) .booleanType() .defaultValue(false) .withDescription( "Whether to generate a variable-length data, please notice that it should only be used for variable-length types (varchar, string, varbinary, bytes)."); private DataGenConnectorOptions() {} }
DataGenConnectorOptions
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/NodeFencer.java
{ "start": 6749, "end": 7130 }
interface ____ (!FenceMethod.class.isAssignableFrom(clazz)) { throw new BadFencingConfigurationException("Class " + clazzName + " does not implement FenceMethod"); } FenceMethod method = (FenceMethod)ReflectionUtils.newInstance( clazz, conf); method.checkArgs(arg); return new FenceMethodWithArg(method, arg); } private static
if
java
google__guava
android/guava-tests/test/com/google/common/util/concurrent/JdkFutureAdaptersTest.java
{ "start": 8135, "end": 10039 }
class ____ implements Runnable { final CountDownLatch wasRun = new CountDownLatch(1); // synchronized so that checkState works as expected. @Override public synchronized void run() { checkState(wasRun.getCount() > 0); wasRun.countDown(); } } public void testListenInPoolThreadRunsListenerAfterRuntimeException() throws Exception { RuntimeExceptionThrowingFuture<String> input = new RuntimeExceptionThrowingFuture<>(); /* * RuntimeExceptionThrowingFuture is provably not a ListenableFuture at compile time, so this * code may someday upset Error Prone. We want the test, though, in case that changes in the * future, so we will suppress any such future Error Prone reports. */ assertWithMessage( "Can't test the main listenInPoolThread path " + "if the input is already a ListenableFuture") .that(input) .isNotInstanceOf(ListenableFuture.class); ListenableFuture<String> listenable = listenInPoolThread(input); /* * This will occur before the waiting get() in the * listenInPoolThread-spawned thread completes: */ RecordingRunnable earlyListener = new RecordingRunnable(); listenable.addListener(earlyListener, directExecutor()); input.allowGetToComplete.countDown(); // Now give the get() thread time to finish: assertTrue(earlyListener.wasRun.await(1, SECONDS)); // Now test an additional addListener call, which will be run in-thread: RecordingRunnable lateListener = new RecordingRunnable(); listenable.addListener(lateListener, directExecutor()); assertTrue(lateListener.wasRun.await(1, SECONDS)); } public void testAdapters_nullChecks() throws Exception { new ClassSanityTester() .forAllPublicStaticMethods(JdkFutureAdapters.class) .thatReturn(Future.class) .testNulls(); } }
RecordingRunnable
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/RecipientListDirectNoConsumerIssueTest.java
{ "start": 1039, "end": 2789 }
class ____ extends ContextTestSupport { @Test public void testDirectNoConsumerOneMessage() throws Exception { getMockEndpoint("mock:error").expectedMinimumMessageCount(1); getMockEndpoint("mock:foo").expectedMinimumMessageCount(1); template.sendBodyAndHeader("direct:start", "Hello World", "foo", "mock:foo;direct:foo"); assertMockEndpointsSatisfied(); } @Test public void testDirectNoConsumerTwoMessages() throws Exception { getMockEndpoint("mock:error").expectedMinimumMessageCount(1); getMockEndpoint("mock:foo").expectedMinimumMessageCount(1); template.sendBodyAndHeader("direct:start", "Hello World", "foo", "mock:foo"); template.sendBodyAndHeader("direct:start", "Bye World", "foo", "direct:foo"); assertMockEndpointsSatisfied(); } @Test public void testDirectNoConsumerOneMessageBar() throws Exception { getMockEndpoint("mock:error").expectedMinimumMessageCount(1); getMockEndpoint("mock:foo").expectedMinimumMessageCount(1); template.sendBodyAndHeader("direct:bar", "Hello World", "bar", "mock:foo;direct:foo"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { context.getComponent("direct", DirectComponent.class).setBlock(false); onException(Exception.class).handled(true).to("mock:error"); from("direct:start").recipientList().header("foo").delimiter(";"); from("direct:bar").recipientList(";").header("bar"); } }; } }
RecipientListDirectNoConsumerIssueTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metadata/JoinedManyToOneOwner.java
{ "start": 458, "end": 985 }
class ____ { private Long id; private House house; private House house2; @Id public Long getId() { return id; } public void setId(Long id) { this.id = id; } @ManyToOne @JoinTable( name = "SOME_OTHER_TABLE" ) public House getHouse() { return house; } public void setHouse(House house) { this.house = house; } @ManyToOne @JoinColumn(name = "house2", nullable = false) public House getHouse2() { return house2; } public void setHouse2(House house2) { this.house2 = house2; } }
JoinedManyToOneOwner
java
apache__camel
components/camel-soap/src/main/java/org/apache/camel/dataformat/soap/name/ServiceInterfaceStrategy.java
{ "start": 1503, "end": 11028 }
class ____ implements ElementNameStrategy { private static final Logger LOG = LoggerFactory.getLogger(ServiceInterfaceStrategy.class); private Map<String, MethodInfo> soapActionToMethodInfo = new HashMap<>(); private Map<String, QName> inTypeNameToQName = new HashMap<>(); private Map<String, QName> outTypeNameToQName = new HashMap<>(); private boolean isClient; private ElementNameStrategy fallBackStrategy; private Map<String, Map<QName, Class<? extends Exception>>> faultNameToException = new HashMap<>(); /** * Init with JAX-WS service interface * * @param serviceInterface * @param isClient determines if marhalling looks at input or output of method */ public ServiceInterfaceStrategy(Class<?> serviceInterface, boolean isClient) { analyzeServiceInterface(serviceInterface); this.isClient = isClient; this.fallBackStrategy = new TypeNameStrategy(); } public String getMethodForSoapAction(String soapAction) { MethodInfo methodInfo = soapActionToMethodInfo.get(soapAction); return (methodInfo == null) ? null : methodInfo.getName(); } private TypeInfo getOutInfo(Method method) { ResponseWrapper respWrap = method.getAnnotation(ResponseWrapper.class); if (respWrap != null && respWrap.className() != null) { return new TypeInfo( respWrap.className(), new QName(respWrap.targetNamespace(), respWrap.localName())); } Class<?> returnType = method.getReturnType(); if (Void.TYPE.equals(returnType)) { return new TypeInfo(null, null); } else { Class<?> type = method.getReturnType(); WebResult webResult = method.getAnnotation(WebResult.class); if (webResult != null) { return new TypeInfo(type.getName(), new QName(webResult.targetNamespace(), webResult.name())); } else { throw new IllegalArgumentException( "Result type of method " + method.getName() + " is not annotated with WebResult. This is not yet supported"); } } } private List<TypeInfo> getInInfo(Method method) { List<TypeInfo> typeInfos = new ArrayList<>(); RequestWrapper requestWrapper = method.getAnnotation(RequestWrapper.class); // parameter types are returned in declaration order Class<?>[] types = method.getParameterTypes(); if (types.length == 0) { return typeInfos; } if (requestWrapper != null && requestWrapper.className() != null) { typeInfos.add(new TypeInfo( requestWrapper.className(), new QName(requestWrapper.targetNamespace(), requestWrapper.localName()))); return typeInfos; } // annotations are returned in declaration order Annotation[][] annotations = method.getParameterAnnotations(); List<WebParam> webParams = new ArrayList<>(); for (Annotation[] singleParameterAnnotations : annotations) { for (Annotation annotation : singleParameterAnnotations) { if (annotation instanceof WebParam) { webParams.add((WebParam) annotation); } } } if (webParams.size() != types.length) { throw new IllegalArgumentException( "The number of @WebParam annotations for Method " + method.getName() + " does not match the number of parameters. This is not supported."); } Iterator<WebParam> webParamIter = webParams.iterator(); int paramCounter = -1; while (webParamIter.hasNext()) { WebParam webParam = webParamIter.next(); typeInfos.add(new TypeInfo( types[++paramCounter].getName(), new QName(webParam.targetNamespace(), webParam.name()))); } return typeInfos; } /** * Determines how the parameter object of the service method will be named in xml. It will use either the * RequestWrapper annotation of the method if present or the WebParam method of the parameter. * * @param method */ private MethodInfo analyzeMethod(Method method) { List<TypeInfo> inInfos = getInInfo(method); TypeInfo outInfo = getOutInfo(method); WebMethod webMethod = method.getAnnotation(WebMethod.class); String soapAction = (webMethod != null) ? webMethod.action() : null; return new MethodInfo( method.getName(), soapAction, inInfos.toArray(new TypeInfo[0]), outInfo); } private void analyzeServiceInterface(Class<?> serviceInterface) { Method[] methods = serviceInterface.getMethods(); for (Method method : methods) { MethodInfo info = analyzeMethod(method); for (int i = 0; i < info.getIn().length; i++) { TypeInfo ti = info.getIn()[i]; if (inTypeNameToQName.containsKey(ti.getTypeName())) { if (ti.getTypeName() != null) { if (!ti.getTypeName().equals("jakarta.xml.ws.Holder") && !inTypeNameToQName.get(ti.getTypeName()).equals(ti.getElName())) { LOG.warn("Ambiguous QName mapping. The type [{}] is already mapped to a QName in this context.", ti.getTypeName()); continue; } } } inTypeNameToQName.put(ti.getTypeName(), ti.getElName()); } String soapAction = info.getSoapAction(); if (soapAction != null && !soapAction.isEmpty()) { soapActionToMethodInfo.put(soapAction, info); addExceptions(soapAction, method); } else { addExceptions(null, method); } outTypeNameToQName.put(info.getOut().getTypeName(), info.getOut().getElName()); } } @SuppressWarnings("unchecked") private void addExceptions(String soapAction, Method method) { Class<?>[] exTypes = method.getExceptionTypes(); for (Class<?> exType : exTypes) { WebFault webFault = exType.getAnnotation(WebFault.class); if (webFault != null) { QName faultName = new QName(webFault.targetNamespace(), webFault.name()); faultNameToException.putIfAbsent(soapAction, new HashMap<>()); Map<QName, Class<? extends Exception>> soapActionFaultNameMap = faultNameToException.get(soapAction); soapActionFaultNameMap.put(faultName, (Class<? extends Exception>) exType); } } } /** * Determine the QName of the method parameter of the method that matches either soapAction and type or if not * possible only the type * * @param soapAction * @param type * @return matching QName throws RuntimeException if no matching QName was found */ @Override public QName findQNameForSoapActionOrType(String soapAction, Class<?> type) { MethodInfo info = soapActionToMethodInfo.get(soapAction); if (info != null) { if (isClient) { if (type != null) { return info.getIn(type.getName()).getElName(); } else { return null; } } else { return info.getOut().getElName(); } } QName qName = null; if (type != null) { if (isClient) { qName = inTypeNameToQName.get(type.getName()); } else { qName = outTypeNameToQName.get(type.getName()); } } if (qName == null) { try { qName = fallBackStrategy.findQNameForSoapActionOrType(soapAction, type); } catch (Exception e) { String msg = "No method found that matches the given SoapAction " + soapAction + " or that has an " + (isClient ? "input" : "output") + " of type " + type.getName(); throw new RuntimeCamelException(msg, e); } } return qName; } @Override public Class<? extends Exception> findExceptionForFaultName(QName faultName) { for (Map<QName, Class<? extends Exception>> perSoapActionFaultNameToException : faultNameToException.values()) { if (perSoapActionFaultNameToException.get(faultName) != null) { return perSoapActionFaultNameToException.get(faultName); } } return null; } @Override public Class<? extends Exception> findExceptionForSoapActionAndFaultName(String soapAction, QName faultName) { if (soapAction == null || soapAction.isEmpty()) { return findExceptionForFaultName(faultName); } Map<QName, Class<? extends Exception>> perSoapActionFaultNameToException = faultNameToException.get(soapAction); if (perSoapActionFaultNameToException == null) { return null; } return perSoapActionFaultNameToException.get(faultName); } }
ServiceInterfaceStrategy
java
quarkusio__quarkus
extensions/jdbc/jdbc-postgresql/runtime/src/main/java/io/quarkus/jdbc/postgresql/runtime/graal/DomHelper.java
{ "start": 822, "end": 3330 }
class ____ { // Stays null unless XML result processing becomes reachable. private BiFunction<DOMResult, BaseConnection, String> processDomResult; // This is only ever invoked if field domResult got initialized; which in turn // is only possible if setResult(Class) is reachable. public static String processDomResult(DOMResult domResult, BaseConnection conn) throws SQLException { BiFunction<DOMResult, BaseConnection, String> func = ImageSingletons.lookup(DomHelper.class).processDomResult; if (func == null) { return null; } else { try { return func.apply(domResult, conn); } catch (UncheckedSQLException e) { throw (SQLException) e.getCause(); } } } // Called by SQLXMLFeature when setResult(Class) becomes reachable static void enableXmlProcessing() { ImageSingletons.lookup(DomHelper.class).processDomResult = DomHelper::doProcessDomResult; } public static String doProcessDomResult(DOMResult domResult, BaseConnection conn) { try { return reallyProcessDomResult(domResult, conn); } catch (SQLException e) { throw new UncheckedSQLException(e); } } // This XML processing code should only be reachable (via processDomResult function) iff it's // actually used. I.e. setResult(Class) is reachable. public static String reallyProcessDomResult(DOMResult domResult, BaseConnection conn) throws SQLException { TransformerFactory factory = getXmlFactoryFactory(conn).newTransformerFactory(); try { Transformer transformer = factory.newTransformer(); DOMSource domSource = new DOMSource(domResult.getNode()); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); transformer.transform(domSource, streamResult); return stringWriter.toString(); } catch (TransformerException te) { throw new PSQLException(GT.tr("Unable to convert DOMResult SQLXML data to a string."), PSQLState.DATA_ERROR, te); } } private static PGXmlFactoryFactory getXmlFactoryFactory(BaseConnection conn) throws SQLException { if (conn != null) { return conn.getXmlFactoryFactory(); } return DefaultPGXmlFactoryFactory.INSTANCE; } } @SuppressWarnings("serial") final
DomHelper