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
FasterXML__jackson-core
src/test/java/tools/jackson/core/unittest/write/FastDoubleArrayGenerationTest.java
{ "start": 191, "end": 703 }
class ____ extends ArrayGenerationTest { private final JsonFactory FACTORY = streamFactoryBuilder() .enable(StreamWriteFeature.USE_FAST_DOUBLE_WRITER) // 17-Sep-2024, tatu: [core#223] change to surrogates, let's use old behavior // for now for simpler testing .disable(JsonWriteFeature.COMBINE_UNICODE_SURROGATES_IN_UTF8) .build(); @Override protected JsonFactory jsonFactory() { return FACTORY; } }
FastDoubleArrayGenerationTest
java
spring-projects__spring-boot
system-test/spring-boot-deployment-system-tests/src/main/java/sample/app/SampleController.java
{ "start": 793, "end": 892 }
class ____ { @GetMapping("/") public String hello() { return "Hello World"; } }
SampleController
java
quarkusio__quarkus
extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/graal/QuartzSubstitutions.java
{ "start": 290, "end": 700 }
class ____ { @Substitute private void bind() throws RemoteException { } @Substitute private void unBind() throws RemoteException { } @Substitute private void registerJMX() throws Exception { } @Substitute private void unregisterJMX() throws Exception { } } @TargetClass(className = "org.quartz.impl.RemoteScheduler") final
Target_org_quartz_core_QuartzScheduler
java
apache__flink
flink-core/src/test/java/org/apache/flink/util/FlinkUserCodeClassLoaderTest.java
{ "start": 1165, "end": 2005 }
class ____ { @Test void testExceptionHandling() { RuntimeException expectedException = new RuntimeException("Expected exception"); AtomicReference<Throwable> handledException = new AtomicReference<>(); assertThatThrownBy( () -> { try (FlinkUserCodeClassLoader classLoaderWithErrorHandler = new ThrowingURLClassLoader( handledException::set, expectedException)) { classLoaderWithErrorHandler.loadClass("dummy.class"); } }) .isSameAs(expectedException); assertThat(handledException.get()).isSameAs(expectedException); } private static
FlinkUserCodeClassLoaderTest
java
processing__processing4
app/src/processing/app/syntax/JEditTextArea.java
{ "start": 65600, "end": 65793 }
class ____ extends ComponentAdapter { public void componentResized(ComponentEvent evt) { recalculateVisibleLines(); scrollBarsInitialized = true; } }
ComponentHandler
java
greenrobot__greendao
tests/DaoTestBase/src/main/java/org/greenrobot/greendao/daotest/SqliteMaster.java
{ "start": 322, "end": 1820 }
class ____ { private String type; private String name; @Property(nameInDb = "tbl_name") private String tableName; private Long rootpage; private String sql; // KEEP FIELDS - put your custom fields here // KEEP FIELDS END @Generated public SqliteMaster() { } @Generated public SqliteMaster(String type, String name, String tableName, Long rootpage, String sql) { this.type = type; this.name = name; this.tableName = tableName; this.rootpage = rootpage; this.sql = sql; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public Long getRootpage() { return rootpage; } public void setRootpage(Long rootpage) { this.rootpage = rootpage; } public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } // KEEP METHODS - put your custom methods here @Override public String toString() { return "Type: " + type + ", name: " + name + ", table: " + tableName + ", SQL: " + sql; } // KEEP METHODS END }
SqliteMaster
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/DatabaseCreationTimestampNullableColumnTest.java
{ "start": 1363, "end": 1457 }
class ____ { @Entity(name = "Person") public static
DatabaseCreationTimestampNullableColumnTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/SequenceInformation.java
{ "start": 304, "end": 1254 }
interface ____ { /** * The qualified sequence name. * * @return The sequence name */ QualifiedSequenceName getSequenceName(); /** * Retrieve the extracted start value defined for the sequence. * * @return The extracted start value or null id the value could not be extracted. */ Number getStartValue(); /** * Retrieve the extracted minimum value defined for the sequence. * * @return The extracted minimum value or null id the value could not be extracted. */ Number getMinValue(); /** * Retrieve the extracted maximum value defined for the sequence. * * @return The extracted maximum value or null id the value could not be extracted. */ Number getMaxValue(); /** * Retrieve the extracted increment value defined for the sequence. * * @return The extracted increment value; use a negative number to indicate the increment could not be extracted. */ Number getIncrementValue(); }
SequenceInformation
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/authorization/OAuth2AuthorizationCodeGrantTests.java
{ "start": 64879, "end": 65645 }
class ____ implements OAuth2TokenGenerator<OAuth2RefreshToken> { private final StringKeyGenerator refreshTokenGenerator = new Base64StringKeyGenerator( Base64.getUrlEncoder().withoutPadding(), 96); @Nullable @Override public OAuth2RefreshToken generate(OAuth2TokenContext context) { if (!OAuth2TokenType.REFRESH_TOKEN.equals(context.getTokenType())) { return null; } Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt .plus(context.getRegisteredClient().getTokenSettings().getRefreshTokenTimeToLive()); return new OAuth2RefreshToken(this.refreshTokenGenerator.generateKey(), issuedAt, expiresAt); } } } @EnableWebSecurity @Configuration(proxyBeanMethods = false) static
CustomRefreshTokenGenerator
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/io/DefaultResourceLoader.java
{ "start": 2901, "end": 3101 }
class ____ at the time of actual resource access. */ public void setClassLoader(@Nullable ClassLoader classLoader) { this.classLoader = classLoader; } /** * Return the ClassLoader to load
loader
java
apache__camel
components/camel-pubnub/src/main/java/org/apache/camel/component/pubnub/PubNubConstants.java
{ "start": 899, "end": 1623 }
class ____ { @Metadata(label = "producer", description = "The operation to perform.", javaType = "String") public static final String OPERATION = "CamelPubNubOperation"; @Metadata(description = "The Timestamp for the event.", javaType = "Long") public static final String TIMETOKEN = "CamelPubNubTimeToken"; @Metadata(label = "consumer", description = "The channel for which the message belongs.", javaType = "String") public static final String CHANNEL = "CamelPubNubChannel"; @Metadata(label = "producer", description = "UUID to be used as a device identifier.", javaType = "String") public static final String UUID = "CamelPubNubUUID"; private PubNubConstants() { } }
PubNubConstants
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/Session.java
{ "start": 46871, "end": 48199 }
class ____ not resolve as a mapped entity * * @deprecated This method will be removed. * Use {@link #find(Class, Object, FindOption...)} instead. * See {@link FindOption}. */ @Deprecated(since = "7.1", forRemoval = true) <T> IdentifierLoadAccess<T> byId(Class<T> entityClass); /** * Create an {@link IdentifierLoadAccess} instance to retrieve an instance of the named * entity type by its primary key. * * @param entityName the entity name of the entity type to be retrieved * * @return an instance of {@link IdentifierLoadAccess} for executing the lookup * * @throws HibernateException If the given name does not resolve to a mapped entity * * @deprecated This method will be removed. * Use {@link #find(String, Object, FindOption...)} instead. * See {@link FindOption}. */ @Deprecated(since = "7.1", forRemoval = true) <T> IdentifierLoadAccess<T> byId(String entityName); /** * Create a {@link MultiIdentifierLoadAccess} instance to retrieve multiple instances * of the given entity type by their primary key values, using batching. * * @param entityClass the entity type to be retrieved * * @return an instance of {@link MultiIdentifierLoadAccess} for executing the lookup * * @throws HibernateException If the given
does
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/security/permission/HttpSecPolicyGrantingRolesTest.java
{ "start": 1997, "end": 4375 }
class ____ { @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest().setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class) .addClasses(TestIdentityController.class, TestIdentityProvider.class, RolesPathHandler.class, CDIBean.class, CustomPermission.class, CustomPermissionWithActions.class, AuthenticatedUser.class, AuthenticatedUserImpl.class) .addAsResource("conf/http-roles-grant-config.properties", "application.properties")); @Test public void mapRolesToRolesSecuredWithRolesAllowed() { assertSuccess(ADMIN, "/test/new-admin-roles-blocking"); assertSuccess(ADMIN, "/test/new-admin-roles"); assertSuccess(ADMIN, "/test/new-admin-roles2"); assertSuccess(ADMIN, "/test/old-admin-roles-blocking"); assertSuccess(ADMIN, "/test/old-admin-roles"); assertSuccess(ADMIN, "/test/multiple-new-roles-1"); assertSuccess(ADMIN, "/test/multiple-new-roles-2"); assertSuccess(ADMIN, "/test/multiple-new-roles-3"); assertForbidden(USER, "/test/new-admin-roles-blocking"); assertForbidden(USER, "/test/new-admin-roles"); assertForbidden(USER, "/test/new-admin-roles2"); assertForbidden(USER, "/test/old-admin-roles-blocking"); assertForbidden(USER, "/test/old-admin-roles"); assertSuccess(USER, "/test/multiple-new-roles-1"); assertSuccess(USER, "/test/multiple-new-roles-2"); assertSuccess(USER, "/test/multiple-new-roles-3"); } @Test public void mapRolesToRolesNoSecurityAnnotation() { assertSuccess(ADMIN, "/test/roles-allowed-path"); assertForbidden(USER, "/test/roles-allowed-path"); assertForbidden(ROOT, "/test/roles-allowed-path"); assertSuccess(ADMIN, "/test/granted-and-checked-by-policy"); assertForbidden(USER, "/test/granted-and-checked-by-policy"); assertSuccess(ROOT, "/test/granted-and-checked-by-policy"); } @Test public void mapRolesToBothPermissionsAndRoles() { assertSuccess(ADMIN, "/test/roles-and-perms-1"); assertSuccess(ADMIN, "/test/roles-and-perms-2"); assertForbidden(USER, "/test/roles-and-perms-1"); assertForbidden(USER, "/test/roles-and-perms-2"); } @ApplicationScoped public static
HttpSecPolicyGrantingRolesTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_doesNotHave_Test.java
{ "start": 1072, "end": 1548 }
class ____ extends AbstractAssertBaseTest { private static Condition<Object> condition; @BeforeAll static void setUpOnce() { condition = new TestCondition<>(); } @Override protected ConcreteAssert invoke_api_method() { return assertions.doesNotHave(condition); } @Override protected void verify_internal_effects() { verify(conditions).assertDoesNotHave(getInfo(assertions), getActual(assertions), condition); } }
AbstractAssert_doesNotHave_Test
java
quarkusio__quarkus
extensions/micrometer/deployment/src/test/java/io/quarkus/micrometer/test/MockServiceSelectorConfiguration.java
{ "start": 203, "end": 1283 }
class ____ implements io.smallrye.stork.api.config.ConfigWithType { private final Map<String, String> parameters; /** * Creates a new FakeSelectorConfiguration * * @param params the parameters, must not be {@code null} */ public MockServiceSelectorConfiguration(Map<String, String> params) { parameters = Collections.unmodifiableMap(params); } /** * Creates a new FakeSelectorConfiguration */ public MockServiceSelectorConfiguration() { parameters = Collections.emptyMap(); } /** * @return the type */ @Override public String type() { return "fake-selector"; } /** * @return the parameters */ @Override public Map<String, String> parameters() { return parameters; } private MockServiceSelectorConfiguration extend(String key, String value) { Map<String, String> copy = new HashMap<>(parameters); copy.put(key, value); return new MockServiceSelectorConfiguration(copy); } }
MockServiceSelectorConfiguration
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/metadata/CheckpointTestUtils.java
{ "start": 16290, "end": 17443 }
class ____ extends SegmentFileStateHandle implements DiscardRecordedStateObject { private static final long serialVersionUID = 1L; private boolean disposed; public TestingSegmentFileStateHandle( Path filePath, long startPos, long stateSize, CheckpointedStateScope scope) { super( filePath, startPos, stateSize, scope, LogicalFile.LogicalFileId.generateRandomId()); } @Override public void collectSizeStats(StateObjectSizeStatsCollector collector) { // Collect to LOCAL_MEMORY for test collector.add(StateObjectLocation.LOCAL_MEMORY, getStateSize()); } @Override public void discardState() { super.discardState(); disposed = true; } @Override public boolean isDisposed() { return disposed; } } private static UUID createRandomUUID(Random rnd) { return new UUID(rnd.nextLong(), rnd.nextLong()); } }
TestingSegmentFileStateHandle
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/text/FormattableUtils.java
{ "start": 1182, "end": 1724 }
interface ____ basic control over formatting * when using a {@link Formatter}. It is primarily concerned with numeric precision * and padding, and is not designed to allow generalized alternate formats.</p> * * @since 3.0 * @deprecated As of <a href="https://commons.apache.org/proper/commons-lang/changes-report.html#a3.6">3.6</a>, use Apache Commons Text * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/FormattableUtils.html"> * FormattableUtils</a>. */ @Deprecated public
provides
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java
{ "start": 8172, "end": 9055 }
class ____ the current invocation * (can be {@code null} or may not even implement the method) * @return the specific target method, or the original method if the * {@code targetClass} does not implement it * @see org.springframework.util.ClassUtils#getMostSpecificMethod * @see org.springframework.core.BridgeMethodResolver#getMostSpecificMethod */ public static Method getMostSpecificMethod(Method method, @Nullable Class<?> targetClass) { Class<?> specificTargetClass = (targetClass != null ? ClassUtils.getUserClass(targetClass) : null); return BridgeMethodResolver.getMostSpecificMethod(method, specificTargetClass); } /** * Can the given pointcut apply at all on the given class? * <p>This is an important test as it can be used to optimize * out a pointcut for a class. * @param pc the static or dynamic pointcut to check * @param targetClass the
for
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/alterTable/MySqlAlterTableTest4.java
{ "start": 1034, "end": 2103 }
class ____ extends TestCase { public void test_alter_first() throws Exception { String sql = "alter table test add dspcode char(200)"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); stmt.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); String output = SQLUtils.toMySqlString(stmt); assertEquals("ALTER TABLE test" + "\n\tADD COLUMN dspcode char(200)", output); assertEquals(1, visitor.getTables().size()); assertEquals(1, visitor.getColumns().size()); assertTrue(visitor.getColumns().contains(new Column("test", "dspcode"))); } }
MySqlAlterTableTest4
java
google__gson
test-graal-native-image/src/test/java/com/google/gson/native_test/ReflectionTest.java
{ "start": 1998, "end": 2261 }
class ____ { private int i = -1; // Explicit constructor with args to remove implicit no-args default constructor private ClassWithoutDefaultConstructor(int i) { this.i = i; } } /** * Tests deserializing a
ClassWithoutDefaultConstructor
java
quarkusio__quarkus
integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KnativeWithTrafficSplittingTest.java
{ "start": 502, "end": 2436 }
class ____ { @RegisterExtension static final QuarkusProdModeTest config = new QuarkusProdModeTest() .withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class)) .setApplicationName("knative-with-traffic-splitting") .setApplicationVersion("0.1-SNAPSHOT") .withConfigurationResource("knative-with-traffic-splitting.properties"); @ProdBuildResults private ProdModeTestResults prodModeTestResults; @Test public void assertGeneratedResources() throws IOException { Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes"); assertThat(kubernetesDir) .isDirectoryContaining(p -> p.getFileName().endsWith("knative.json")) .isDirectoryContaining(p -> p.getFileName().endsWith("knative.yml")) .satisfies(p -> assertThat(p.toFile().listFiles()).hasSize(2)); List<HasMetadata> kubernetesList = DeserializationUtil .deserializeAsList(kubernetesDir.resolve("knative.yml")); assertThat(kubernetesList).filteredOn(i -> "Service".equals(i.getKind())).singleElement().satisfies(i -> { assertThat(i).isInstanceOfSatisfying(Service.class, s -> { assertThat(s.getSpec()).satisfies(spec -> { assertThat(s.getMetadata()).satisfies(m -> { assertThat(m.getName()).isEqualTo("knative-with-traffic-splitting"); }); assertThat(spec.getTemplate()).satisfies(template -> { assertThat(template.getMetadata().getName()).isEqualTo("my-revision"); }); assertThat(spec.getTraffic()).singleElement().satisfies(t -> { assertThat(t.getPercent()).isEqualTo(80); }); }); }); }); } }
KnativeWithTrafficSplittingTest
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/support/AbstractGenericPointcutAdvisor.java
{ "start": 974, "end": 1398 }
class ____ extends AbstractPointcutAdvisor { private Advice advice = EMPTY_ADVICE; /** * Specify the advice that this advisor should apply. */ public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public String toString() { return getClass().getName() + ": advice [" + getAdvice() + "]"; } }
AbstractGenericPointcutAdvisor
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2300/Issue2397.java
{ "start": 891, "end": 1404 }
class ____ implements Serializable { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Msg(int id, String name) { this.id = id; this.name = name; } } public static
Msg
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/utils/VoidChainTaskExecutorTests.java
{ "start": 742, "end": 5443 }
class ____ extends ESTestCase { private final ThreadPool threadPool = new TestThreadPool(getClass().getName()); private final CountDownLatch latch = new CountDownLatch(1); @Override @After public void tearDown() throws Exception { try { terminate(threadPool); } finally { super.tearDown(); } } public void testExecute() throws InterruptedException { final List<String> strings = new ArrayList<>(); ActionListener<List<Void>> finalListener = createBlockingListener(() -> strings.add("last"), e -> fail()); VoidChainTaskExecutor voidChainTaskExecutor = new VoidChainTaskExecutor(threadPool.generic(), false); voidChainTaskExecutor.add(listener -> { strings.add("first"); listener.onResponse(null); }); voidChainTaskExecutor.add(listener -> { strings.add("second"); listener.onResponse(null); }); voidChainTaskExecutor.execute(finalListener); latch.await(); assertThat(strings, contains("first", "second", "last")); } public void testExecute_GivenSingleFailureAndShortCircuit() throws InterruptedException { final List<String> strings = new ArrayList<>(); ActionListener<List<Void>> finalListener = createBlockingListener( () -> fail(), e -> assertThat(e.getMessage(), equalTo("some error")) ); VoidChainTaskExecutor voidChainTaskExecutor = new VoidChainTaskExecutor(threadPool.generic(), true); voidChainTaskExecutor.add(listener -> { strings.add("before"); listener.onResponse(null); }); voidChainTaskExecutor.add(listener -> { throw new RuntimeException("some error"); }); voidChainTaskExecutor.add(listener -> { strings.add("after"); listener.onResponse(null); }); voidChainTaskExecutor.execute(finalListener); latch.await(); assertThat(strings, contains("before")); } public void testExecute_GivenMultipleFailuresAndShortCircuit() throws InterruptedException { final List<String> strings = new ArrayList<>(); ActionListener<List<Void>> finalListener = createBlockingListener( () -> fail(), e -> assertThat(e.getMessage(), equalTo("some error 1")) ); VoidChainTaskExecutor voidChainTaskExecutor = new VoidChainTaskExecutor(threadPool.generic(), true); voidChainTaskExecutor.add(listener -> { strings.add("before"); listener.onResponse(null); }); voidChainTaskExecutor.add(listener -> { throw new RuntimeException("some error 1"); }); voidChainTaskExecutor.add(listener -> { throw new RuntimeException("some error 2"); }); voidChainTaskExecutor.execute(finalListener); latch.await(); assertThat(strings, contains("before")); } public void testExecute_GivenFailureAndNoShortCircuit() throws InterruptedException { final List<String> strings = new ArrayList<>(); ActionListener<List<Void>> finalListener = createBlockingListener(() -> strings.add("last"), e -> fail()); VoidChainTaskExecutor voidChainTaskExecutor = new VoidChainTaskExecutor(threadPool.generic(), false); voidChainTaskExecutor.add(listener -> { strings.add("before"); listener.onResponse(null); }); voidChainTaskExecutor.add(listener -> { throw new RuntimeException("some error"); }); voidChainTaskExecutor.add(listener -> { strings.add("after"); listener.onResponse(null); }); voidChainTaskExecutor.execute(finalListener); latch.await(); assertThat(strings, contains("before", "after", "last")); } public void testExecute_GivenNoTasksAdded() throws InterruptedException { final List<String> strings = new ArrayList<>(); ActionListener<List<Void>> finalListener = createBlockingListener(() -> strings.add("last"), e -> fail()); VoidChainTaskExecutor voidChainTaskExecutor = new VoidChainTaskExecutor(threadPool.generic(), false); voidChainTaskExecutor.execute(finalListener); latch.await(); assertThat(strings, contains("last")); } private ActionListener<List<Void>> createBlockingListener(Runnable runnable, Consumer<Exception> errorHandler) { return ActionListener.wrap(nullValue -> { runnable.run(); latch.countDown(); }, e -> { errorHandler.accept(e); latch.countDown(); }); } }
VoidChainTaskExecutorTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.java
{ "start": 30957, "end": 31273 }
class ____ { public void doTest() { Client client = new Client(); client.before(1); client.before(1, 2, 3); } } """) .addOutputLines( "out/Caller.java", """ public final
Caller
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/math/RoundToDouble6Evaluator.java
{ "start": 1094, "end": 4493 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(RoundToDouble6Evaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator field; private final double p0; private final double p1; private final double p2; private final double p3; private final double p4; private final double p5; private final DriverContext driverContext; private Warnings warnings; public RoundToDouble6Evaluator(Source source, EvalOperator.ExpressionEvaluator field, double p0, double p1, double p2, double p3, double p4, double p5, DriverContext driverContext) { this.source = source; this.field = field; this.p0 = p0; this.p1 = p1; this.p2 = p2; this.p3 = p3; this.p4 = p4; this.p5 = p5; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (DoubleBlock fieldBlock = (DoubleBlock) field.eval(page)) { DoubleVector fieldVector = fieldBlock.asVector(); if (fieldVector == null) { return eval(page.getPositionCount(), fieldBlock); } return eval(page.getPositionCount(), fieldVector).asBlock(); } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += field.baseRamBytesUsed(); return baseRamBytesUsed; } public DoubleBlock eval(int positionCount, DoubleBlock fieldBlock) { try(DoubleBlock.Builder result = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { switch (fieldBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } double field = fieldBlock.getDouble(fieldBlock.getFirstValueIndex(p)); result.appendDouble(RoundToDouble.process(field, this.p0, this.p1, this.p2, this.p3, this.p4, this.p5)); } return result.build(); } } public DoubleVector eval(int positionCount, DoubleVector fieldVector) { try(DoubleVector.FixedBuilder result = driverContext.blockFactory().newDoubleVectorFixedBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { double field = fieldVector.getDouble(p); result.appendDouble(p, RoundToDouble.process(field, this.p0, this.p1, this.p2, this.p3, this.p4, this.p5)); } return result.build(); } } @Override public String toString() { return "RoundToDouble6Evaluator[" + "field=" + field + ", p0=" + p0 + ", p1=" + p1 + ", p2=" + p2 + ", p3=" + p3 + ", p4=" + p4 + ", p5=" + p5 + "]"; } @Override public void close() { Releasables.closeExpectNoException(field); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
RoundToDouble6Evaluator
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/instantiation/InstantiationWithGenericsExpressionTest.java
{ "start": 1133, "end": 5013 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { final ConcreteEntity entity = new ConcreteEntity(); entity.setId( 1 ); entity.setGen( 1L ); entity.setData( "entity_1" ); session.persist( entity ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testConstructorBinaryExpression(SessionFactoryScope scope) { scope.inTransaction( session -> assertThat( session.createQuery( "select new ConstructorDto(e.gen+e.gen, e.data) from ConcreteEntity e", ConstructorDto.class ).getSingleResult() ).extracting( ConstructorDto::getGen, ConstructorDto::getData ) .containsExactly( 2L, "entity_1" ) ); } @Test public void testImplicitConstructorBinaryExpression(SessionFactoryScope scope) { scope.inTransaction( session -> assertThat( session.createQuery( "select e.gen+e.gen, e.data from ConcreteEntity e", ConstructorDto.class ).getSingleResult() ).extracting( ConstructorDto::getGen, ConstructorDto::getData ) .containsExactly( 2L, "entity_1" ) ); } @Test public void testInjectionBinaryExpression(SessionFactoryScope scope) { scope.inTransaction( session -> assertThat( session.createQuery( "select new InjectionDto(e.gen+e.gen as gen, e.data as data) from ConcreteEntity e", InjectionDto.class ).getSingleResult() ).extracting( InjectionDto::getGen, InjectionDto::getData ) .containsExactly( 2L, "entity_1" ) ); } @Test public void testConstructorUnaryExpression(SessionFactoryScope scope) { scope.inTransaction( session -> assertThat( session.createQuery( "select new ConstructorDto(-e.gen, e.data) from ConcreteEntity e", ConstructorDto.class ).getSingleResult() ).extracting( ConstructorDto::getGen, ConstructorDto::getData ) .containsExactly( -1L, "entity_1" ) ); } @Test public void testImplicitConstructorUnaryExpression(SessionFactoryScope scope) { scope.inTransaction( session -> assertThat( session.createQuery( "select -e.gen, e.data from ConcreteEntity e", ConstructorDto.class ).getSingleResult() ).extracting( ConstructorDto::getGen, ConstructorDto::getData ) .containsExactly( -1L, "entity_1" ) ); } @Test public void testInjectionUnaryExpression(SessionFactoryScope scope) { scope.inTransaction( session -> assertThat( session.createQuery( "select new InjectionDto(-e.gen as gen, e.data as data) from ConcreteEntity e", InjectionDto.class ).getSingleResult() ).extracting( InjectionDto::getGen, InjectionDto::getData ) .containsExactly( -1L, "entity_1" ) ); } @Test public void testConstructorFunction(SessionFactoryScope scope) { scope.inTransaction( session -> { assertThat( session.createQuery( "select new ConstructorDto(abs(e.gen), e.data) from ConcreteEntity e", ConstructorDto.class ).getSingleResult() ).extracting( ConstructorDto::getGen, ConstructorDto::getData ) .containsExactly( 1L, "entity_1" ); } ); } @Test public void testImplicitFunction(SessionFactoryScope scope) { scope.inTransaction( session -> { assertThat( session.createQuery( "select abs(e.gen), e.data from ConcreteEntity e", ConstructorDto.class ).getSingleResult() ).extracting( ConstructorDto::getGen, ConstructorDto::getData ) .containsExactly( 1L, "entity_1" ); } ); } @Test public void testInjectionFunction(SessionFactoryScope scope) { scope.inTransaction( session -> { assertThat( session.createQuery( "select new InjectionDto(abs(e.gen) as gen, e.data as data) from ConcreteEntity e", InjectionDto.class ).getSingleResult() ).extracting( InjectionDto::getGen, InjectionDto::getData ) .containsExactly( 1L, "entity_1" ); } ); } @MappedSuperclass static abstract
InstantiationWithGenericsExpressionTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/jdbc/AbstractReturningWork.java
{ "start": 482, "end": 1250 }
class ____<T> implements ReturningWork<T>, WorkExecutorVisitable<T> { /** * Accepts a {@link WorkExecutor} visitor for executing the discrete work * encapsulated by this work instance using the supplied connection. * * @param executor The visitor that executes the work * @param connection The connection on which to perform the work. * * @return the valued returned by {@link #execute(Connection)}. * * @throws SQLException Thrown during execution of the underlying JDBC interaction. * @throws org.hibernate.HibernateException Generally indicates a wrapped SQLException. */ public T accept(WorkExecutor<T> executor, Connection connection) throws SQLException { return executor.executeReturningWork( this, connection ); } }
AbstractReturningWork
java
quarkusio__quarkus
integration-tests/elytron-resteasy-reactive/src/main/java/io/quarkus/it/resteasy/reactive/elytron/StreamingOutputResource.java
{ "start": 471, "end": 1386 }
class ____ { private static final int ITEMS_PER_EMIT = 100; private static final byte[] CHUNK = "This is one chunk of data.\n".getBytes(StandardCharsets.UTF_8); @GET @Path("/output") @Produces(MediaType.TEXT_PLAIN) @Blocking public StreamingOutput streamOutput(@QueryParam("fail") @DefaultValue("false") boolean fail) { return outputStream -> { try { writeData(outputStream); if (fail) { throw new IOException("dummy failure"); } writeData(outputStream); } catch (IOException e) { throw new RuntimeException(e); } }; } private void writeData(OutputStream out) throws IOException { for (int i = 0; i < ITEMS_PER_EMIT; i++) { out.write(CHUNK); out.flush(); } } }
StreamingOutputResource
java
apache__maven
its/core-it-support/core-it-plugins/maven-it-plugin-packaging/src/main/java/org/apache/maven/plugin/coreit/PackagingMojo.java
{ "start": 1263, "end": 2265 }
class ____ extends AbstractMojo { /** */ @Parameter(defaultValue = "${project.build.finalName}", required = true) private String finalName; /** */ @Parameter(defaultValue = "${project.build.directory}", required = true, readonly = true) private File outputDirectory; public void execute() throws MojoExecutionException { File jarFile = new File(outputDirectory, finalName + "-it.jar"); getLog().info("[MAVEN-CORE-IT-LOG] Creating artifact file: " + jarFile); try { jarFile.getParentFile().mkdirs(); jarFile.createNewFile(); } catch (IOException e) { throw new MojoExecutionException("Error assembling JAR", e); } /* * NOTE: Normal packaging plugins would set the main artifact's file path now but that's beyond the purpose of * this test plugin. Hence there's no need to introduce further coupling with the Maven Artifact API. */ } }
PackagingMojo
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/dataformat/JacksonXMLDataFormat.java
{ "start": 20765, "end": 23422 }
enum ____ * <tt>com.fasterxml.jackson.databind.SerializationFeature</tt>, * <tt>com.fasterxml.jackson.databind.DeserializationFeature</tt>, or * <tt>com.fasterxml.jackson.databind.MapperFeature</tt> * <p/> * Multiple features can be separated by comma */ public Builder disableFeatures(String disableFeatures) { this.disableFeatures = disableFeatures; return this; } /** * If enabled then Jackson is allowed to attempt to use the CamelJacksonUnmarshalType header during the * unmarshalling. * <p/> * This should only be enabled when desired to be used. */ public Builder allowUnmarshallType(String allowUnmarshallType) { this.allowUnmarshallType = allowUnmarshallType; return this; } /** * If enabled then Jackson is allowed to attempt to use the CamelJacksonUnmarshalType header during the * unmarshalling. * <p/> * This should only be enabled when desired to be used. */ public Builder allowUnmarshallType(boolean allowUnmarshallType) { this.allowUnmarshallType = Boolean.toString(allowUnmarshallType); return this; } public Builder contentTypeHeader(String contentTypeHeader) { this.contentTypeHeader = contentTypeHeader; return this; } public Builder contentTypeHeader(boolean contentTypeHeader) { this.contentTypeHeader = Boolean.toString(contentTypeHeader); return this; } /** * If set then Jackson will use the Timezone when marshalling/unmarshalling. */ public Builder timezone(String timezone) { this.timezone = timezone; return this; } /** * Sets the maximum string length (in chars or bytes, depending on input context). The default is 20,000,000. * This limit is not exact, the limit is applied when we increase internal buffer sizes and an exception will * happen at sizes greater than this limit. Some text values that are a little bigger than the limit may be * treated as valid but no text values with sizes less than or equal to this limit will be treated as invalid. */ public Builder maxStringLength(String maxStringLength) { this.maxStringLength = maxStringLength; return this; } @Override public JacksonXMLDataFormat end() { return new JacksonXMLDataFormat(this); } } }
from
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLCreateFunctionStatement.java
{ "start": 910, "end": 7638 }
class ____ extends SQLStatementImpl implements SQLCreateStatement, SQLObjectWithDataType { protected SQLName definer; protected boolean create = true; protected boolean orReplace; protected SQLName name; protected SQLStatement block; protected List<SQLParameter> parameters = new ArrayList<>(); protected List<SQLAssignItem> options = new ArrayList<>(); // for oracle private String javaCallSpec; private SQLName authid; SQLDataType returnDataType; // for mysql private String comment; private boolean deterministic; private boolean parallelEnable; private boolean aggregate; private SQLName using; private boolean pipelined; private boolean resultCache; private String wrappedSource; private String language; private boolean temporary; protected boolean ifNotExists; public SQLCreateFunctionStatement() { } public SQLCreateFunctionStatement clone() { SQLCreateFunctionStatement x = new SQLCreateFunctionStatement(); if (definer != null) { x.setDefiner(definer.clone()); } x.create = create; x.orReplace = orReplace; if (name != null) { x.setName(name.clone()); } if (block != null) { x.setBlock(block.clone()); } for (SQLParameter p : parameters) { SQLParameter p2 = p.clone(); p2.setParent(x); x.parameters.add(p2); } x.javaCallSpec = javaCallSpec; if (authid != null) { x.setAuthid(authid.clone()); } if (returnDataType != null) { x.setReturnDataType(returnDataType.clone()); } x.comment = comment; x.deterministic = deterministic; x.pipelined = pipelined; x.language = language; return x; } @Override public void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, definer); acceptChild(visitor, name); acceptChild(visitor, parameters); acceptChild(visitor, returnDataType); acceptChild(visitor, block); } visitor.endVisit(this); } public List<SQLParameter> getParameters() { return parameters; } public SQLParameter getParameter(String name) { if (name == null) { return null; } for (SQLParameter parameter : parameters) { if (name.equals(parameter.getName().getSimpleName())) { return parameter; } } return null; } public void setParameters(List<SQLParameter> parameters) { this.parameters = parameters; } public SQLName getName() { return name; } public void setName(SQLName x) { if (x != null) { x.setParent(this); } this.name = x; } public SQLStatement getBlock() { return block; } public void setBlock(SQLStatement block) { if (block != null) { block.setParent(this); } this.block = block; } public SQLName getAuthid() { return authid; } public void setAuthid(SQLName authid) { if (authid != null) { authid.setParent(this); } this.authid = authid; } public List<SQLAssignItem> getOptions() { return options; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public boolean isOrReplace() { return orReplace; } public void setOrReplace(boolean orReplace) { this.orReplace = orReplace; } public SQLName getDefiner() { return definer; } public void setDefiner(SQLName definer) { this.definer = definer; } public boolean isCreate() { return create; } public void setCreate(boolean create) { this.create = create; } public String getJavaCallSpec() { return javaCallSpec; } public void setJavaCallSpec(String javaCallSpec) { this.javaCallSpec = javaCallSpec; } public SQLDataType getReturnDataType() { return returnDataType; } public void setReturnDataType(SQLDataType returnDataType) { if (returnDataType != null) { returnDataType.setParent(this); } this.returnDataType = returnDataType; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public boolean isDeterministic() { return deterministic; } public void setDeterministic(boolean deterministic) { this.deterministic = deterministic; } public String getSchema() { SQLName name = getName(); if (name == null) { return null; } if (name instanceof SQLPropertyExpr) { return ((SQLPropertyExpr) name).getOwnernName(); } return null; } @Override public SQLDataType getDataType() { return returnDataType; } @Override public void setDataType(SQLDataType dataType) { this.setReturnDataType(dataType); } public boolean isParallelEnable() { return parallelEnable; } public void setParallelEnable(boolean parallel_enable) { this.parallelEnable = parallel_enable; } public boolean isAggregate() { return aggregate; } public void setAggregate(boolean aggregate) { this.aggregate = aggregate; } public SQLName getUsing() { return using; } public void setUsing(SQLName using) { this.using = using; } public boolean isPipelined() { return pipelined; } public void setPipelined(boolean pipelined) { this.pipelined = pipelined; } public boolean isResultCache() { return resultCache; } public void setResultCache(boolean resultCache) { this.resultCache = resultCache; } public String getWrappedSource() { return wrappedSource; } public void setWrappedSource(String wrappedSource) { this.wrappedSource = wrappedSource; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public boolean isIfNotExists() { return ifNotExists; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } }
SQLCreateFunctionStatement
java
spring-projects__spring-framework
spring-jms/src/main/java/org/springframework/jms/listener/adapter/MessageListenerAdapter.java
{ "start": 3160, "end": 3617 }
interface ____ { * void handleMessage(String text); * void handleMessage(Map map); * void handleMessage(byte[] bytes); * void handleMessage(Serializable obj); * }</pre> * * This next example handles all {@code Message} types and gets * passed the actual (raw) {@code Message} as an argument. Again, no * {@code Message} will be sent back as all of these methods return * {@code void}. * * <pre class="code">public
MessageContentsDelegate
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/method/ProtectPointcutPostProcessor.java
{ "start": 2450, "end": 2900 }
class ____ method security metadata with * {@link MapBasedMethodSecurityMetadataSource}, normal Spring Security capabilities such * as {@link MethodSecurityMetadataSourceAdvisor} can be used. It does not matter the fact * the method metadata was originally obtained from an AspectJ pointcut expression * evaluation. * * @author Ben Alex * @since 2.0 * @deprecated Use {@code use-authorization-manager} flag instead */ @Deprecated final
registers
java
spring-projects__spring-framework
spring-webflux/src/test/java/org/springframework/web/reactive/resource/CachingResourceResolverTests.java
{ "start": 1558, "end": 6113 }
class ____ { private static final Duration TIMEOUT = Duration.ofSeconds(5); private Cache cache; private ResourceResolverChain chain; private List<Resource> locations; @BeforeEach void setup() { this.cache = new ConcurrentMapCache("resourceCache"); List<ResourceResolver> resolvers = new ArrayList<>(); resolvers.add(new CachingResourceResolver(this.cache)); resolvers.add(new PathResourceResolver()); this.chain = new DefaultResourceResolverChain(resolvers); this.locations = new ArrayList<>(); this.locations.add(new ClassPathResource("test/", getClass())); } @Test void resolveResourceInternal() { Resource expected = new ClassPathResource("test/bar.css", getClass()); MockServerWebExchange exchange = MockServerWebExchange.from(get("")); Resource actual = this.chain.resolveResource(exchange, "bar.css", this.locations).block(TIMEOUT); assertThat(actual).isNotSameAs(expected); assertThat(actual).isEqualTo(expected); } @Test void resolveResourceInternalFromCache() { Resource expected = mock(); this.cache.put(resourceKey("bar.css"), expected); MockServerWebExchange exchange = MockServerWebExchange.from(get("")); Resource actual = this.chain.resolveResource(exchange, "bar.css", this.locations).block(TIMEOUT); assertThat(actual).isSameAs(expected); } @Test void resolveResourceInternalNoMatch() { MockServerWebExchange exchange = MockServerWebExchange.from(get("")); assertThat(this.chain.resolveResource(exchange, "invalid.css", this.locations).block(TIMEOUT)).isNull(); } @Test void resolverUrlPath() { String expected = "/foo.css"; String actual = this.chain.resolveUrlPath(expected, this.locations).block(TIMEOUT); assertThat(actual).isEqualTo(expected); } @Test void resolverUrlPathFromCache() { String expected = "cached-imaginary.css"; this.cache.put(CachingResourceResolver.RESOLVED_URL_PATH_CACHE_KEY_PREFIX + "imaginary.css", expected); String actual = this.chain.resolveUrlPath("imaginary.css", this.locations).block(TIMEOUT); assertThat(actual).isEqualTo(expected); } @Test void resolverUrlPathNoMatch() { assertThat(this.chain.resolveUrlPath("invalid.css", this.locations).block(TIMEOUT)).isNull(); } @Test void resolveResourceAcceptEncodingInCacheKey(GzippedFiles gzippedFiles) { String file = "bar.css"; gzippedFiles.create(file); // 1. Resolve plain resource MockServerWebExchange exchange = MockServerWebExchange.from(get(file)); Resource expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT); String cacheKey = resourceKey(file); assertThat(this.cache.get(cacheKey).get()).isSameAs(expected); // 2. Resolve with Accept-Encoding exchange = MockServerWebExchange.from(get(file) .header("Accept-Encoding", "gzip ; a=b , deflate , br ; c=d ")); expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT); cacheKey = resourceKey(file + "+encoding=br,gzip"); assertThat(this.cache.get(cacheKey).get()).isSameAs(expected); // 3. Resolve with Accept-Encoding but no matching codings exchange = MockServerWebExchange.from(get(file).header("Accept-Encoding", "deflate")); expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT); cacheKey = resourceKey(file); assertThat(this.cache.get(cacheKey).get()).isSameAs(expected); } @Test void resolveResourceNoAcceptEncoding() { String file = "bar.css"; MockServerWebExchange exchange = MockServerWebExchange.from(get(file)); Resource expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT); String cacheKey = resourceKey(file); Object actual = this.cache.get(cacheKey).get(); assertThat(actual).isEqualTo(expected); } @Test void resolveResourceMatchingEncoding() { Resource resource = mock(); Resource gzipped = mock(); this.cache.put(resourceKey("bar.css"), resource); this.cache.put(resourceKey("bar.css+encoding=gzip"), gzipped); String file = "bar.css"; MockServerWebExchange exchange = MockServerWebExchange.from(get(file)); assertThat(this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT)).isSameAs(resource); exchange = MockServerWebExchange.from(get(file).header("Accept-Encoding", "gzip")); assertThat(this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT)).isSameAs(gzipped); } private static String resourceKey(String key) { return CachingResourceResolver.RESOLVED_RESOURCE_CACHE_KEY_PREFIX + key; } }
CachingResourceResolverTests
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/api/functions/sink/legacy/TwoPhaseCommitSinkFunctionTest.java
{ "start": 12746, "end": 13629 }
class ____ extends Clock { private final ZoneId zoneId; private long epochMilli; private SettableClock() { this.zoneId = ZoneOffset.UTC; } public SettableClock(ZoneId zoneId, long epochMilli) { this.zoneId = zoneId; this.epochMilli = epochMilli; } public void setEpochMilli(long epochMilli) { this.epochMilli = epochMilli; } @Override public ZoneId getZone() { return zoneId; } @Override public Clock withZone(ZoneId zone) { if (zone.equals(this.zoneId)) { return this; } return new SettableClock(zone, epochMilli); } @Override public Instant instant() { return Instant.ofEpochMilli(epochMilli); } } }
SettableClock
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/ContainerType.java
{ "start": 1060, "end": 1109 }
enum ____ { APPLICATION_MASTER, TASK }
ContainerType
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/jmx/export/metadata/ManagedNotification.java
{ "start": 884, "end": 2136 }
class ____ { private String @Nullable [] notificationTypes; private @Nullable String name; private @Nullable String description; /** * Set a single notification type, or a list of notification types * as comma-delimited String. */ public void setNotificationType(String notificationType) { this.notificationTypes = StringUtils.commaDelimitedListToStringArray(notificationType); } /** * Set a list of notification types. */ public void setNotificationTypes(String @Nullable ... notificationTypes) { this.notificationTypes = notificationTypes; } /** * Return the list of notification types. */ public String @Nullable [] getNotificationTypes() { return this.notificationTypes; } /** * Set the name of this notification. */ public void setName(@Nullable String name) { this.name = name; } /** * Return the name of this notification. */ public @Nullable String getName() { return this.name; } /** * Set a description for this notification. */ public void setDescription(@Nullable String description) { this.description = description; } /** * Return a description for this notification. */ public @Nullable String getDescription() { return this.description; } }
ManagedNotification
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/action/UpdateTransformAction.java
{ "start": 1966, "end": 6268 }
class ____ extends BaseTasksRequest<Request> { private final TransformConfigUpdate update; private final String id; private final boolean deferValidation; private TransformConfig config; private AuthorizationState authState; public Request(TransformConfigUpdate update, String id, boolean deferValidation, TimeValue timeout) { this.update = update; this.id = id; this.deferValidation = deferValidation; this.setTimeout(timeout); } public Request(StreamInput in) throws IOException { super(in); this.update = new TransformConfigUpdate(in); this.id = in.readString(); this.deferValidation = in.readBoolean(); if (in.readBoolean()) { this.config = new TransformConfig(in); } if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_8_0)) { if (in.readBoolean()) { this.authState = new AuthorizationState(in); } } } public static Request fromXContent( final XContentParser parser, final String id, final boolean deferValidation, final TimeValue timeout ) { return new Request(TransformConfigUpdate.fromXContent(parser), id, deferValidation, timeout); } /** * More complex validations with how {@link TransformConfig#getDestination()} and * {@link TransformConfig#getSource()} relate are done in the update transport handler. */ @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (update.getDestination() != null && update.getDestination().getIndex() != null) { validationException = SourceDestValidator.validateRequest(validationException, update.getDestination().getIndex()); } TimeValue frequency = update.getFrequency(); if (frequency != null) { if (frequency.compareTo(MIN_FREQUENCY) < 0) { validationException = addValidationError( "minimum permitted [" + TransformField.FREQUENCY + "] is [" + MIN_FREQUENCY.getStringRep() + "]", validationException ); } else if (frequency.compareTo(MAX_FREQUENCY) > 0) { validationException = addValidationError( "highest permitted [" + TransformField.FREQUENCY + "] is [" + MAX_FREQUENCY.getStringRep() + "]", validationException ); } } return validationException; } public String getId() { return id; } public boolean isDeferValidation() { return deferValidation; } public TransformConfigUpdate getUpdate() { return update; } public TransformConfig getConfig() { return config; } public void setConfig(TransformConfig config) { this.config = config; } public AuthorizationState getAuthState() { return authState; } public void setAuthState(AuthorizationState authState) { this.authState = authState; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); update.writeTo(out); out.writeString(id); out.writeBoolean(deferValidation); if (config == null) { out.writeBoolean(false); } else { out.writeBoolean(true); config.writeTo(out); } if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_8_0)) { if (authState == null) { out.writeBoolean(false); } else { out.writeBoolean(true); authState.writeTo(out); } } } @Override public int hashCode() { // the base
Request
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/CompositeStateHandle.java
{ "start": 1974, "end": 3233 }
interface ____ extends StateObject { /** * Register both newly created and already referenced shared states in the given {@link * SharedStateRegistry}. This method is called when the checkpoint successfully completes or is * recovered from failures. * * <p>After this is completed, newly created shared state is considered as published is no * longer owned by this handle. This means that it should no longer be deleted as part of calls * to {@link #discardState()}. Instead, {@link #discardState()} will trigger an unregistration * from the registry. * * @param stateRegistry The registry where shared states are registered. */ void registerSharedStates(SharedStateRegistry stateRegistry, long checkpointID); /** * Returns the persisted data size during checkpoint execution in bytes. If incremental * checkpoint is enabled, this value represents the incremental persisted data size, and usually * smaller than {@link #getStateSize()}. If the size is unknown, this method would return same * result as {@link #getStateSize()}. * * @return The persisted data size during checkpoint execution in bytes. */ long getCheckpointedSize(); }
CompositeStateHandle
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/filter/hql/FilterWithDifferentConditionsTest.java
{ "start": 2611, "end": 3573 }
class ____ { @Id private Integer id; @ManyToMany @MapKeyColumn(name = "CAR_TYPE") @JoinTable(name = "PERSON_RENTED") @FilterJoinTable(name = "addressFilter", condition = "(CAR_TYPE = 'bike')") private Map<String, Vehicle> rented = new HashMap<>(); @ManyToMany @JoinTable(name = "PERSON_OWNED") @MapKeyColumn(name = "CAR_TYPE") @FilterJoinTable(name = "addressFilter") private Map<String, Vehicle> owned = new HashMap<>(); public Person() { } public Person(Integer id) { this.id = id; } public void addRented(String type, Vehicle vehicle) { this.rented.put( type, vehicle ); } public void addOwned(String type, Vehicle vehicle) { this.owned.put( type, vehicle ); } public Integer getId() { return id; } public Collection<Vehicle> getRented() { return rented.values(); } public Collection<Vehicle> getOwned() { return owned.values(); } } @Entity(name = "Vehicle") public static
Person
java
apache__flink
flink-filesystems/flink-s3-fs-base/src/main/java/com/amazonaws/services/s3/model/transform/XmlResponsesSaxParser.java
{ "start": 41483, "end": 43702 }
enum ____ early. */ } } } } @Override protected void doEndElement(String uri, String name, String qName) { if (in("AccessControlPolicy", "Owner")) { if (name.equals("ID")) { accessControlList.getOwner().setId(getText()); } else if (name.equals("DisplayName")) { accessControlList.getOwner().setDisplayName(getText()); } } else if (in("AccessControlPolicy", "AccessControlList")) { if (name.equals("Grant")) { accessControlList.grantPermission(currentGrantee, currentPermission); currentGrantee = null; currentPermission = null; } } else if (in("AccessControlPolicy", "AccessControlList", "Grant")) { if (name.equals("Permission")) { currentPermission = Permission.parsePermission(getText()); } } else if (in("AccessControlPolicy", "AccessControlList", "Grant", "Grantee")) { if (name.equals("ID")) { currentGrantee.setIdentifier(getText()); } else if (name.equals("EmailAddress")) { currentGrantee.setIdentifier(getText()); } else if (name.equals("URI")) { /* * Only GroupGrantees contain an URI element in them, and we * can't construct currentGrantee during startElement for a * GroupGrantee since it's an enum. */ currentGrantee = GroupGrantee.parseGroupGrantee(getText()); } else if (name.equals("DisplayName")) { ((CanonicalGrantee) currentGrantee).setDisplayName(getText()); } } } } /** * Handler for LoggingStatus response XML documents for a bucket. The document is parsed into an * {@link BucketLoggingConfiguration} object available via the {@link * #getBucketLoggingConfiguration()} method. */ public static
value
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/LongScriptBlockDocValuesReader.java
{ "start": 888, "end": 3050 }
class ____ extends DocValuesBlockLoader { private final LongFieldScript.LeafFactory factory; LongScriptBlockLoader(LongFieldScript.LeafFactory factory) { this.factory = factory; } @Override public Builder builder(BlockFactory factory, int expectedCount) { return factory.longs(expectedCount); } @Override public AllReader reader(LeafReaderContext context) throws IOException { return new LongScriptBlockDocValuesReader(factory.newInstance(context)); } } private final LongFieldScript script; private int docId; LongScriptBlockDocValuesReader(LongFieldScript script) { this.script = script; } @Override public int docId() { return docId; } @Override public BlockLoader.Block read(BlockLoader.BlockFactory factory, BlockLoader.Docs docs, int offset, boolean nullsFiltered) throws IOException { // Note that we don't pre-sort our output so we can't use longsFromDocValues try (BlockLoader.LongBuilder builder = factory.longs(docs.count() - offset)) { for (int i = offset; i < docs.count(); i++) { read(docs.get(i), builder); } return builder.build(); } } @Override public void read(int docId, BlockLoader.StoredFields storedFields, BlockLoader.Builder builder) throws IOException { this.docId = docId; read(docId, (BlockLoader.LongBuilder) builder); } private void read(int docId, BlockLoader.LongBuilder builder) { script.runForDoc(docId); switch (script.count()) { case 0 -> builder.appendNull(); case 1 -> builder.appendLong(script.values()[0]); default -> { builder.beginPositionEntry(); for (int i = 0; i < script.count(); i++) { builder.appendLong(script.values()[i]); } builder.endPositionEntry(); } } } @Override public String toString() { return "ScriptLongs"; } }
LongScriptBlockLoader
java
google__guice
extensions/assistedinject/src/com/google/inject/assistedinject/FactoryProvider.java
{ "start": 7671, "end": 9203 }
interface ____ the passed implementation type. Errors errors = new Errors(); Key<?> implementationKey = Key.get(implementationType); try { for (Method method : factoryType.getRawType().getMethods()) { Key<?> returnType = getKey(factoryType.getReturnType(method), method, method.getAnnotations(), errors); if (!implementationKey.equals(returnType)) { collector.addBinding(returnType, implementationType); } } } catch (ErrorsException e) { throw new ConfigurationException(e.getErrors().getMessages()); } return new FactoryProvider2<F>(Key.get(factoryType), collector, /* userLookups= */ null); } } private FactoryProvider( TypeLiteral<F> factoryType, TypeLiteral<?> implementationType, Map<Method, AssistedConstructor<?>> factoryMethodToConstructor) { this.factoryType = factoryType; this.implementationType = implementationType; this.factoryMethodToConstructor = factoryMethodToConstructor; checkDeclaredExceptionsMatch(); } @Inject void setInjectorAndCheckUnboundParametersAreInjectable(Injector injector) { this.injector = injector; for (AssistedConstructor<?> c : factoryMethodToConstructor.values()) { for (Parameter p : c.getAllParameters()) { if (!p.isProvidedByFactory() && !paramCanBeInjected(p, injector)) { // this is lame - we're not using the proper mechanism to add an // error to the injector. Throughout this
to
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/upgrade/HttpUpgradeCheckHeaderMergingTest.java
{ "start": 3053, "end": 3432 }
class ____ implements HttpUpgradeCheck { @Override public Uni<CheckResult> perform(HttpUpgradeContext context) { return CheckResult.permitUpgrade( Map.of("k3", List.of("val1", "val2", "val3", "val4"), "k2", List.of("val2", "val3", "val4"))); } } @WebSocket(path = "/headers") public static
Header3HttpUpgradeCheck
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoBeanContextCustomizerEqualityTests.java
{ "start": 3300, "end": 3401 }
class ____ { @MockitoBean(answers = RETURNS_MOCKS) private String exampleService; } static
Case3
java
apache__flink
flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/CEP.java
{ "start": 960, "end": 1101 }
class ____ complex event processing. * * <p>Methods which transform a {@link DataStream} into a {@link PatternStream} to do CEP. */ public
for
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SoftDeleteMappingImpl.java
{ "start": 2263, "end": 11685 }
class ____ implements SoftDeleteMapping { private final NavigableRole navigableRole; private final SoftDeletableModelPart softDeletable; private final SoftDeleteType strategy; private final String columnName; private final String tableName; private final JdbcMapping jdbcMapping; private final Object deletionIndicator; // TIMESTAMP private final String currentTimestampFunctionName; private final SelfRenderingFunctionSqlAstExpression<?> currentTimestampFunctionExpression; // ACTIVE/DELETED private final Object deletedLiteralValue; private final String deletedLiteralText; private final Object nonDeletedLiteralValue; private final String nonDeletedLiteralText; public SoftDeleteMappingImpl( SoftDeletableModelPart softDeletable, SoftDeletable bootMapping, String tableName, MappingModelCreationProcess modelCreationProcess) { assert bootMapping.getSoftDeleteColumn() != null; this.softDeletable = softDeletable; navigableRole = softDeletable.getNavigableRole().append( ROLE_NAME ); strategy = bootMapping.getSoftDeleteStrategy(); final var dialect = modelCreationProcess.getCreationContext().getDialect(); final var softDeleteColumn = bootMapping.getSoftDeleteColumn(); final var columnValue = (BasicValue) softDeleteColumn.getValue(); final var resolution = columnValue.resolve(); this.tableName = tableName; columnName = softDeleteColumn.getName(); jdbcMapping = resolution.getJdbcMapping(); if ( bootMapping.getSoftDeleteStrategy() == SoftDeleteType.TIMESTAMP ) { currentTimestampFunctionName = dialect.currentTimestamp(); final var currentTimestampFunctionType = modelCreationProcess.getCreationContext().getTypeConfiguration() .getBasicTypeForJavaType( Instant.class ); final var currentTimestampFunction = new CurrentFunction( currentTimestampFunctionName, currentTimestampFunctionName, currentTimestampFunctionType ); currentTimestampFunctionExpression = new SelfRenderingFunctionSqlAstExpression<>( currentTimestampFunctionName, currentTimestampFunction, emptyList(), currentTimestampFunctionType, softDeletable ); deletionIndicator = currentTimestampFunctionName; deletedLiteralValue = null; deletedLiteralText = null; nonDeletedLiteralValue = null; nonDeletedLiteralText = null; } else { //noinspection unchecked final var converter = (BasicValueConverter<Boolean, ?>) resolution.getValueConverter(); //noinspection unchecked final JdbcLiteralFormatter<Object> literalFormatter = resolution.getJdbcMapping().getJdbcLiteralFormatter(); if ( converter == null ) { // the database column is BIT or BOOLEAN: pass-thru deletedLiteralValue = true; nonDeletedLiteralValue = false; } else { deletedLiteralValue = converter.toRelationalValue( true ); nonDeletedLiteralValue = converter.toRelationalValue( false ); } deletedLiteralText = literalFormatter.toJdbcLiteral( deletedLiteralValue, dialect, null ); nonDeletedLiteralText = literalFormatter.toJdbcLiteral( nonDeletedLiteralValue, dialect, null ); deletionIndicator = deletedLiteralValue; currentTimestampFunctionName = null; currentTimestampFunctionExpression = null; } } @Override public SoftDeleteType getSoftDeleteStrategy() { return strategy; } @Override public String getColumnName() { return columnName; } @Override public String getTableName() { return tableName; } @Override public String getWriteExpression() { return strategy == SoftDeleteType.TIMESTAMP ? null : nonDeletedLiteralText; } public Object getDeletionIndicator() { return deletionIndicator; } @Override public Assignment createSoftDeleteAssignment(TableReference tableReference) { final var columnReference = new ColumnReference( tableReference, this ); final var valueExpression = strategy == SoftDeleteType.TIMESTAMP ? currentTimestampFunctionExpression : new JdbcLiteral<>( deletedLiteralValue, jdbcMapping ); return new Assignment( columnReference, valueExpression ); } @Override public Predicate createNonDeletedRestriction(TableReference tableReference) { final var softDeleteColumn = new ColumnReference( tableReference, this ); if ( strategy == SoftDeleteType.TIMESTAMP ) { return new NullnessPredicate( softDeleteColumn, false, jdbcMapping ); } else { final JdbcLiteral<?> notDeletedLiteral = new JdbcLiteral<>( nonDeletedLiteralValue, jdbcMapping ); return new ComparisonPredicate( softDeleteColumn, EQUAL, notDeletedLiteral ); } } @Override public Predicate createNonDeletedRestriction(TableReference tableReference, SqlExpressionResolver expressionResolver) { final var softDeleteColumn = expressionResolver.resolveSqlExpression( tableReference, this ); if ( strategy == SoftDeleteType.TIMESTAMP ) { return new NullnessPredicate( softDeleteColumn, false, jdbcMapping ); } else { return new ComparisonPredicate( softDeleteColumn, EQUAL, new JdbcLiteral<>( nonDeletedLiteralValue, jdbcMapping ) ); } } @Override public ColumnValueBinding createNonDeletedValueBinding(ColumnReference softDeleteColumnReference) { final var nonDeletedFragment = strategy == SoftDeleteType.TIMESTAMP ? new ColumnWriteFragment( null, emptyList(), this ) : new ColumnWriteFragment( nonDeletedLiteralText, emptyList(), this ); return new ColumnValueBinding( softDeleteColumnReference, nonDeletedFragment ); } @Override public ColumnValueBinding createDeletedValueBinding(ColumnReference softDeleteColumnReference) { final ColumnWriteFragment deletedFragment = strategy == SoftDeleteType.TIMESTAMP ? new ColumnWriteFragment( currentTimestampFunctionName, emptyList(), this ) : new ColumnWriteFragment( deletedLiteralText, emptyList(), this ); return new ColumnValueBinding( softDeleteColumnReference, deletedFragment ); } @Override public JdbcMapping getJdbcMapping() { return jdbcMapping; } @Override public String getPartName() { return ROLE_NAME; } @Override public NavigableRole getNavigableRole() { return navigableRole; } @Override public int forEachJdbcType(int offset, IndexedConsumer<JdbcMapping> action) { action.accept( offset, jdbcMapping ); return 1; } @Override public Object disassemble(Object value, SharedSessionContractImplementor session) { return value; } @Override public void addToCacheKey(MutableCacheKeyBuilder cacheKey, Object value, SharedSessionContractImplementor session) { } @Override public <X, Y> int forEachDisassembledJdbcValue( Object value, int offset, X x, Y y, JdbcValuesBiConsumer<X, Y> valuesConsumer, SharedSessionContractImplementor session) { valuesConsumer.consume( offset, x, y, value, getJdbcMapping() ); return 1; } @Override public MappingType getPartMappingType() { return jdbcMapping; } @Override public JavaType<?> getJavaType() { return jdbcMapping.getMappedJavaType(); } @Override public boolean hasPartitionedSelectionMapping() { return false; } @Override public <T> DomainResult<T> createDomainResult( NavigablePath navigablePath, TableGroup tableGroup, String resultVariable, DomainResultCreationState creationState) { final var sqlSelection = resolveSqlSelection( navigablePath, tableGroup, creationState ); return new BasicResult<>( sqlSelection.getValuesArrayPosition(), resultVariable, getJdbcMapping(), navigablePath, false, !sqlSelection.isVirtual() ); } private SqlSelection resolveSqlSelection( NavigablePath navigablePath, TableGroup tableGroup, DomainResultCreationState creationState) { final var indicatorTable = softDeletable.getSoftDeleteTableDetails(); final var tableReference = tableGroup.resolveTableReference( navigablePath.getRealParent(), indicatorTable.getTableName() ); final var expressionResolver = creationState.getSqlAstCreationState().getSqlExpressionResolver(); return expressionResolver.resolveSqlSelection( expressionResolver.resolveSqlExpression( tableReference, this ), getJavaType(), null, creationState.getSqlAstCreationState().getCreationContext().getMappingMetamodel().getTypeConfiguration() ); } @Override public void applySqlSelections( NavigablePath navigablePath, TableGroup tableGroup, DomainResultCreationState creationState) { resolveSqlSelection( navigablePath, tableGroup, creationState ); } @Override public void applySqlSelections( NavigablePath navigablePath, TableGroup tableGroup, DomainResultCreationState creationState, BiConsumer<SqlSelection, JdbcMapping> selectionConsumer) { final var sqlSelection = resolveSqlSelection( navigablePath, tableGroup, creationState ); selectionConsumer.accept( sqlSelection, getJdbcMapping() ); } @Override public <X, Y> int breakDownJdbcValues( Object domainValue, int offset, X x, Y y, JdbcValueBiConsumer<X, Y> valueConsumer, SharedSessionContractImplementor session) { valueConsumer.consume( offset, x, y, disassemble( domainValue, session ), this ); return 1; } @Override public EntityMappingType findContainingEntityMapping() { return softDeletable.findContainingEntityMapping(); } @Override public String toString() { return "SoftDeleteMapping(" + tableName + "." + columnName + ")"; } }
SoftDeleteMappingImpl
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/typeutils/DecimalSerializerTest.java
{ "start": 1025, "end": 1714 }
class ____ extends SerializerTestBase<DecimalData> { @Override protected DecimalDataSerializer createSerializer() { return new DecimalDataSerializer(5, 2); } @Override protected int getLength() { return -1; } @Override protected Class<DecimalData> getTypeClass() { return DecimalData.class; } @Override protected DecimalData[] getTestData() { return new DecimalData[] { DecimalData.fromUnscaledLong(1, 5, 2), DecimalData.fromUnscaledLong(2, 5, 2), DecimalData.fromUnscaledLong(3, 5, 2), DecimalData.fromUnscaledLong(4, 5, 2) }; } }
DecimalSerializerTest
java
apache__flink
flink-python/src/test/java/org/apache/flink/python/env/process/ProcessPythonEnvironmentManagerTest.java
{ "start": 2741, "end": 19954 }
class ____ { private static String tmpDir; private static boolean isUnix; @BeforeAll static void prepareTempDirectory() throws IOException { File tmpFile = File.createTempFile("process_environment_manager_test", ""); if (tmpFile.delete() && tmpFile.mkdirs()) { tmpDir = tmpFile.getAbsolutePath(); } else { throw new IOException( "Create temp directory: " + tmpFile.getAbsolutePath() + " failed!"); } for (int i = 0; i < 6; i++) { File distributedFile = new File(tmpDir, "file" + i); try (FileOutputStream out = new FileOutputStream(distributedFile)) { out.write(i); } } for (int i = 0; i < 2; i++) { File distributedDirectory = new File(tmpDir, "dir" + i); if (distributedDirectory.mkdirs()) { for (int j = 0; j < 2; j++) { File fileInDirs = new File(tmpDir, "dir" + i + File.separator + "file" + j); try (FileOutputStream out = new FileOutputStream(fileInDirs)) { out.write(i); out.write(j); } } } else { throw new IOException( "Create temp dir: " + distributedDirectory.getAbsolutePath() + " failed!"); } } isUnix = OperatingSystem.isFreeBSD() || OperatingSystem.isLinux() || OperatingSystem.isMac() || OperatingSystem.isSolaris(); for (int i = 0; i < 2; i++) { File zipFile = new File(tmpDir, "zip" + i); try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(zipFile))) { ZipArchiveEntry zipfile0 = new ZipArchiveEntry("zipDir" + i + "/zipfile0"); zipfile0.setUnixMode(0711); zipOut.putArchiveEntry(zipfile0); zipOut.write(new byte[] {1, 1, 1, 1, 1}); zipOut.closeArchiveEntry(); ZipArchiveEntry zipfile1 = new ZipArchiveEntry("zipDir" + i + "/zipfile1"); zipfile1.setUnixMode(0644); zipOut.putArchiveEntry(zipfile1); zipOut.write(new byte[] {2, 2, 2, 2, 2}); zipOut.closeArchiveEntry(); } File zipExpected = new File(String.join(File.separator, tmpDir, "zipExpected" + i, "zipDir" + i)); if (!zipExpected.mkdirs()) { throw new IOException( "Create temp dir: " + zipExpected.getAbsolutePath() + " failed!"); } File zipfile0 = new File(zipExpected, "zipfile0"); try (FileOutputStream out = new FileOutputStream(zipfile0)) { out.write(new byte[] {1, 1, 1, 1, 1}); } File zipfile1 = new File(zipExpected, "zipfile1"); try (FileOutputStream out = new FileOutputStream(zipfile1)) { out.write(new byte[] {2, 2, 2, 2, 2}); } if (isUnix) { if (!(zipfile0.setReadable(true, true) && zipfile0.setWritable(true, true) && zipfile0.setExecutable(true))) { throw new IOException( "Set unixmode 711 to temp file: " + zipfile0.getAbsolutePath() + "failed!"); } if (!(zipfile1.setReadable(true) && zipfile1.setWritable(true, true) && zipfile1.setExecutable(false))) { throw new IOException( "Set unixmode 644 to temp file: " + zipfile1.getAbsolutePath() + "failed!"); } } } } @AfterAll static void cleanTempDirectory() { if (tmpDir != null) { FileUtils.deleteDirectoryQuietly(new File(tmpDir)); tmpDir = null; } } @Test void testPythonFiles() throws Exception { // use LinkedHashMap to preserve the path order in environment variable Map<String, String> pythonFiles = new LinkedHashMap<>(); pythonFiles.put(String.join(File.separator, tmpDir, "zip0"), "test_zip.zip"); pythonFiles.put(String.join(File.separator, tmpDir, "file1"), "test_file1.py"); pythonFiles.put(String.join(File.separator, tmpDir, "file2"), "test_file2.egg"); pythonFiles.put(String.join(File.separator, tmpDir, "dir0"), "test_dir"); PythonDependencyInfo dependencyInfo = new PythonDependencyInfo(pythonFiles, null, null, new HashMap<>(), "python"); try (ProcessPythonEnvironmentManager environmentManager = createBasicPythonEnvironmentManager(dependencyInfo)) { environmentManager.open(); String baseDir = environmentManager.getBaseDirectory(); Map<String, String> environmentVariable = environmentManager.getPythonEnv(); String[] expectedUserPythonPaths = new String[] { String.join(File.separator, baseDir, PYTHON_FILES_DIR, "zip0", "test_zip"), String.join(File.separator, baseDir, PYTHON_FILES_DIR, "file1"), String.join( File.separator, baseDir, PYTHON_FILES_DIR, "file2", "test_file2.egg"), String.join(File.separator, baseDir, PYTHON_FILES_DIR, "dir0", "test_dir") }; String expectedPythonPath = String.join(File.pathSeparator, expectedUserPythonPaths); assertThat(environmentVariable.get("PYTHONPATH")).isEqualTo(expectedPythonPath); assertFileEquals( new File(String.join(File.separator, tmpDir, "file1")), new File( String.join( File.separator, baseDir, PYTHON_FILES_DIR, "file1", "test_file1.py"))); assertFileEquals( new File(String.join(File.separator, tmpDir, "zipExpected0")), new File( String.join( File.separator, baseDir, PYTHON_FILES_DIR, "zip0", "test_zip"))); assertFileEquals( new File(String.join(File.separator, tmpDir, "file2")), new File( String.join( File.separator, baseDir, PYTHON_FILES_DIR, "file2", "test_file2.egg"))); assertFileEquals( new File(String.join(File.separator, tmpDir, "dir0")), new File( String.join( File.separator, baseDir, PYTHON_FILES_DIR, "dir0", "test_dir"))); } } @Test void testRequirements() throws Exception { PythonDependencyInfo dependencyInfo = new PythonDependencyInfo( new HashMap<>(), String.join(File.separator, tmpDir, "file0"), String.join(File.separator, tmpDir, "dir0"), new HashMap<>(), "python"); try (ProcessPythonEnvironmentManager environmentManager = createBasicPythonEnvironmentManager(dependencyInfo)) { File baseDirectory = new File(tmpDir, "python-dist-" + UUID.randomUUID().toString()); if (!baseDirectory.mkdirs()) { throw new IOException( "Could not find a unique directory name in '" + tmpDir + "' for storing the generated files of python dependency."); } String tmpBase = baseDirectory.getAbsolutePath(); Map<String, String> environmentVariable = environmentManager.constructEnvironmentVariables(tmpBase); Map<String, String> expected = new HashMap<>(); expected.put("python", "python"); expected.put("BOOT_LOG_DIR", tmpBase); expected.put(PYFLINK_GATEWAY_DISABLED, "true"); expected.put(PYTHON_REQUIREMENTS_FILE, String.join(File.separator, tmpDir, "file0")); expected.put(PYTHON_REQUIREMENTS_CACHE, String.join(File.separator, tmpDir, "dir0")); expected.put( PYTHON_REQUIREMENTS_INSTALL_DIR, String.join(File.separator, tmpBase, PYTHON_REQUIREMENTS_DIR)); assertThat(environmentVariable).isEqualTo(expected); } } @Test void testArchives() throws Exception { // use LinkedHashMap to preserve the file order in python working directory Map<String, String> archives = new LinkedHashMap<>(); archives.put(String.join(File.separator, tmpDir, "zip0"), "py27.zip"); archives.put(String.join(File.separator, tmpDir, "zip1"), "py37"); PythonDependencyInfo dependencyInfo = new PythonDependencyInfo(new HashMap<>(), null, null, archives, "python"); try (ProcessPythonEnvironmentManager environmentManager = createBasicPythonEnvironmentManager(dependencyInfo)) { environmentManager.open(); String tmpBase = environmentManager.getBaseDirectory(); Map<String, String> environmentVariable = environmentManager.getPythonEnv(); Map<String, String> expected = getBasicExpectedEnv(environmentManager); expected.put( PYTHON_WORKING_DIR, String.join(File.separator, tmpBase, PYTHON_ARCHIVES_DIR)); assertThat(environmentVariable).isEqualTo(expected); assertFileEquals( new File(String.join(File.separator, tmpDir, "zipExpected0")), new File(String.join(File.separator, tmpBase, PYTHON_ARCHIVES_DIR, "py27.zip")), true); assertFileEquals( new File(String.join(File.separator, tmpDir, "zipExpected1")), new File(String.join(File.separator, tmpBase, PYTHON_ARCHIVES_DIR, "py37")), true); } } @Test void testPythonExecutable() throws Exception { PythonDependencyInfo dependencyInfo = new PythonDependencyInfo( new HashMap<>(), null, null, new HashMap<>(), "/usr/local/bin/python"); try (ProcessPythonEnvironmentManager environmentManager = createBasicPythonEnvironmentManager(dependencyInfo)) { environmentManager.open(); Map<String, String> environmentVariable = environmentManager.getPythonEnv(); Map<String, String> expected = getBasicExpectedEnv(environmentManager); expected.put("python", "/usr/local/bin/python"); assertThat(environmentVariable).isEqualTo(expected); } } @Test void testCreateRetrievalToken() throws Exception { PythonDependencyInfo dependencyInfo = new PythonDependencyInfo(new HashMap<>(), null, null, new HashMap<>(), "python"); Map<String, String> sysEnv = new HashMap<>(); sysEnv.put("FLINK_HOME", "/flink"); try (ProcessPythonEnvironmentManager environmentManager = new ProcessPythonEnvironmentManager( dependencyInfo, new String[] {tmpDir}, sysEnv, new JobID())) { environmentManager.open(); String retrievalToken = environmentManager.createRetrievalToken(); File retrievalTokenFile = new File(retrievalToken); byte[] content = new byte[(int) retrievalTokenFile.length()]; try (DataInputStream input = new DataInputStream(new FileInputStream(retrievalToken))) { input.readFully(content); } assertThat(new String(content)).isEqualTo("{\"manifest\": {}}"); } } @Test void testSetLogDirectory() throws Exception { PythonDependencyInfo dependencyInfo = new PythonDependencyInfo(new HashMap<>(), null, null, new HashMap<>(), "python"); try (ProcessPythonEnvironmentManager environmentManager = new ProcessPythonEnvironmentManager( dependencyInfo, new String[] {tmpDir}, new HashMap<>(), new JobID())) { environmentManager.open(); Map<String, String> env = environmentManager.constructEnvironmentVariables( environmentManager.getBaseDirectory()); Map<String, String> expected = getBasicExpectedEnv(environmentManager); expected.put("BOOT_LOG_DIR", environmentManager.getBaseDirectory()); assertThat(env).isEqualTo(expected); } } @Test void testOpenClose() throws Exception { PythonDependencyInfo dependencyInfo = new PythonDependencyInfo(new HashMap<>(), null, null, new HashMap<>(), "python"); try (ProcessPythonEnvironmentManager environmentManager = createBasicPythonEnvironmentManager(dependencyInfo)) { environmentManager.open(); environmentManager.createRetrievalToken(); String tmpBase = environmentManager.getBaseDirectory(); assertThat(new File(tmpBase)).isDirectory(); environmentManager.close(); assertThat(new File(tmpBase)).doesNotExist(); } } private static void assertFileEquals(File expectedFile, File actualFile) throws IOException, NoSuchAlgorithmException { assertFileEquals(expectedFile, actualFile, false); } private static void assertFileEquals(File expectedFile, File actualFile, boolean checkUnixMode) throws IOException, NoSuchAlgorithmException { assertThat(actualFile).exists(); assertThat(expectedFile).exists(); if (expectedFile.getAbsolutePath().equals(actualFile.getAbsolutePath())) { return; } if (isUnix && checkUnixMode) { Set<PosixFilePermission> expectedPerm = Files.getPosixFilePermissions(Paths.get(expectedFile.toURI())); Set<PosixFilePermission> actualPerm = Files.getPosixFilePermissions(Paths.get(actualFile.toURI())); assertThat(actualPerm).isEqualTo(expectedPerm); } final BasicFileAttributes expectedFileAttributes = Files.readAttributes(expectedFile.toPath(), BasicFileAttributes.class); if (expectedFileAttributes.isDirectory()) { assertThat(actualFile).isDirectory(); String[] expectedSubFiles = expectedFile.list(); assertThat(actualFile.list()).isEqualTo(expectedSubFiles); if (expectedSubFiles != null) { for (String fileName : expectedSubFiles) { assertFileEquals( new File(expectedFile.getAbsolutePath(), fileName), new File(actualFile.getAbsolutePath(), fileName)); } } } else { assertThat(actualFile).hasSize(expectedFileAttributes.size()); if (expectedFileAttributes.size() > 0) { assertThat(org.apache.commons.io.FileUtils.contentEquals(expectedFile, actualFile)) .isTrue(); } } } private static Map<String, String> getBasicExpectedEnv( ProcessPythonEnvironmentManager environmentManager) { Map<String, String> map = new HashMap<>(); String tmpBase = environmentManager.getBaseDirectory(); map.put("python", "python"); map.put("BOOT_LOG_DIR", tmpBase); map.put(PYFLINK_GATEWAY_DISABLED, "true"); return map; } private static ProcessPythonEnvironmentManager createBasicPythonEnvironmentManager( PythonDependencyInfo dependencyInfo) { return new ProcessPythonEnvironmentManager( dependencyInfo, new String[] {tmpDir}, new HashMap<>(), new JobID()); } }
ProcessPythonEnvironmentManagerTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/histogram/InternalHistogram.java
{ "start": 2003, "end": 2190 }
class ____ extends InternalMultiBucketAggregation<InternalHistogram, InternalHistogram.Bucket> implements Histogram, HistogramFactory { public static
InternalHistogram
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_have_Test.java
{ "start": 1092, "end": 1554 }
class ____ extends ObjectArrayAssertBaseTest { private Condition<Object> condition; @BeforeEach void before() { condition = new TestCondition<>(); } @Override protected ObjectArrayAssert<Object> invoke_api_method() { return assertions.doNotHave(condition); } @Override protected void verify_internal_effects() { verify(arrays).assertDoNotHave(getInfo(assertions), getActual(assertions), condition); } }
ObjectArrayAssert_have_Test
java
bumptech__glide
samples/flickr/src/main/java/com/bumptech/glide/samples/flickr/FlickrPhotoGrid.java
{ "start": 5135, "end": 7083 }
class ____ extends RecyclerView.Adapter<PhotoViewHolder> implements ListPreloader.PreloadModelProvider<Photo> { private final LayoutInflater inflater; private List<Photo> photos = Collections.emptyList(); PhotoAdapter() { this.inflater = LayoutInflater.from(getActivity()); } void setPhotos(List<Photo> photos) { this.photos = photos; notifyDataSetChanged(); } @Override public int getItemViewType(int position) { return 0; } @Override public PhotoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.flickr_photo_grid_item, parent, false); ViewGroup.LayoutParams params = view.getLayoutParams(); params.width = photoSize; params.height = photoSize; return new PhotoViewHolder(view); } @Override public void onBindViewHolder(PhotoViewHolder holder, int position) { final Photo current = photos.get(position); fullRequest .load(current) .thumbnail(thumbnail ? thumbnailRequest.load(current) : null) .into(holder.imageView); holder.imageView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = FullscreenActivity.getIntent(getActivity(), current); startActivity(intent); } }); } @Override public long getItemId(int i) { return RecyclerView.NO_ID; } @Override public int getItemCount() { return photos.size(); } @NonNull @Override public List<Photo> getPreloadItems(int position) { return photos.subList(position, position + 1); } @Nullable @Override public RequestBuilder<Drawable> getPreloadRequestBuilder(@NonNull Photo item) { return preloadRequest.load(item); } } private static final
PhotoAdapter
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ext/javatime/ser/LocalTimeSerTest.java
{ "start": 1175, "end": 1374 }
class ____ extends DateTimeTestBase { private final ObjectMapper MAPPER = newMapper(); private final ObjectWriter writer = MAPPER.writer(); // [modules-java8#115] static
LocalTimeSerTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/contextual/ContextualDeserializationTest.java
{ "start": 2110, "end": 2219 }
class ____ { @Name("array") public StringValue[] beans; } static
ContextualArrayBean
java
netty__netty
handler/src/test/java/io/netty/handler/ssl/JdkSslEngineTest.java
{ "start": 14461, "end": 14702 }
class ____ extends RuntimeException { private static final long serialVersionUID = 9214869217774035223L; SkipTestException(String message) { super(message); } } private static final
SkipTestException
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/fields/RecursiveComparisonAssert_isEqualTo_ignoringFieldsOfTypesMatchingRegexes_Test.java
{ "start": 5123, "end": 5503 }
class ____ { private final Number number; NumberHolder(final Number number) { this.number = number; } public Number getNumber() { return number; } @Override public String toString() { return number.toString(); } } @Test void should_pass_when_fields_with_given_types_are_ignored_on_unordered_collections() {
NumberHolder
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/MethodMatcher.java
{ "start": 2851, "end": 4681 }
interface ____ { /** * Perform static checking to determine whether the given method matches. * <p>If this method returns {@code false} or if {@link #isRuntime()} * returns {@code false}, no runtime check (i.e. no * {@link #matches(Method, Class, Object[])} call) will be made. * @param method the candidate method * @param targetClass the target class * @return whether this method matches statically */ boolean matches(Method method, Class<?> targetClass); /** * Is this {@code MethodMatcher} dynamic, that is, must a final check be made * via the {@link #matches(Method, Class, Object[])} method at runtime even * if {@link #matches(Method, Class)} returns {@code true}? * <p>Can be invoked when an AOP proxy is created, and need not be invoked * again before each method invocation. * @return whether a runtime match via {@link #matches(Method, Class, Object[])} * is required if static matching passed */ boolean isRuntime(); /** * Check whether there is a runtime (dynamic) match for this method, which * must have matched statically. * <p>This method is invoked only if {@link #matches(Method, Class)} returns * {@code true} for the given method and target class, and if * {@link #isRuntime()} returns {@code true}. * <p>Invoked immediately before potential running of the advice, after any * advice earlier in the advice chain has run. * @param method the candidate method * @param targetClass the target class * @param args arguments to the method * @return whether there's a runtime match * @see #matches(Method, Class) */ boolean matches(Method method, Class<?> targetClass, @Nullable Object... args); /** * Canonical instance of a {@code MethodMatcher} that matches all methods. */ MethodMatcher TRUE = TrueMethodMatcher.INSTANCE; }
MethodMatcher
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/external/http/sender/RequestExecutorService.java
{ "start": 4704, "end": 20896 }
interface ____ { RateLimiter create(double accumulatedTokensLimit, double tokensPerTimeUnit, TimeUnit unit); } // TODO: for later (after 8.18) // TODO: pass in divisor to RateLimiterCreator // TODO: another map for service/task-type-key -> set of RateLimitingEndpointHandler (used for updates; update divisor and then update // all endpoint handlers) // TODO: one map for service/task-type-key -> divisor (this gets also read when we create an inference endpoint) // TODO: divisor value read/writes need to be synchronized in some way // default for testing static final RateLimiterCreator DEFAULT_RATE_LIMIT_CREATOR = RateLimiter::new; private static final Logger logger = LogManager.getLogger(RequestExecutorService.class); private static final TimeValue RATE_LIMIT_GROUP_CLEANUP_INTERVAL = TimeValue.timeValueDays(1); private final ConcurrentMap<Object, RateLimitingEndpointHandler> rateLimitGroupings = new ConcurrentHashMap<>(); private final AtomicInteger rateLimitDivisor = new AtomicInteger(1); private final ThreadPool threadPool; private final CountDownLatch startupLatch; private final CountDownLatch terminationLatch = new CountDownLatch(1); private final RequestSender requestSender; private final RequestExecutorServiceSettings settings; private final Clock clock; private final AtomicBoolean shutdown = new AtomicBoolean(false); private final AdjustableCapacityBlockingQueue.QueueCreator<RejectableTask> queueCreator; private final RateLimiterCreator rateLimiterCreator; private final AtomicReference<Scheduler.Cancellable> cancellableCleanupTask = new AtomicReference<>(); private final AtomicBoolean started = new AtomicBoolean(false); private final AdjustableCapacityBlockingQueue<RejectableTask> requestQueue; private volatile Future<?> requestQueueTask; public RequestExecutorService( ThreadPool threadPool, @Nullable CountDownLatch startupLatch, RequestExecutorServiceSettings settings, RequestSender requestSender ) { this(threadPool, DEFAULT_QUEUE_CREATOR, startupLatch, settings, requestSender, Clock.systemUTC(), DEFAULT_RATE_LIMIT_CREATOR); } public RequestExecutorService( ThreadPool threadPool, AdjustableCapacityBlockingQueue.QueueCreator<RejectableTask> queueCreator, @Nullable CountDownLatch startupLatch, RequestExecutorServiceSettings settings, RequestSender requestSender, Clock clock, RateLimiterCreator rateLimiterCreator ) { this.threadPool = Objects.requireNonNull(threadPool); this.queueCreator = Objects.requireNonNull(queueCreator); this.startupLatch = startupLatch; this.requestSender = Objects.requireNonNull(requestSender); this.settings = Objects.requireNonNull(settings); this.clock = Objects.requireNonNull(clock); this.rateLimiterCreator = Objects.requireNonNull(rateLimiterCreator); this.requestQueue = new AdjustableCapacityBlockingQueue<>(queueCreator, settings.getQueueCapacity()); } public void shutdown() { if (shutdown.compareAndSet(false, true)) { if (requestQueueTask != null) { // Wakes up the queue in processRequestQueue requestQueue.offer(NOOP_TASK); } if (cancellableCleanupTask.get() != null) { logger.debug(() -> "Stopping clean up thread"); cancellableCleanupTask.get().cancel(); } } } public boolean isShutdown() { return shutdown.get(); } public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return terminationLatch.await(timeout, unit); } public boolean isTerminated() { return terminationLatch.getCount() == 0; } public int queueSize() { return requestQueue.size() + rateLimitGroupings.values().stream().mapToInt(RateLimitingEndpointHandler::queueSize).sum(); } /** * Begin servicing tasks. * <p> * <b>Note: This should only be called once for the life of the object.</b> * </p> */ public void start() { try { assert started.get() == false : "start() can only be called once"; started.set(true); startCleanupTask(); startRequestQueueTask(); signalStartInitiated(); startHandlingRateLimitedTasks(); } catch (Exception e) { logger.warn("Failed to start request executor", e); cleanup(CleanupStrategy.RATE_LIMITED_REQUEST_QUEUES_ONLY); } } private void signalStartInitiated() { if (startupLatch != null) { startupLatch.countDown(); } } private void startCleanupTask() { assert cancellableCleanupTask.get() == null : "The clean up task can only be set once"; cancellableCleanupTask.set(startCleanupThread(RATE_LIMIT_GROUP_CLEANUP_INTERVAL)); } private void startRequestQueueTask() { assert requestQueueTask == null : "The request queue can only be started once"; requestQueueTask = threadPool.executor(UTILITY_THREAD_POOL_NAME).submit(this::processRequestQueue); } private Scheduler.Cancellable startCleanupThread(TimeValue interval) { logger.debug(() -> Strings.format("Clean up task scheduled with interval [%s]", interval)); return threadPool.scheduleWithFixedDelay(this::removeStaleGroupings, interval, threadPool.executor(UTILITY_THREAD_POOL_NAME)); } // default for testing void removeStaleGroupings() { var now = Instant.now(clock); for (var iter = rateLimitGroupings.values().iterator(); iter.hasNext();) { var endpoint = iter.next(); // if the current time is after the last time the endpoint enqueued a request + allowed stale period then we'll remove it if (now.isAfter(endpoint.timeOfLastEnqueue().plus(settings.getRateLimitGroupStaleDuration()))) { endpoint.close(); iter.remove(); } } } private void scheduleNextHandleTasks(TimeValue timeToWait) { if (shutdown.get()) { logger.debug("Shutdown requested while scheduling next handle task call, cleaning up"); cleanup(CleanupStrategy.RATE_LIMITED_REQUEST_QUEUES_ONLY); return; } threadPool.schedule(this::startHandlingRateLimitedTasks, timeToWait, threadPool.executor(UTILITY_THREAD_POOL_NAME)); } private void processRequestQueue() { try { while (isShutdown() == false) { var task = requestQueue.take(); if (task == NOOP_TASK) { if (isShutdown()) { logger.debug("Shutdown requested, exiting request queue processing"); break; } // Skip processing NoopTask continue; } if (isShutdown()) { logger.debug("Shutdown requested while handling request tasks, cleaning up"); rejectNonRateLimitedRequest(task); break; } executeTaskImmediately(task); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.debug("Inference request queue interrupted, exiting"); } catch (Exception e) { logger.error("Unexpected error processing request queue, terminating", e); } finally { cleanup(CleanupStrategy.REQUEST_QUEUE_ONLY); } } private void executeTaskImmediately(RejectableTask task) { try { task.getRequestManager() .execute(task.getInferenceInputs(), requestSender, task.getRequestCompletedFunction(), task.getListener()); } catch (Exception e) { logger.warn( format("Failed to execute fast-path request for inference id [%s]", task.getRequestManager().inferenceEntityId()), e ); var rejectionException = new EsRejectedExecutionException( format("Failed to execute request for inference id [%s]", task.getRequestManager().inferenceEntityId()), false ); rejectionException.initCause(e); task.onRejection(rejectionException); } } // visible for testing void submitTaskToRateLimitedExecutionPath(RequestTask task) { var requestManager = task.getRequestManager(); var endpoint = rateLimitGroupings.computeIfAbsent(requestManager.rateLimitGrouping(), key -> { var endpointHandler = new RateLimitingEndpointHandler( Integer.toString(requestManager.rateLimitGrouping().hashCode()), queueCreator, settings, requestSender, clock, requestManager.rateLimitSettings(), this::isShutdown, rateLimiterCreator, rateLimitDivisor.get() ); endpointHandler.init(); return endpointHandler; }); endpoint.enqueue(task); } private static boolean isEmbeddingsIngestInput(InferenceInputs inputs) { return inputs instanceof EmbeddingsInput embeddingsInput && InputType.isIngest(embeddingsInput.getInputType()); } private static boolean rateLimitingEnabled(RateLimitSettings rateLimitSettings) { return rateLimitSettings != null && rateLimitSettings.isEnabled(); } private void cleanup(CleanupStrategy cleanupStrategy) { try { shutdown(); switch (cleanupStrategy) { case RATE_LIMITED_REQUEST_QUEUES_ONLY -> notifyRateLimitedRequestsOfShutdown(); case REQUEST_QUEUE_ONLY -> rejectRequestsInRequestQueue(); default -> logger.error(Strings.format("Unknown clean up strategy for request executor: [%s]", cleanupStrategy.toString())); } terminationLatch.countDown(); } catch (Exception e) { logger.warn("Encountered an error while cleaning up", e); } } private void startHandlingRateLimitedTasks() { try { TimeValue timeToWait; do { if (isShutdown()) { logger.debug("Shutdown requested while handling rate limited tasks, cleaning up"); cleanup(CleanupStrategy.RATE_LIMITED_REQUEST_QUEUES_ONLY); return; } timeToWait = settings.getTaskPollFrequency(); for (var endpoint : rateLimitGroupings.values()) { timeToWait = TimeValue.min(endpoint.executeEnqueuedTask(), timeToWait); } // if we execute a task the timeToWait will be 0 so we'll immediately look for more work } while (timeToWait.compareTo(TimeValue.ZERO) <= 0); scheduleNextHandleTasks(timeToWait); } catch (Exception e) { logger.warn("Encountered an error while handling rate limited tasks", e); cleanup(CleanupStrategy.RATE_LIMITED_REQUEST_QUEUES_ONLY); } } private void notifyRateLimitedRequestsOfShutdown() { assert isShutdown() : "Requests should only be notified if the executor is shutting down"; for (var endpoint : rateLimitGroupings.values()) { endpoint.notifyRequestsOfShutdown(); } } private void rejectRequestsInRequestQueue() { assert isShutdown() : "Requests in request queue should only be notified if the executor is shutting down"; List<RejectableTask> requests = new ArrayList<>(); requestQueue.drainTo(requests); for (var request : requests) { // NoopTask does not implement being rejected, therefore we need to skip it if (request != NOOP_TASK) { rejectNonRateLimitedRequest(request); } } } private void rejectNonRateLimitedRequest(RejectableTask task) { var inferenceEntityId = task.getRequestManager().inferenceEntityId(); rejectRequest( task, format( "Failed to send request for inference id [%s] because the request executor service has been shutdown", inferenceEntityId ), format("Failed to notify request for inference id [%s] of rejection after executor service shutdown", inferenceEntityId) ); } private static void rejectRequest(RejectableTask task, String rejectionMessage, String rejectionFailedMessage) { try { task.onRejection(new EsRejectedExecutionException(rejectionMessage, true)); } catch (Exception e) { logger.warn(rejectionFailedMessage); } } // default for testing Integer remainingQueueCapacity(RequestManager requestManager) { var endpoint = rateLimitGroupings.get(requestManager.rateLimitGrouping()); if (endpoint == null) { return null; } return endpoint.remainingCapacity(); } // default for testing int numberOfRateLimitGroups() { return rateLimitGroupings.size(); } /** * Execute the request at some point in the future. * * @param requestManager the http request to send * @param inferenceInputs the inputs to send in the request * @param timeout the maximum time to wait for this request to complete (failing or succeeding). Once the time elapses, the * listener::onFailure is called with a {@link org.elasticsearch.ElasticsearchTimeoutException}. * If null, then the request will wait forever * @param listener an {@link ActionListener<InferenceServiceResults>} for the response or failure */ public void execute( RequestManager requestManager, InferenceInputs inferenceInputs, @Nullable TimeValue timeout, ActionListener<InferenceServiceResults> listener ) { var task = new RequestTask( requestManager, inferenceInputs, timeout, threadPool, // TODO when multi-tenancy (as well as batching) is implemented we need to be very careful that we preserve // the thread contexts correctly to avoid accidentally retrieving the credentials for the wrong user ContextPreservingActionListener.wrapPreservingContext(listener, threadPool.getThreadContext()) ); if (isShutdown()) { task.onRejection( new EsRejectedExecutionException( format( "Failed to enqueue request task for inference id [%s] because the request executor service has been shutdown", requestManager.inferenceEntityId() ), true ) ); return; } if (isEmbeddingsIngestInput(inferenceInputs) || rateLimitingEnabled(requestManager.rateLimitSettings())) { submitTaskToRateLimitedExecutionPath(task); } else { boolean taskAccepted = requestQueue.offer(task); if (taskAccepted == false) { task.onRejection( new EsRejectedExecutionException( format("Failed to enqueue request task for inference id [%s]", requestManager.inferenceEntityId()), false ) ); } } } /** * Provides rate limiting functionality for requests. A single {@link RateLimitingEndpointHandler} governs a group of requests. * This allows many requests to be serialized if they are being sent too fast. If the rate limit has not been met they will be sent * as soon as a thread is available. */ static
RateLimiterCreator
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/xml/OracleXmlTableFunction.java
{ "start": 937, "end": 1692 }
class ____ extends XmlTableFunction { public OracleXmlTableFunction(TypeConfiguration typeConfiguration) { super( false, new OracleXmlTableSetReturningFunctionTypeResolver(), typeConfiguration ); } @Override protected String determineColumnType(CastTarget castTarget, SqlAstTranslator<?> walker) { final String typeName = super.determineColumnType( castTarget, walker ); return switch ( typeName ) { // clob is not supported as column type for xmltable case "clob" -> "varchar2(" + walker.getSessionFactory().getJdbcServices().getDialect().getMaxVarcharLength() + ")"; case "number(1,0)" -> isEncodedBoolean( castTarget.getJdbcMapping() ) ? "varchar2(5)" : typeName; default -> typeName; }; } private static
OracleXmlTableFunction
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/codec/multipart/PartEvent.java
{ "start": 4850, "end": 5618 }
interface ____ { /** * Return the name of the event, as provided through the * {@code Content-Disposition name} parameter. * @return the name of the part, never {@code null} or empty */ default String name() { String name = headers().getContentDisposition().getName(); Assert.state(name != null, "No name available"); return name; } /** * Return the headers of the part that this event belongs to. */ HttpHeaders headers(); /** * Return the content of this event. The returned buffer must be consumed or * {@linkplain org.springframework.core.io.buffer.DataBufferUtils#release(DataBuffer) released}. */ DataBuffer content(); /** * Indicates whether this is the last event of a particular * part. */ boolean isLast(); }
PartEvent
java
quarkusio__quarkus
integration-tests/kafka-ssl/src/test/java/io/quarkus/it/kafka/SslKafkaConsumerTest.java
{ "start": 711, "end": 2642 }
class ____ { public abstract CertificateFormat getFormat(); @Test public void testReception() { String format = getFormat().name(); try (Producer<Integer, String> producer = createProducer(CertificateFormat.valueOf(format))) { producer.send(new ProducerRecord<>("test-ssl-consumer", 1, "hi world")); String string = RestAssured .given().queryParam("format", format) .when().get("/ssl") .andReturn().asString(); Assertions.assertEquals("hi world", string); } } public static Producer<Integer, String> createProducer(CertificateFormat format) { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, System.getProperty("bootstrap.servers")); props.put(ProducerConfig.CLIENT_ID_CONFIG, "test-ssl-producer"); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); String truststore = switch (format) { case PKCS12 -> "kafka-truststore.p12"; case JKS -> "kafka-truststore.jks"; case PEM -> "kafka.crt"; }; File tsFile = new File("target/certs/" + truststore); props.setProperty(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); props.setProperty(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, tsFile.getPath()); if (format != CertificateFormat.PEM) { props.setProperty(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "Z_pkTh9xgZovK4t34cGB2o6afT4zZg0L"); } props.setProperty(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, format.name()); props.setProperty(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, ""); return new KafkaProducer<>(props); } }
SslKafkaConsumerTest
java
spring-projects__spring-security
access/src/main/java/org/springframework/security/access/intercept/AbstractSecurityInterceptor.java
{ "start": 22287, "end": 22565 }
class ____ implements AuthenticationManager { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { throw new AuthenticationServiceException("Cannot authenticate " + authentication); } } }
NoOpAuthenticationManager
java
resilience4j__resilience4j
resilience4j-feign/src/test/java/io/github/resilience4j/feign/test/TestService.java
{ "start": 242, "end": 700 }
interface ____ { @RequestLine("GET /greeting") String greeting(); default String defaultGreeting() { return greeting(); } static TestService create(String url, RateLimiter rateLimiter) { FeignDecorators decorators = FeignDecorators.builder() .withRateLimiter(rateLimiter) .build(); return Resilience4jFeign.builder(decorators) .target(TestService.class, url); } }
TestService
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/javadoc/MalformedInlineTagTest.java
{ "start": 2776, "end": 2953 }
class ____ {} """) .addOutputLines( "Test.java", """ /** This malformed tag spans {@code multiple lines}. */
Test
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/configuration/Configuration_apply_Test.java
{ "start": 1447, "end": 4363 }
class ____ { @Test void apply_should_change_assertj_behavior() throws Exception { // GIVEN Configuration configuration = new NonDefaultConfiguration(); // WHEN configuration.apply(); // THEN then(FieldSupport.extraction().isAllowedToUsePrivateFields()).isEqualTo(configuration.extractingPrivateFieldsEnabled()); then(FieldSupport.comparison().isAllowedToUsePrivateFields()).isEqualTo(configuration.comparingPrivateFieldsEnabled()); then(Introspection.canExtractBareNamePropertyMethods()).isEqualTo(configuration.bareNamePropertyExtractionEnabled()); then(configuration.representation()).isNotSameAs(STANDARD_REPRESENTATION); // a bit dodgy but since our custom representation inherits StandardRepresentation, changing maxElementsForPrinting and // maxLengthForSingleLineDescription will be effective. then(StandardRepresentation.getMaxElementsForPrinting()).isEqualTo(configuration.maxElementsForPrinting()); then(StandardRepresentation.getMaxStackTraceElementsDisplayed()).isEqualTo(configuration.maxStackTraceElementsDisplayed()); then(StandardRepresentation.getMaxLengthForSingleLineDescription()).isEqualTo(configuration.maxLengthForSingleLineDescription()); boolean removeAssertJRelatedElementsFromStackTrace = Failures.instance().isRemoveAssertJRelatedElementsFromStackTrace(); then(removeAssertJRelatedElementsFromStackTrace).isEqualTo(configuration.removeAssertJRelatedElementsFromStackTraceEnabled()); // check lenient is honored by parsing a string that would fail if the DateFormat was not lenient. then(configuration.lenientDateParsingEnabled()).isTrue(); Date dateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse("2001-02-03T04:05:06"); then(dateTime).isEqualTo("2001-02-03T04:05:06") // passes whether the lenient flag is enabled or not .isEqualTo("2001-01-34T04:05:06"); // passes only when the lenient flag is enabled // check that additional date formats can be used Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2001-02-03"); then(date).isEqualTo("2001_02_03") .isEqualTo("2001|02|03"); then(AssumptionExceptionFactory.getPreferredAssumptionException()).isEqualTo(configuration.preferredAssumptionException()); } @Test void should_reset_date_formats() throws Exception { // GIVEN Configuration configuration = new NonDefaultConfiguration(); // WHEN configuration.apply(); Configuration.DEFAULT_CONFIGURATION.apply(); // THEN then(Configuration.DEFAULT_CONFIGURATION.additionalDateFormats()).isEmpty(); Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2001-02-03"); expectAssertionError(() -> then(date).isEqualTo("2001_02_03")); } @AfterEach public void afterEach() { // revert whatever we did in the other tests Configuration.DEFAULT_CONFIGURATION.apply(); } }
Configuration_apply_Test
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/criteria/JpaWindowFrame.java
{ "start": 443, "end": 744 }
interface ____ { /** * Get the {@link FrameKind} of this window frame. * * @return the window frame kind */ FrameKind getKind(); /** * Get the {@link Expression} of this window frame. * * @return the window frame expression */ @Nullable Expression<?> getExpression(); }
JpaWindowFrame
java
hibernate__hibernate-orm
hibernate-jcache/src/test/java/org/hibernate/orm/test/caching/SecondLevelCacheTest.java
{ "start": 8874, "end": 9623 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; @NaturalId @Column(name = "code", unique = true) private String code; //Getters and setters are omitted for brevity //end::caching-entity-natural-id-mapping-example[] public Person() {} public Person(String name) { this.name = name; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } //tag::caching-entity-natural-id-mapping-example[] } //end::caching-entity-natural-id-mapping-example[] }
Person
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/common/Type.java
{ "start": 51127, "end": 51635 }
interface ____, if any, * will appear last in the list. * * @return the direct supertypes, or an empty list if none */ public List<Type> getDirectSuperTypes() { return typeUtils.directSupertypes( typeMirror ) .stream() .map( typeFactory::getType ) .collect( Collectors.toList() ); } /** * Searches for the given superclass and collects all type arguments for the given class * * @param superclass the superclass or
types
java
elastic__elasticsearch
x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/action/SearchableSnapshotsStatsResponseTests.java
{ "start": 1570, "end": 8897 }
class ____ extends ESTestCase { public void testSerialization() throws IOException { for (int i = 0; i < randomIntBetween(10, 50); i++) { final SearchableSnapshotsStatsResponse testInstance = createTestInstance(); final SearchableSnapshotsStatsResponse deserializedInstance = copyWriteable( testInstance, writableRegistry(), SearchableSnapshotsStatsResponse::new, TransportVersion.current() ); assertEqualInstances(testInstance, deserializedInstance); } } public void testLevelValidation() { RestSearchableSnapshotsStatsAction action = new RestSearchableSnapshotsStatsAction(); final HashMap<String, String> params = new HashMap<>(); params.put("level", ClusterStatsLevel.CLUSTER.getLevel()); // cluster is valid RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withPath("/_searchable_snapshots/stats") .withParams(params) .build(); action.prepareRequest(request, mock(NodeClient.class)); // indices is valid params.put("level", ClusterStatsLevel.INDICES.getLevel()); request = new FakeRestRequest.Builder(xContentRegistry()).withPath("/_searchable_snapshots/stats").withParams(params).build(); action.prepareRequest(request, mock(NodeClient.class)); // shards is valid params.put("level", ClusterStatsLevel.SHARDS.getLevel()); request = new FakeRestRequest.Builder(xContentRegistry()).withPath("/_searchable_snapshots/stats").withParams(params).build(); action.prepareRequest(request, mock(NodeClient.class)); params.put("level", NodeStatsLevel.NODE.getLevel()); final RestRequest invalidLevelRequest1 = new FakeRestRequest.Builder(xContentRegistry()).withPath("/_stats") .withParams(params) .build(); IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> action.prepareRequest(invalidLevelRequest1, mock(NodeClient.class)) ); assertThat(e, hasToString(containsString("level parameter must be one of [cluster] or [indices] or [shards] but was [node]"))); params.put("level", "invalid"); final RestRequest invalidLevelRequest = new FakeRestRequest.Builder(xContentRegistry()).withPath("/_stats") .withParams(params) .build(); e = expectThrows(IllegalArgumentException.class, () -> action.prepareRequest(invalidLevelRequest, mock(NodeClient.class))); assertThat(e, hasToString(containsString("level parameter must be one of [cluster] or [indices] or [shards] but was [invalid]"))); } private void assertEqualInstances(SearchableSnapshotsStatsResponse expected, SearchableSnapshotsStatsResponse actual) { assertThat(actual.getTotalShards(), equalTo(expected.getTotalShards())); assertThat(actual.getSuccessfulShards(), equalTo(expected.getSuccessfulShards())); assertThat(actual.getFailedShards(), equalTo(expected.getFailedShards())); DefaultShardOperationFailedException[] originalFailures = expected.getShardFailures(); DefaultShardOperationFailedException[] parsedFailures = actual.getShardFailures(); assertThat(originalFailures.length, equalTo(parsedFailures.length)); for (int i = 0; i < originalFailures.length; i++) { assertThat(originalFailures[i].index(), equalTo(parsedFailures[i].index())); assertThat(originalFailures[i].shardId(), equalTo(parsedFailures[i].shardId())); assertThat(originalFailures[i].status(), equalTo(parsedFailures[i].status())); } assertThat(actual.getStats(), equalTo(expected.getStats())); } private SearchableSnapshotsStatsResponse createTestInstance() { final int totalShards = randomIntBetween(0, 20); final int successfulShards = totalShards > 0 ? randomIntBetween(0, totalShards) : 0; final int failedShards = totalShards - successfulShards; final String indexName = randomAlphaOfLength(10); final int replicas = randomIntBetween(0, 2); final SnapshotId snapshotId = new SnapshotId(randomAlphaOfLength(5), randomAlphaOfLength(5)); final IndexId indexId = new IndexId(randomAlphaOfLength(5), randomAlphaOfLength(5)); final List<SearchableSnapshotShardStats> shardStats = new ArrayList<>(); final List<DefaultShardOperationFailedException> shardFailures = new ArrayList<>(); for (int i = 0; i < totalShards; i++) { if (i < successfulShards) { shardStats.add(createSearchableSnapshotShardStats(indexName, i, true, snapshotId, indexId)); for (int j = 0; j < replicas; j++) { shardStats.add(createSearchableSnapshotShardStats(indexName, i, false, snapshotId, indexId)); } } else { shardFailures.add(new DefaultShardOperationFailedException(indexName, i, new Exception())); } } return new SearchableSnapshotsStatsResponse(shardStats, totalShards, successfulShards, failedShards, shardFailures); } private static SearchableSnapshotShardStats createSearchableSnapshotShardStats( String index, int shardId, boolean primary, SnapshotId snapshotId, IndexId indexId ) { final ShardRouting shardRouting = newShardRouting(index, shardId, randomAlphaOfLength(5), primary, ShardRoutingState.STARTED); final List<SearchableSnapshotShardStats.CacheIndexInputStats> inputStats = new ArrayList<>(); for (int j = 0; j < randomInt(10); j++) { inputStats.add(randomCacheIndexInputStats()); } return new SearchableSnapshotShardStats(shardRouting, snapshotId, indexId, inputStats); } private static SearchableSnapshotShardStats.CacheIndexInputStats randomCacheIndexInputStats() { return new SearchableSnapshotShardStats.CacheIndexInputStats( randomAlphaOfLength(10), randomNonNegativeLong(), ByteSizeValue.ofBytes(randomNonNegativeLong()), ByteSizeValue.ofBytes(randomNonNegativeLong()), ByteSizeValue.ofBytes(randomNonNegativeLong()), randomNonNegativeLong(), randomNonNegativeLong(), randomCounter(), randomCounter(), randomCounter(), randomCounter(), randomCounter(), randomCounter(), randomCounter(), randomCounter(), randomTimedCounter(), randomTimedCounter(), randomTimedCounter(), randomCounter(), randomCounter(), randomNonNegativeLong() ); } private static SearchableSnapshotShardStats.Counter randomCounter() { return new SearchableSnapshotShardStats.Counter(randomLong(), randomLong(), randomLong(), randomLong()); } private static SearchableSnapshotShardStats.TimedCounter randomTimedCounter() { return new SearchableSnapshotShardStats.TimedCounter(randomLong(), randomLong(), randomLong(), randomLong(), randomLong()); } }
SearchableSnapshotsStatsResponseTests
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/files/Files_assertIsExecutable_Test.java
{ "start": 1381, "end": 2528 }
class ____ extends FilesBaseTest { @Test void should_fail_if_actual_is_null() { // GIVEN File actual = null; // WHEN var error = expectAssertionError(() -> underTest.assertIsExecutable(INFO, actual)); // THEN then(error).hasMessage(actualIsNull()); } @Test void should_fail_if_file_does_not_exist() { // GIVEN File nonExistentFile = new File("xyz"); // WHEN expectAssertionError(() -> underTest.assertIsExecutable(INFO, nonExistentFile)); // THEN verify(failures).failure(INFO, shouldBeExecutable(nonExistentFile)); } @Test @DisabledOnOs(value = WINDOWS, disabledReason = "gh-2312") void should_fail_if_actual_is_not_executable() { // GIVEN File actual = resourceFile("empty.txt"); // WHEN expectAssertionError(() -> underTest.assertIsExecutable(INFO, actual)); // THEN verify(failures).failure(INFO, shouldBeExecutable(actual)); } @Test void should_pass_if_actual_is_executable() { // GIVEN File actual = resourceFile("executable_file.sh"); // WHEN/THEN underTest.assertIsExecutable(INFO, actual); } }
Files_assertIsExecutable_Test
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/SapNetweaverComponentBuilderFactory.java
{ "start": 1892, "end": 4015 }
interface ____ extends ComponentBuilder<NetWeaverComponent> { /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default SapNetweaverComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default SapNetweaverComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } }
SapNetweaverComponentBuilder
java
spring-projects__spring-boot
module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/context/SpringBootTestRandomPortApplicationListener.java
{ "start": 3815, "end": 5374 }
enum ____ { SERVER("server.port"), MANAGEMENT("management.server.port"); private final String property; Port(String property) { this.property = property; } String property() { return this.property; } } private record Ports(PropertyResolver resolver, ConversionService conversionService) { private static final Integer ZERO = Integer.valueOf(0); boolean isFixed(MapPropertySource source, Port port) { return !ZERO.equals(get(source, port, null)); } boolean isConfigured(PropertySource<?> source, Port port) { return source.getProperty(port.property()) != null; } @Contract("_, _, !null -> !null") @Nullable Integer get(PropertySources sources, Port port, @Nullable Integer defaultValue) { return sources.stream() .map((source) -> get(source, port, defaultValue)) .filter(Objects::nonNull) .findFirst() .orElse(defaultValue); } @Contract("_, _, !null -> !null") @Nullable Integer get(PropertySource<?> source, Port port, @Nullable Integer defaultValue) { Object value = source.getProperty(port.property()); if (value == null || ClassUtils.isAssignableValue(Integer.class, value)) { return (Integer) value; } try { return asInteger(value); } catch (ConversionFailedException ex) { if (value instanceof String string) { return asInteger(resolver().resolveRequiredPlaceholders(string)); } throw ex; } } private @Nullable Integer asInteger(@Nullable Object value) { return conversionService().convert(value, Integer.class); } } }
Port
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/common/ResourceCommitRequest.java
{ "start": 1220, "end": 5926 }
class ____<A extends SchedulerApplicationAttempt, N extends SchedulerNode> { // New containers to be allocated private List<ContainerAllocationProposal<A, N>> containersToAllocate = Collections.emptyList(); // New containers to be released private List<ContainerAllocationProposal<A, N>> containersToReserve = Collections.emptyList(); // We don't need these containers anymore private List<SchedulerContainer<A, N>> toReleaseContainers = Collections.emptyList(); private Resource totalAllocatedResource; private Resource totalReservedResource; private Resource totalReleasedResource; public ResourceCommitRequest( List<ContainerAllocationProposal<A, N>> containersToAllocate, List<ContainerAllocationProposal<A, N>> containersToReserve, List<SchedulerContainer<A, N>> toReleaseContainers) { if (null != containersToAllocate) { this.containersToAllocate = containersToAllocate; } if (null != containersToReserve) { this.containersToReserve = containersToReserve; } if (null != toReleaseContainers) { this.toReleaseContainers = toReleaseContainers; } totalAllocatedResource = Resources.createResource(0); totalReservedResource = Resources.createResource(0); /* * For total-release resource, it has two parts: * 1) Unconditional release: for example, an app reserved a container, * but the app doesn't has any pending resource. * 2) Conditional release: for example, reservation continuous looking, or * Lazy preemption -- which we need to kill some resource to allocate * or reserve the new container. * * For the 2nd part, it is inside: * ContainerAllocationProposal#toRelease, which means we will kill/release * these containers to allocate/reserve the given container. * * So we need to account both of conditional/unconditional to-release * containers to the total release-able resource. */ totalReleasedResource = Resources.createResource(0); for (ContainerAllocationProposal<A,N> c : this.containersToAllocate) { Resources.addTo(totalAllocatedResource, c.getAllocatedOrReservedResource()); for (SchedulerContainer<A,N> r : c.getToRelease()) { Resources.addTo(totalReleasedResource, r.getRmContainer().getAllocatedOrReservedResource()); } } for (ContainerAllocationProposal<A,N> c : this.containersToReserve) { Resources.addTo(totalReservedResource, c.getAllocatedOrReservedResource()); for (SchedulerContainer<A,N> r : c.getToRelease()) { Resources.addTo(totalReleasedResource, r.getRmContainer().getAllocatedOrReservedResource()); } } for (SchedulerContainer<A,N> r : this.toReleaseContainers) { Resources.addTo(totalReleasedResource, r.getRmContainer().getAllocatedOrReservedResource()); } } public List<ContainerAllocationProposal<A, N>> getContainersToAllocate() { return containersToAllocate; } public List<ContainerAllocationProposal<A, N>> getContainersToReserve() { return containersToReserve; } public List<SchedulerContainer<A, N>> getContainersToRelease() { return toReleaseContainers; } public Resource getTotalAllocatedResource() { return totalAllocatedResource; } public Resource getTotalReservedResource() { return totalReservedResource; } public Resource getTotalReleasedResource() { return totalReleasedResource; } /* * Util functions to make your life easier */ public boolean anythingAllocatedOrReserved() { return (!containersToAllocate.isEmpty()) || (!containersToReserve .isEmpty()); } public ContainerAllocationProposal<A, N> getFirstAllocatedOrReservedContainer() { ContainerAllocationProposal<A, N> c = null; if (!containersToAllocate.isEmpty()) { c = containersToAllocate.get(0); } if (c == null && !containersToReserve.isEmpty()) { c = containersToReserve.get(0); } return c; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("New " + getClass().getName() + ":" + "\n"); if (null != containersToAllocate && !containersToAllocate.isEmpty()) { sb.append("\t ALLOCATED=" + containersToAllocate.toString()); } if (null != containersToReserve && !containersToReserve.isEmpty()) { sb.append("\t RESERVED=" + containersToReserve.toString()); } if (null != toReleaseContainers && !toReleaseContainers.isEmpty()) { sb.append("\t RELEASED=" + toReleaseContainers.toString()); } return sb.toString(); } }
ResourceCommitRequest
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/search/AsyncVectorSearchRunner.java
{ "start": 3738, "end": 6031 }
class ____ implements ResultFuture<RowData> { private final BlockingQueue<JoinedRowResultFuture> resultFutureBuffer; private final boolean isLeftOuterJoin; private final GenericRowData nullRow; private RowData leftRow; private ResultFuture<RowData> realOutput; private JoinedRowResultFuture( BlockingQueue<JoinedRowResultFuture> resultFutureBuffer, boolean isLeftOuterJoin, int searchTableArity) { this.resultFutureBuffer = resultFutureBuffer; this.isLeftOuterJoin = isLeftOuterJoin; this.nullRow = new GenericRowData(searchTableArity); } public void reset(RowData leftRow, ResultFuture<RowData> realOutput) { this.leftRow = leftRow; this.realOutput = realOutput; } @Override public void complete(Collection<RowData> result) { if (result == null || result.isEmpty()) { if (isLeftOuterJoin) { RowData outRow = new JoinedRowData(leftRow.getRowKind(), leftRow, nullRow); realOutput.complete(Collections.singleton(outRow)); } else { realOutput.complete(Collections.emptyList()); } } else { List<RowData> outRows = new ArrayList<>(); for (RowData right : result) { RowData outRow = new JoinedRowData(leftRow.getRowKind(), leftRow, right); outRows.add(outRow); } realOutput.complete(outRows); } try { // put this collector to the queue to avoid this collector is used // again before outRows in the collector is not consumed. resultFutureBuffer.put(this); } catch (InterruptedException e) { completeExceptionally(e); } } @Override public void completeExceptionally(Throwable error) { realOutput.completeExceptionally(error); } @Override public void complete(CollectionSupplier<RowData> supplier) { throw new UnsupportedOperationException(); } } }
JoinedRowResultFuture
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/TaskFinishedEvent.java
{ "start": 1690, "end": 5678 }
class ____ implements HistoryEvent { private TaskFinished datum = null; private TaskID taskid; private TaskAttemptID successfulAttemptId; private long finishTime; private TaskType taskType; private String status; private Counters counters; private long startTime; /** * Create an event to record the successful completion of a task. * @param id Task ID * @param attemptId Task Attempt ID of the successful attempt for this task * @param finishTime Finish time of the task * @param taskType Type of the task * @param status Status string * @param counters Counters for the task * @param startTs task start time */ public TaskFinishedEvent(TaskID id, TaskAttemptID attemptId, long finishTime, TaskType taskType, String status, Counters counters, long startTs) { this.taskid = id; this.successfulAttemptId = attemptId; this.finishTime = finishTime; this.taskType = taskType; this.status = status; this.counters = counters; this.startTime = startTs; } public TaskFinishedEvent(TaskID id, TaskAttemptID attemptId, long finishTime, TaskType taskType, String status, Counters counters) { this(id, attemptId, finishTime, taskType, status, counters, SystemClock.getInstance().getTime()); } TaskFinishedEvent() {} public Object getDatum() { if (datum == null) { datum = new TaskFinished(); datum.setTaskid(new Utf8(taskid.toString())); if(successfulAttemptId != null) { datum.setSuccessfulAttemptId(new Utf8(successfulAttemptId.toString())); } datum.setFinishTime(finishTime); datum.setCounters(EventWriter.toAvro(counters)); datum.setTaskType(new Utf8(taskType.name())); datum.setStatus(new Utf8(status)); } return datum; } public void setDatum(Object oDatum) { this.datum = (TaskFinished)oDatum; this.taskid = TaskID.forName(datum.getTaskid().toString()); if (datum.getSuccessfulAttemptId() != null) { this.successfulAttemptId = TaskAttemptID .forName(datum.getSuccessfulAttemptId().toString()); } this.finishTime = datum.getFinishTime(); this.taskType = TaskType.valueOf(datum.getTaskType().toString()); this.status = datum.getStatus().toString(); this.counters = EventReader.fromAvro(datum.getCounters()); } /** Gets task id. */ public TaskID getTaskId() { return taskid; } /** Gets successful task attempt id. */ public TaskAttemptID getSuccessfulTaskAttemptId() { return successfulAttemptId; } /** Gets the task finish time. */ public long getFinishTime() { return finishTime; } /** * Gets the task start time to be reported to ATSv2. * @return task start time */ public long getStartTime() { return startTime; } /** Gets task counters. */ public Counters getCounters() { return counters; } /** Gets task type. */ public TaskType getTaskType() { return taskType; } /** * Gets task status. * @return task status */ public String getTaskStatus() { return status.toString(); } /** Gets event type. */ public EventType getEventType() { return EventType.TASK_FINISHED; } @Override public TimelineEvent toTimelineEvent() { TimelineEvent tEvent = new TimelineEvent(); tEvent.setId(StringUtils.toUpperCase(getEventType().name())); tEvent.addInfo("TASK_TYPE", getTaskType().toString()); tEvent.addInfo("FINISH_TIME", getFinishTime()); tEvent.addInfo("STATUS", TaskStatus.State.SUCCEEDED.toString()); tEvent.addInfo("SUCCESSFUL_TASK_ATTEMPT_ID", getSuccessfulTaskAttemptId() == null ? "" : getSuccessfulTaskAttemptId().toString()); return tEvent; } @Override public Set<TimelineMetric> getTimelineMetrics() { Set<TimelineMetric> jobMetrics = JobHistoryEventUtils .countersToTimelineMetric(getCounters(), finishTime); return jobMetrics; } }
TaskFinishedEvent
java
apache__rocketmq
common/src/main/java/org/apache/rocketmq/common/message/MessageQueueForC.java
{ "start": 885, "end": 3890 }
class ____ implements Comparable<MessageQueueForC>, Serializable { private static final long serialVersionUID = 5320967846569962104L; private String topic; private String brokerName; private int queueId; private long offset; public MessageQueueForC(String topic, String brokerName, int queueId, long offset) { this.topic = topic; this.brokerName = brokerName; this.queueId = queueId; this.offset = offset; } @Override public int compareTo(MessageQueueForC o) { int result = this.topic.compareTo(o.topic); if (result != 0) { return result; } result = this.brokerName.compareTo(o.brokerName); if (result != 0) { return result; } result = this.queueId - o.queueId; if (result != 0) { return result; } if ((this.offset - o.offset) > 0) { return 1; } else if ((this.offset - o.offset) == 0) { return 0; } else { return -1; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((brokerName == null) ? 0 : brokerName.hashCode()); result = prime * result + queueId; result = prime * result + ((topic == null) ? 0 : topic.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MessageQueueForC other = (MessageQueueForC) obj; if (brokerName == null) { if (other.brokerName != null) return false; } else if (!brokerName.equals(other.brokerName)) return false; if (queueId != other.queueId) return false; if (topic == null) { if (other.topic != null) return false; } else if (!topic.equals(other.topic)) return false; if (offset != other.offset) { return false; } return true; } @Override public String toString() { return "MessageQueueForC [topic=" + topic + ", brokerName=" + brokerName + ", queueId=" + queueId + ", offset=" + offset + "]"; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public String getBrokerName() { return brokerName; } public void setBrokerName(String brokerName) { this.brokerName = brokerName; } public int getQueueId() { return queueId; } public void setQueueId(int queueId) { this.queueId = queueId; } public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } }
MessageQueueForC
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/NetworkTagMappingManager.java
{ "start": 1052, "end": 1106 }
interface ____ network tag mapping manager. */ public
for
java
apache__dubbo
dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/DefaultCommandExecutorTest.java
{ "start": 1285, "end": 3305 }
class ____ { @Test void testExecute1() { Assertions.assertThrows(NoSuchCommandException.class, () -> { DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel()); executor.execute(CommandContextFactory.newInstance("not-exit")); }); } @Test void testExecute2() throws Exception { DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel()); final CommandContext commandContext = CommandContextFactory.newInstance("greeting", new String[] {"dubbo"}, false); commandContext.setQosConfiguration(QosConfiguration.builder() .anonymousAccessPermissionLevel(PermissionLevel.PROTECTED.name()) .build()); String result = executor.execute(commandContext); assertThat(result, equalTo("greeting dubbo")); } @Test void shouldNotThrowPermissionDenyException_GivenPermissionConfigAndMatchDefaultPUBLICCmdPermissionLevel() { DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel()); final CommandContext commandContext = CommandContextFactory.newInstance("live", new String[] {"dubbo"}, false); commandContext.setQosConfiguration(QosConfiguration.builder().build()); Assertions.assertDoesNotThrow(() -> executor.execute(commandContext)); } @Test void shouldNotThrowPermissionDenyException_GivenPermissionConfigAndNotMatchCmdPermissionLevel() { DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel()); final CommandContext commandContext = CommandContextFactory.newInstance("live", new String[] {"dubbo"}, false); // 1 PROTECTED commandContext.setQosConfiguration( QosConfiguration.builder().anonymousAccessPermissionLevel("1").build()); Assertions.assertDoesNotThrow(() -> executor.execute(commandContext)); } }
DefaultCommandExecutorTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/CharArrayAssertBaseTest.java
{ "start": 903, "end": 1405 }
class ____ extends BaseTestTemplate<CharArrayAssert, char[]> { protected CharArrays arrays; @Override protected CharArrayAssert create_assertions() { return new CharArrayAssert(emptyArray()); } @Override protected void inject_internal_objects() { super.inject_internal_objects(); arrays = mock(CharArrays.class); assertions.arrays = arrays; } protected CharArrays getArrays(CharArrayAssert someAssertions) { return someAssertions.arrays; } }
CharArrayAssertBaseTest
java
elastic__elasticsearch
x-pack/plugin/downsample/src/main/java/org/elasticsearch/xpack/downsample/DownsampleMetrics.java
{ "start": 2290, "end": 3376 }
enum ____ { SUCCESS("success"), MISSING_DOCS("missing_docs"), FAILED("failed"), INVALID_CONFIGURATION("invalid_configuration"); static final String NAME = "status"; private final String message; ActionStatus(String message) { this.message = message; } String getMessage() { return message; } } void recordShardOperation(long durationInMilliSeconds, ActionStatus status) { meterRegistry.getLongHistogram(LATENCY_SHARD).record(durationInMilliSeconds, Map.of(ActionStatus.NAME, status.getMessage())); meterRegistry.getLongCounter(ACTIONS_SHARD).incrementBy(1L, Map.of(ActionStatus.NAME, status.getMessage())); } void recordOperation(long durationInMilliSeconds, ActionStatus status) { meterRegistry.getLongHistogram(LATENCY_TOTAL).record(durationInMilliSeconds, Map.of(ActionStatus.NAME, status.getMessage())); meterRegistry.getLongCounter(ACTIONS).incrementBy(1L, Map.of(ActionStatus.NAME, status.getMessage())); } }
ActionStatus
java
apache__camel
components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyUdpWithInOutUsingPlainSocketTest.java
{ "start": 1279, "end": 3296 }
class ____ extends BaseNettyTest { private static final Logger LOG = LoggerFactory.getLogger(NettyUdpWithInOutUsingPlainSocketTest.class); @Test public void testSendAndReceiveOnce() throws Exception { String out = sendAndReceiveUdpMessages("World"); assertNotNull("should receive data", out); assertEquals("Hello World\n", out); } private String sendAndReceiveUdpMessages(String input) throws Exception { DatagramSocket socket = new DatagramSocket(); InetAddress address = InetAddress.getByName("127.0.0.1"); // must append delimiter byte[] data = (input + "\n").getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, getPort()); LOG.debug("+++ Sending data +++"); socket.send(packet); Thread.sleep(1000); byte[] buf = new byte[128]; DatagramPacket receive = new DatagramPacket(buf, buf.length, address, getPort()); LOG.debug("+++ Receiving data +++"); socket.receive(receive); socket.close(); return new String(receive.getData(), 0, receive.getLength()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("netty:udp://127.0.0.1:{{port}}?textline=true&sync=true").process(new Processor() { public void process(Exchange exchange) { String s = exchange.getIn().getBody(String.class); LOG.debug("Server got: {}", s); exchange.getMessage().setBody("Hello " + s); // just make the remote address is there assertNotNull(exchange.getIn().getHeader(NettyConstants.NETTY_REMOTE_ADDRESS), "The remote address header should not be Null"); } }); } }; } }
NettyUdpWithInOutUsingPlainSocketTest
java
elastic__elasticsearch
x-pack/plugin/security/qa/multi-cluster/src/javaRestTest/java/org/elasticsearch/xpack/remotecluster/ConsumingTestServer.java
{ "start": 1000, "end": 3391 }
class ____ extends ExternalResource { private static final Logger logger = LogManager.getLogger(ConsumingTestServer.class); final ArrayBlockingQueue<String> received = new ArrayBlockingQueue<>(1000); private static HttpServer server; private final Thread messageConsumerThread = consumerThread(); private volatile Consumer<String> consumer; private volatile boolean consumerRunning = true; @Override protected void before() throws Throwable { server = HttpServer.create(); server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); server.createContext("/", this::handle); server.start(); messageConsumerThread.start(); } private Thread consumerThread() { return new Thread(() -> { while (consumerRunning) { if (consumer != null) { try { String msg = received.poll(1L, TimeUnit.SECONDS); if (msg != null && msg.isEmpty() == false) { consumer.accept(msg); } } catch (InterruptedException e) { throw new RuntimeException(e); } } } }); } @Override protected void after() { server.stop(1); consumerRunning = false; } private void handle(HttpExchange exchange) throws IOException { try (exchange) { try { try (InputStream requestBody = exchange.getRequestBody()) { if (requestBody != null) { var read = readJsonMessages(requestBody); received.addAll(read); } } } catch (RuntimeException e) { logger.warn("failed to parse request", e); } exchange.sendResponseHeaders(201, 0); } } private List<String> readJsonMessages(InputStream input) { // parse NDJSON return new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)).lines().toList(); } public int getPort() { return server.getAddress().getPort(); } public void addMessageConsumer(Consumer<String> messageConsumer) { this.consumer = messageConsumer; } }
ConsumingTestServer
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentMap.java
{ "start": 11041, "end": 11695 }
class ____ implements Map.Entry<K, V> { private final K key; final Map.Entry<WeakKey<K>, V> entry; private SimpleEntry(K key, Map.Entry<WeakKey<K>, V> entry) { this.key = key; this.entry = entry; } @Override public K getKey() { return key; } @Override public V getValue() { return entry.getValue(); } @Override public V setValue(V value) { if (value == null) { throw new NullPointerException(); } return entry.setValue(value); } } }
SimpleEntry
java
google__guava
android/guava/src/com/google/common/base/CharMatcher.java
{ "start": 44983, "end": 45361 }
class ____ extends CharMatcher { static final CharMatcher INSTANCE = new JavaUpperCase(); @Override public boolean matches(char c) { return Character.isUpperCase(c); } @Override public String toString() { return "CharMatcher.javaUpperCase()"; } } /** Implementation of {@link #javaLowerCase()}. */ private static final
JavaUpperCase
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/validation/BindingElementValidator.java
{ "start": 6983, "end": 16215 }
class ____ the size? protected abstract Optional<XType> bindingElementType(); /** * Adds an error if the {@link #bindingElementType() binding element type} is not appropriate. * * <p>Adds an error if the type is not a primitive, array, declared type, or type variable. * * <p>If the binding is not a multibinding contribution, adds an error if the type is a * framework type. * * <p>If the element has {@link dagger.multibindings.ElementsIntoSet @ElementsIntoSet} or {@code * SET_VALUES}, adds an error if the type is not a {@code Set<T>} for some {@code T} */ protected void checkType() { switch (ContributionType.fromBindingElement(element)) { case UNIQUE: // Basic checks on the types bindingElementType().ifPresent(this::checkKeyType); // Validate that a unique binding is not attempting to bind a framework type. This // validation is only appropriate for unique bindings because multibindings may collect // framework types. E.g. Set<Provider<Foo>> is perfectly reasonable. checkFrameworkType(); // Validate that a unique binding is not attempting to bind an unqualified assisted type. // This validation is only appropriate for unique bindings because multibindings may // collect assisted types. checkAssistedType(); // Check for any specifically disallowed types bindingElementType().ifPresent(this::checkDisallowedType); break; case SET: bindingElementType().ifPresent(this::checkSetValueFrameworkType); break; case MAP: bindingElementType().ifPresent(this::checkMapValueFrameworkType); break; case SET_VALUES: checkSetValuesType(); break; } } /** * Adds an error if {@code keyType} is not a primitive, declared type, array, or type variable. */ protected void checkKeyType(XType keyType) { if (isVoid(keyType)) { report.addError(bindingElements("must %s a value (not void)", bindingElementTypeVerb())); } else if (!(isPrimitive(keyType) || isDeclared(keyType) || isArray(keyType) || isTypeVariable(keyType))) { report.addError(badTypeMessage()); } } /** Adds errors for unqualified assisted types. */ private void checkAssistedType() { if (qualifiers.isEmpty() && bindingElementType().isPresent() && isDeclared(bindingElementType().get())) { XTypeElement keyElement = bindingElementType().get().getTypeElement(); if (isAssistedInjectionType(keyElement)) { report.addError( "Dagger does not support providing @AssistedInject types without a qualifier.", keyElement); } if (isAssistedFactoryType(keyElement)) { report.addError("Dagger does not support providing @AssistedFactory types.", keyElement); } } } /** * Adds an error if the type for an element with {@link * dagger.multibindings.ElementsIntoSet @ElementsIntoSet} or {@code SET_VALUES} is not a a * {@code Set<T>} for a reasonable {@code T}. */ // TODO(gak): should we allow "covariant return" for set values? protected void checkSetValuesType() { bindingElementType().ifPresent(this::checkSetValuesType); } /** Adds an error if {@code type} is not a {@code Set<T>} for a reasonable {@code T}. */ protected final void checkSetValuesType(XType type) { if (!SetType.isSet(type)) { report.addError(elementsIntoSetNotASetMessage()); } else { SetType setType = SetType.from(type); if (setType.isRawType()) { report.addError(elementsIntoSetRawSetMessage()); } else { checkSetValueFrameworkType(setType.elementType()); } } } /** * Adds an error if the element has more than one {@linkplain Qualifier qualifier} annotation. */ private void checkQualifiers() { if (qualifiers.size() > 1) { for (XAnnotation qualifier : qualifiers) { report.addError( bindingElements("may not use more than one @Qualifier"), element, qualifier); } } } /** * Adds an error if an {@link dagger.multibindings.IntoMap @IntoMap} element doesn't have * exactly one {@link dagger.MapKey @MapKey} annotation, or if an element that is {@link * dagger.multibindings.IntoMap @IntoMap} has any. */ private void checkMapKeys() { if (!allowsMultibindings.allowsMultibindings()) { return; } ImmutableSet<XAnnotation> mapKeys = getMapKeys(element); if (ContributionType.fromBindingElement(element).equals(ContributionType.MAP)) { switch (mapKeys.size()) { case 0: report.addError(bindingElements("of type map must declare a map key")); break; case 1: break; default: report.addError(bindingElements("may not have more than one map key")); break; } } else if (!mapKeys.isEmpty()) { report.addError(bindingElements("of non map type cannot declare a map key")); } } /** * Adds errors if: * * <ul> * <li>the element doesn't allow {@linkplain MultibindingAnnotations multibinding annotations} * and has any * <li>the element does allow them but has more than one * <li>the element has a multibinding annotation and its {@link dagger.Provides} or {@link * dagger.producers.Produces} annotation has a {@code type} parameter. * </ul> */ private void checkMultibindingAnnotations() { ImmutableSet<XAnnotation> multibindingAnnotations = XElements.getAllAnnotations(element, MULTIBINDING_ANNOTATIONS); switch (allowsMultibindings) { case NO_MULTIBINDINGS: for (XAnnotation annotation : multibindingAnnotations) { report.addError( bindingElements("cannot have multibinding annotations"), element, annotation); } break; case ALLOWS_MULTIBINDINGS: if (multibindingAnnotations.size() > 1) { for (XAnnotation annotation : multibindingAnnotations) { report.addError( bindingElements("cannot have more than one multibinding annotation"), element, annotation); } } break; } } /** * Adds an error if the element has a scope but doesn't allow scoping, or if it has more than * one {@linkplain Scope scope} annotation. */ private void checkScopes() { ImmutableSet<Scope> scopes = injectionAnnotations.getScopes(element); String error = null; switch (allowsScoping) { case ALLOWS_SCOPING: if (scopes.size() <= 1) { return; } error = bindingElements("cannot use more than one @Scope"); break; case NO_SCOPING: error = bindingElements("cannot be scoped"); break; } verifyNotNull(error); for (Scope scope : scopes) { report.addError(error, element, scope.scopeAnnotation().xprocessing()); } } /** * Adds an error if the {@link #bindingElementType() type} is a {@linkplain FrameworkTypes * framework type}. */ private void checkFrameworkType() { if (bindingElementType().filter(FrameworkTypes::isFrameworkType).isPresent()) { report.addError(bindingElements("must not %s framework types: %s", bindingElementTypeVerb(), XTypes.toStableString(bindingElementType().get()))); } } private void checkSetValueFrameworkType(XType bindingType) { checkKeyType(bindingType); if (FrameworkTypes.isSetValueFrameworkType(bindingType)) { report.addError(bindingElements( "with @IntoSet/@ElementsIntoSet must not %s framework types: %s", bindingElementTypeVerb(), XTypes.toStableString(bindingType))); } checkDisallowedType(bindingType); } private void checkMapValueFrameworkType(XType bindingType) { checkKeyType(bindingType); if (FrameworkTypes.isMapValueFrameworkType(bindingType)) { report.addError( bindingElements("with @IntoMap must not %s framework types: %s", bindingElementTypeVerb(), XTypes.toStableString(bindingType))); } checkDisallowedType(bindingType); } private void checkDisallowedType(XType bindingType) { // TODO(erichang): Consider if we want to go inside complex types to ban // dagger.internal.Provider as well? E.g. List<dagger.internal.Provider<Foo>> if (FrameworkTypes.isDisallowedType(bindingType)) { report.addError(bindingElements("must not %s disallowed types: %s", bindingElementTypeVerb(), XTypes.toStableString(bindingElementType().get()))); } } } /** Whether to check multibinding annotations. */
checking
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrar.java
{ "start": 5335, "end": 11520 }
class ____ { private final Class<?> type; private final @Nullable Constructor<?> bindConstructor; private final BeanProperties bean; private final Set<Class<?>> seen; Processor(Bindable<?> bindable) { this(bindable, false, new HashSet<>()); } private Processor(Bindable<?> bindable, boolean nestedType, Set<Class<?>> seen) { this.type = getRawClass(bindable); this.bindConstructor = (bindable.getBindMethod() != BindMethod.JAVA_BEAN) ? BindConstructorProvider.DEFAULT.getBindConstructor(getBindableType(bindable), nestedType) : null; this.bean = JavaBeanBinder.BeanProperties.of(bindable); this.seen = seen; } private static Class<?> getBindableType(Bindable<?> bindable) { Class<?> resolved = bindable.getType().resolve(); Assert.state(resolved != null, "'resolved' must not be null"); return resolved; } private static Class<?> getRawClass(Bindable<?> bindable) { Class<?> rawClass = bindable.getType().getRawClass(); Assert.state(rawClass != null, "'rawClass' must not be null"); return rawClass; } void process(ReflectionHints hints) { if (this.seen.contains(this.type)) { return; } this.seen.add(this.type); handleConstructor(hints); if (this.bindConstructor != null) { handleValueObjectProperties(hints); } else if (this.bean != null && !this.bean.getProperties().isEmpty()) { handleJavaBeanProperties(hints); } } private void handleConstructor(ReflectionHints hints) { if (this.bindConstructor != null) { if (KotlinDetector.isKotlinType(this.bindConstructor.getDeclaringClass())) { KotlinDelegate.handleConstructor(hints, this.bindConstructor); } else { hints.registerConstructor(this.bindConstructor, ExecutableMode.INVOKE); } return; } Arrays.stream(this.type.getDeclaredConstructors()) .filter(this::hasNoParameters) .findFirst() .ifPresent((constructor) -> hints.registerConstructor(constructor, ExecutableMode.INVOKE)); } private boolean hasNoParameters(Constructor<?> candidate) { return candidate.getParameterCount() == 0; } private void handleValueObjectProperties(ReflectionHints hints) { Assert.state(this.bindConstructor != null, "'bindConstructor' must not be null"); for (int i = 0; i < this.bindConstructor.getParameterCount(); i++) { String propertyName = this.bindConstructor.getParameters()[i].getName(); ResolvableType propertyType = ResolvableType.forConstructorParameter(this.bindConstructor, i); handleProperty(hints, propertyName, propertyType); } } private void handleJavaBeanProperties(ReflectionHints hints) { Map<String, BeanProperty> properties = this.bean.getProperties(); properties.forEach((name, property) -> { Method getter = property.getGetter(); if (getter != null) { hints.registerMethod(getter, ExecutableMode.INVOKE); } Method setter = property.getSetter(); if (setter != null) { hints.registerMethod(setter, ExecutableMode.INVOKE); } Field field = property.getField(); if (field != null) { hints.registerField(field); } handleProperty(hints, name, property.getType()); }); } private void handleProperty(ReflectionHints hints, String propertyName, ResolvableType propertyType) { Class<?> propertyClass = propertyType.resolve(); if (propertyClass == null) { return; } if (propertyClass.equals(this.type)) { return; // Prevent infinite recursion } Class<?> componentType = getComponentClass(propertyType); if (componentType != null) { // Can be a list of simple types if (!isJavaType(componentType)) { processNested(componentType, hints); } } else if (isNestedType(propertyName, propertyClass)) { processNested(propertyClass, hints); } } private void processNested(Class<?> type, ReflectionHints hints) { new Processor(Bindable.of(type), true, this.seen).process(hints); } private @Nullable Class<?> getComponentClass(ResolvableType type) { ResolvableType componentType = getComponentType(type); if (componentType == null) { return null; } if (isContainer(componentType)) { // Resolve nested generics like Map<String, List<SomeType>> return getComponentClass(componentType); } return componentType.toClass(); } private @Nullable ResolvableType getComponentType(ResolvableType type) { if (type.isArray()) { return type.getComponentType(); } if (isCollection(type)) { return type.asCollection().getGeneric(); } if (isMap(type)) { return type.asMap().getGeneric(1); } return null; } private boolean isContainer(ResolvableType type) { return type.isArray() || isCollection(type) || isMap(type); } private boolean isCollection(ResolvableType type) { return Collection.class.isAssignableFrom(type.toClass()); } private boolean isMap(ResolvableType type) { return Map.class.isAssignableFrom(type.toClass()); } /** * Specify whether the specified property refer to a nested type. A nested type * represents a sub-namespace that need to be fully resolved. Nested types are * either inner classes or annotated with {@link NestedConfigurationProperty}. * @param propertyName the name of the property * @param propertyType the type of the property * @return whether the specified {@code propertyType} is a nested type */ private boolean isNestedType(String propertyName, Class<?> propertyType) { Class<?> declaringClass = propertyType.getDeclaringClass(); if (declaringClass != null && isNested(declaringClass, this.type)) { return true; } Field field = ReflectionUtils.findField(this.type, propertyName); return (field != null) && MergedAnnotations.from(field).isPresent(Nested.class); } private static boolean isNested(Class<?> type, Class<?> candidate) { if (type.isAssignableFrom(candidate)) { return true; } return (candidate.getDeclaringClass() != null && isNested(type, candidate.getDeclaringClass())); } private boolean isJavaType(Class<?> candidate) { return candidate.getPackageName().startsWith("java."); } } /** * Inner
Processor
java
google__error-prone
core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
{ "start": 72281, "end": 72992 }
class ____ extends BugChecker implements ClassTreeMatcher { @Override public Description matchClass(ClassTree tree, VisitorState state) { return addSuppressWarningsIfCompilationSucceeds( tree, state, false, fix -> describeMatch(tree, fix)); } } @Test public void compilesWithFix_inAllCompilationUnits() { // This compilation will succeed because we consider all compilation errors. CompilationTestHelper.newInstance( AddSuppressWarningsIfCompilationSucceedsInAllCompilationUnits.class, getClass()) .addSourceLines( "InAllCompilationUnits.java", """
AddSuppressWarningsIfCompilationSucceedsInAllCompilationUnits
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/filter/MarkerFilter.java
{ "start": 1722, "end": 7368 }
class ____ extends AbstractFilter { public static final String ATTR_MARKER = "marker"; private final String name; private MarkerFilter(final String name, final Result onMatch, final Result onMismatch) { super(onMatch, onMismatch); this.name = name; } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object... params) { return filter(marker); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final Object msg, final Throwable t) { return filter(marker); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final Message msg, final Throwable t) { return filter(marker); } @Override public Result filter(final LogEvent event) { return filter(event.getMarker()); } private Result filter(final Marker marker) { return marker != null && marker.isInstanceOf(name) ? onMatch : onMismatch; } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0) { return filter(marker); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1) { return filter(marker); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2) { return filter(marker); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3) { return filter(marker); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4) { return filter(marker); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5) { return filter(marker); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5, final Object p6) { return filter(marker); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5, final Object p6, final Object p7) { return filter(marker); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5, final Object p6, final Object p7, final Object p8) { return filter(marker); } @Override public Result filter( final Logger logger, final Level level, final Marker marker, final String msg, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5, final Object p6, final Object p7, final Object p8, final Object p9) { return filter(marker); } @Override public String toString() { return name; } /** * Creates the MarkerFilter. * @param marker The Marker name to match. * @param match The action to take if a match occurs. * @param mismatch The action to take if no match occurs. * @return A MarkerFilter. */ // TODO Consider refactoring to use AbstractFilter.AbstractFilterBuilder @PluginFactory public static MarkerFilter createFilter( @PluginAttribute(ATTR_MARKER) final String marker, @PluginAttribute(AbstractFilterBuilder.ATTR_ON_MATCH) final Result match, @PluginAttribute(AbstractFilterBuilder.ATTR_ON_MISMATCH) final Result mismatch) { if (marker == null) { LOGGER.error("A marker must be provided for MarkerFilter"); return null; } return new MarkerFilter(marker, match, mismatch); } }
MarkerFilter
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/main/java/org/apache/camel/spring/xml/TrustManagersParametersFactoryBean.java
{ "start": 1319, "end": 2188 }
class ____ extends AbstractTrustManagersParametersFactoryBean implements FactoryBean<TrustManagersParameters>, ApplicationContextAware { private KeyStoreParametersFactoryBean keyStore; @XmlTransient private ApplicationContext applicationContext; @Override public KeyStoreParametersFactoryBean getKeyStore() { return this.keyStore; } public void setKeyStore(KeyStoreParametersFactoryBean keyStore) { this.keyStore = keyStore; } @Override protected CamelContext getCamelContextWithId(String camelContextId) { return CamelContextResolverHelper.getCamelContextWithId(applicationContext, camelContextId); } @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } }
TrustManagersParametersFactoryBean
java
apache__dubbo
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java
{ "start": 1172, "end": 2442 }
class ____ { private static CompositeMeterRegistry compositeRegistry = new CompositeMeterRegistry(); /** * Use CompositeMeterRegistry according to the following priority * 1. If useGlobalRegistry is configured, use the micrometer global CompositeMeterRegistry * 2. If there is a spring actuator, use spring's CompositeMeterRegistry * 3. Dubbo's own CompositeMeterRegistry is used by default */ public static CompositeMeterRegistry getCompositeRegistry(ApplicationModel applicationModel) { Optional<MetricsConfig> configOptional = applicationModel.getApplicationConfigManager().getMetrics(); if (configOptional.isPresent() && configOptional.get().getUseGlobalRegistry() != null && configOptional.get().getUseGlobalRegistry()) { return Metrics.globalRegistry; } else { return compositeRegistry; } } public static CompositeMeterRegistry getCompositeRegistry() { return getCompositeRegistry(ApplicationModel.defaultModel()); } public static void setCompositeRegistry(CompositeMeterRegistry compositeRegistry) { MetricsGlobalRegistry.compositeRegistry = compositeRegistry; } }
MetricsGlobalRegistry
java
spring-projects__spring-security
access/src/test/java/org/springframework/security/web/access/channel/ChannelProcessingFilterTests.java
{ "start": 6375, "end": 7373 }
class ____ implements FilterInvocationSecurityMetadataSource { private Collection<ConfigAttribute> toReturn; private String servletPath; private boolean provideIterator; MockFilterInvocationDefinitionMap(String servletPath, boolean provideIterator, String... toReturn) { this.servletPath = servletPath; this.toReturn = SecurityConfig.createList(toReturn); this.provideIterator = provideIterator; } @Override public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { FilterInvocation fi = (FilterInvocation) object; if (this.servletPath.equals(fi.getHttpRequest().getServletPath())) { return this.toReturn; } else { return null; } } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { if (!this.provideIterator) { return null; } return this.toReturn; } @Override public boolean supports(Class<?> clazz) { return true; } } }
MockFilterInvocationDefinitionMap
java
quarkusio__quarkus
extensions/websockets-next/runtime-dev/src/main/java/io/quarkus/websockets/next/runtime/dev/ui/WebSocketNextJsonRPCService.java
{ "start": 1236, "end": 12094 }
class ____ implements ConnectionListener { private static final Logger LOG = Logger.getLogger(WebSocketNextJsonRPCService.class); private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"); private static final String DEVUI_SOCKET_KEY_HEADER = "X-devui-socket-key"; private final BroadcastProcessor<JsonObject> connectionStatus; private final BroadcastProcessor<JsonObject> connectionMessages; private final ConnectionManager connectionManager; private final Vertx vertx; private final ConcurrentMap<String, DevWebSocket> sockets; private final VertxHttpConfig httpConfig; private final WebSocketsServerRuntimeConfig.DevMode devModeConfig; WebSocketNextJsonRPCService(Instance<ConnectionManager> connectionManager, Vertx vertx, VertxHttpConfig httpConfig, WebSocketsServerRuntimeConfig config) { this.connectionStatus = BroadcastProcessor.create(); this.connectionMessages = BroadcastProcessor.create(); this.connectionManager = connectionManager.isResolvable() ? connectionManager.get() : null; this.vertx = vertx; this.httpConfig = httpConfig; this.devModeConfig = config.devMode(); this.sockets = new ConcurrentHashMap<>(); if (this.connectionManager != null) { this.connectionManager.addListener(this); } } public Multi<JsonObject> connectionStatus() { return connectionStatus; } public Multi<JsonObject> connectionMessages() { return connectionMessages; } public JsonObject getConnections(List<String> endpoints) { JsonObject json = new JsonObject(); if (connectionManager != null) { for (String endpoint : endpoints) { List<WebSocketConnection> connections = new ArrayList<>(connectionManager.getConnections(endpoint)); connections.sort(Comparator.comparing(WebSocketConnection::creationTime)); JsonArray array = new JsonArray(); for (WebSocketConnection c : connections) { array.add(toJsonObject(endpoint, c)); } json.put(endpoint, array); } } json.put("connectionMessagesLimit", devModeConfig.connectionMessagesLimit()); return json; } public JsonArray getMessages(String connectionKey) { DevWebSocket socket = sockets.get(connectionKey); if (socket != null) { JsonArray ret = new JsonArray(); List<TextMessage> messages = socket.messages; synchronized (messages) { for (ListIterator<TextMessage> it = messages.listIterator(messages.size()); it.hasPrevious();) { ret.add(it.previous().toJsonObject()); } } return ret; } return new JsonArray(); } public Uni<JsonObject> openDevConnection(String path, String endpointPath) { if (connectionManager == null) { return failureUni(); } if (isInvalidPath(path, endpointPath)) { LOG.errorf("Invalid path %s; original endpoint path %s", path, endpointPath); return failureUni(); } WebSocketClient client = vertx.createWebSocketClient(); String connectionKey = UUID.randomUUID().toString(); Uni<WebSocket> uni = Uni.createFrom().completionStage(() -> client .connect(new WebSocketConnectOptions() .setPort(httpConfig.port()) .setHost(httpConfig.host()) .setURI(path) .addHeader(DEVUI_SOCKET_KEY_HEADER, connectionKey)) .toCompletionStage()); return uni.onItem().transform(s -> { LOG.debugf("Opened Dev UI connection with key %s to %s", connectionKey, path); List<TextMessage> messages = new ArrayList<>(); s.textMessageHandler(m -> { synchronized (messages) { if (messages.size() < devModeConfig.connectionMessagesLimit()) { TextMessage t = new TextMessage(true, m, LocalDateTime.now()); messages.add(t); connectionMessages.onNext(t.toJsonObject().put("key", connectionKey)); } else { LOG.debugf("Opened Dev UI connection [%s] received a message but the limit [%s] has been reached", connectionKey, devModeConfig.connectionMessagesLimit()); } } }); sockets.put(connectionKey, new DevWebSocket(s, messages)); return new JsonObject().put("success", true).put("key", connectionKey); }).onFailure().recoverWithItem(t -> { LOG.errorf(t, "Unable to open Dev UI connection with key %s to %s", connectionKey, path); return new JsonObject().put("success", false); }); } static boolean isInvalidPath(String path, String endpointPath) { if (!endpointPath.contains("{")) { return !normalize(path).equals(endpointPath); } // "/foo/{bar}-1/baz" -> ["foo","{bar}","baz"] String[] endpointPathSegments = endpointPath.split("/"); String[] pathSegments = normalize(path).split("/"); if (endpointPathSegments.length != pathSegments.length) { return true; } for (int i = 0; i < endpointPathSegments.length; i++) { String es = endpointPathSegments[i]; String s = pathSegments[i]; if (es.startsWith("{") && es.endsWith("}")) { // path segment only contains path param continue; } else if (es.contains("{")) { String[] parts = es.split("\\{[a-zA-Z0-9_]+\\}"); for (String part : parts) { if (!s.contains(part)) { return true; } } } else if (!es.equals(s)) { // no path param and segments are not equal return true; } } return false; } private static String normalize(String path) { int queryIdx = path.indexOf("?"); if (queryIdx != -1) { return path.substring(0, queryIdx); } return path; } public Uni<JsonObject> closeDevConnection(String connectionKey) { if (connectionManager == null) { return failureUni(); } DevWebSocket socket = sockets.remove(connectionKey); if (socket != null) { Uni<Void> uni = Uni.createFrom().completionStage(() -> socket.socket.close().toCompletionStage()); return uni.onItem().transform(v -> { LOG.debugf("Closed Dev UI connection with key %s", connectionKey); return new JsonObject().put("success", true); }).onFailure().recoverWithItem(t -> { LOG.errorf(t, "Unable to close Dev UI connection with key %s", connectionKey); return new JsonObject().put("success", false); }); } return failureUni(); } public Uni<JsonObject> sendTextMessage(String connectionKey, String message) { DevWebSocket socket = sockets.get(connectionKey); if (socket != null) { Uni<Void> uni = Uni.createFrom().completionStage(() -> socket.socket.writeTextMessage(message).toCompletionStage()); return uni.onItem().transform(v -> { List<TextMessage> messages = socket.messages; synchronized (messages) { if (messages.size() < devModeConfig.connectionMessagesLimit()) { TextMessage t = new TextMessage(false, message, LocalDateTime.now()); messages.add(t); connectionMessages.onNext(t.toJsonObject().put("key", connectionKey)); LOG.debugf("Sent text message to connection with key %s", connectionKey); } else { LOG.debugf("Sent text message to connection [%s] but the limit [%s] has been reached", connectionKey, devModeConfig.connectionMessagesLimit()); } } return new JsonObject().put("success", true); }).onFailure().recoverWithItem(t -> { LOG.errorf(t, "Unable to send text message to connection with key %s", connectionKey); return new JsonObject().put("success", false); }); } return failureUni(); } public JsonObject clearMessages(String connectionKey) { DevWebSocket socket = sockets.get(connectionKey); if (socket != null) { socket.clearMessages(); return new JsonObject().put("success", true); } return new JsonObject().put("success", false); } private Uni<JsonObject> failureUni() { return Uni.createFrom().item(new JsonObject().put("success", false)); } @Override public void connectionAdded(String endpoint, WebSocketConnection connection) { connectionStatus.onNext(toJsonObject(endpoint, connection)); } @Override public void connectionRemoved(String endpoint, String connectionId) { connectionStatus.onNext(new JsonObject().put("id", connectionId).put("endpoint", endpoint).put("removed", true)); } JsonObject toJsonObject(String endpoint, WebSocketConnection c) { JsonObject json = new JsonObject(); json.put("id", c.id()); json.put("endpoint", endpoint); json.put("creationTime", LocalDateTime.ofInstant(c.creationTime(), ZoneId.systemDefault()).format(FORMATTER)); json.put("handshakePath", c.handshakeRequest().path()); String key = c.handshakeRequest().header(DEVUI_SOCKET_KEY_HEADER); if (key != null) { json.put("devuiSocketKey", key); } return json; } record DevWebSocket(WebSocket socket, List<TextMessage> messages) { void clearMessages() { synchronized (messages) { messages.clear(); } } } record TextMessage(boolean incoming, String text, LocalDateTime timestamp) { JsonObject toJsonObject() { return new JsonObject() .put("text", text) .put("incoming", incoming) .put("time", timestamp.format(FORMATTER)) .put("className", incoming ? "incoming" : "outgoing") .put("userAbbr", incoming ? "IN" : "OUT"); } } }
WebSocketNextJsonRPCService
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/RegisterNodeManagerResponse.java
{ "start": 1103, "end": 2244 }
class ____ { public abstract MasterKey getContainerTokenMasterKey(); public abstract void setContainerTokenMasterKey(MasterKey secretKey); public abstract MasterKey getNMTokenMasterKey(); public abstract void setNMTokenMasterKey(MasterKey secretKey); public abstract NodeAction getNodeAction(); public abstract void setNodeAction(NodeAction nodeAction); public abstract long getRMIdentifier(); public abstract void setRMIdentifier(long rmIdentifier); public abstract String getDiagnosticsMessage(); public abstract void setDiagnosticsMessage(String diagnosticsMessage); public abstract void setRMVersion(String version); public abstract String getRMVersion(); public abstract Resource getResource(); public abstract void setResource(Resource resource); public abstract boolean getAreNodeLabelsAcceptedByRM(); public abstract void setAreNodeLabelsAcceptedByRM( boolean areNodeLabelsAcceptedByRM); public abstract boolean getAreNodeAttributesAcceptedByRM(); public abstract void setAreNodeAttributesAcceptedByRM( boolean areNodeAttributesAcceptedByRM); }
RegisterNodeManagerResponse
java
quarkusio__quarkus
extensions/scheduler/common/src/main/java/io/quarkus/scheduler/common/runtime/DefaultInvoker.java
{ "start": 323, "end": 1658 }
class ____ implements ScheduledInvoker { @Override public CompletionStage<Void> invoke(ScheduledExecution execution) throws Exception { ManagedContext requestContext = Arc.container().requestContext(); if (requestContext.isActive()) { return invokeBean(execution); } else { // 1. Activate the context // 2. Capture the state (which is basically a shared Map instance) // 3. Destroy the context correctly when the returned stage completes requestContext.activate(); final ContextState state = requestContext.getState(); try { return invokeBean(execution).whenComplete((v, t) -> { requestContext.destroy(state); }); } catch (Throwable e) { // Terminate the context and return a failed stage if something goes really wrong requestContext.terminate(); return CompletableFuture.failedStage(e); } finally { // Always deactivate the context requestContext.deactivate(); } } } // This method is generated and should never throw an exception protected abstract CompletionStage<Void> invokeBean(ScheduledExecution execution); }
DefaultInvoker
java
apache__camel
components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/annotation/ReplaceBeanFromMethodTest.java
{ "start": 2616, "end": 3078 }
class ____ { @ReplaceInRegistry Greetings myGreetings() { return new CustomGreetings("Willow"); } @Test void shouldSupportNestedTest() throws Exception { mock.expectedBodiesReceived("Hi Willow!"); String result = template.requestBody((Object) null, String.class); mock.assertIsSatisfied(); assertEquals("Hi Willow!", result); } } static
NestedTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/consumer/GateBuffersSpecTest.java
{ "start": 1585, "end": 10025 }
class ____ { private static ResultPartitionType[] parameters() { return ResultPartitionType.values(); } @ParameterizedTest @MethodSource("parameters") void testCalculationWithSufficientRequiredBuffers(ResultPartitionType partitionType) { int numInputChannels = 499; GateBuffersSpec gateBuffersSpec = createGateBuffersSpec(numInputChannels, partitionType); int minFloating = 1; int maxFloating = 8; int numExclusivePerChannel = 2; int targetTotalBuffersPerGate = 1006; checkBuffersInGate( gateBuffersSpec, minFloating, maxFloating, numExclusivePerChannel, targetTotalBuffersPerGate); } @ParameterizedTest @MethodSource("parameters") void testCalculationWithOneExclusiveBuffer(ResultPartitionType partitionType) { int numInputChannels = 500; GateBuffersSpec gateBuffersSpec = createGateBuffersSpec(numInputChannels, partitionType); boolean isPipeline = isPipelinedOrHybridResultPartition(partitionType); int minFloating = isPipeline ? 1 : 500; int maxFloating = isPipelinedOrHybridResultPartition(partitionType) ? 8 : 508; int numExclusivePerChannel = isPipelinedOrHybridResultPartition(partitionType) ? 2 : 1; int targetTotalBuffersPerGate = 1008; checkBuffersInGate( gateBuffersSpec, minFloating, maxFloating, numExclusivePerChannel, targetTotalBuffersPerGate); } @ParameterizedTest @MethodSource("parameters") void testUpperBoundaryCalculationWithOneExclusiveBuffer(ResultPartitionType partitionType) { int numInputChannels = 999; GateBuffersSpec gateBuffersSpec = createGateBuffersSpec(numInputChannels, partitionType); int minFloating = 1; int maxFloating = isPipelinedOrHybridResultPartition(partitionType) ? 8 : 1007; int numExclusivePerChannel = isPipelinedOrHybridResultPartition(partitionType) ? 2 : 1; int targetTotalBuffersPerGate = 2006; checkBuffersInGate( gateBuffersSpec, minFloating, maxFloating, numExclusivePerChannel, targetTotalBuffersPerGate); } @ParameterizedTest @MethodSource("parameters") void testBoundaryCalculationWithoutExclusiveBuffer(ResultPartitionType partitionType) { int numInputChannels = 1000; GateBuffersSpec gateBuffersSpec = createGateBuffersSpec(numInputChannels, partitionType); boolean isPipeline = isPipelinedOrHybridResultPartition(partitionType); int minFloating = isPipeline ? 1 : 1000; int maxFloating = isPipeline ? 8 : numInputChannels * 2 + 8; int numExclusivePerChannel = isPipeline ? 2 : 0; int targetTotalBuffersPerGate = 2008; checkBuffersInGate( gateBuffersSpec, minFloating, maxFloating, numExclusivePerChannel, targetTotalBuffersPerGate); } @ParameterizedTest @MethodSource("parameters") void testCalculationWithConfiguredZeroExclusiveBuffer(ResultPartitionType partitionType) { int numInputChannels = 1001; int numExclusiveBuffersPerChannel = 0; GateBuffersSpec gateBuffersSpec = createGateBuffersSpec( numInputChannels, partitionType, numExclusiveBuffersPerChannel); int minFloating = 1; int maxFloating = 8; int numExclusivePerChannel = 0; int targetTotalBuffersPerGate = 8; checkBuffersInGate( gateBuffersSpec, minFloating, maxFloating, numExclusivePerChannel, targetTotalBuffersPerGate); } @ParameterizedTest @MethodSource("parameters") void testConfiguredMaxRequiredBuffersPerGate(ResultPartitionType partitionType) { boolean enabledTieredStorage = false; Optional<Integer> configuredMaxRequiredBuffers = Optional.of(100); int effectiveMaxRequiredBuffers = getEffectiveMaxRequiredBuffersPerGate( partitionType, configuredMaxRequiredBuffers, enabledTieredStorage); assertThat(effectiveMaxRequiredBuffers).isEqualTo(configuredMaxRequiredBuffers.get()); enabledTieredStorage = true; effectiveMaxRequiredBuffers = getEffectiveMaxRequiredBuffersPerGate( partitionType, configuredMaxRequiredBuffers, enabledTieredStorage); assertThat(effectiveMaxRequiredBuffers).isEqualTo(configuredMaxRequiredBuffers.get()); } @ParameterizedTest @MethodSource("parameters") void testDefaultMaxRequiredBuffersPerGate(ResultPartitionType partitionType) { Optional<Integer> emptyConfig = Optional.empty(); boolean enabledTieredStorage = false; int effectiveMaxRequiredBuffers = getEffectiveMaxRequiredBuffersPerGate( partitionType, emptyConfig, enabledTieredStorage); int expectEffectiveMaxRequiredBuffers = isPipelinedOrHybridResultPartitionNewMode(partitionType, enabledTieredStorage) ? DEFAULT_MAX_REQUIRED_BUFFERS_PER_GATE_FOR_STREAM : DEFAULT_MAX_REQUIRED_BUFFERS_PER_GATE_FOR_BATCH; assertThat(effectiveMaxRequiredBuffers).isEqualTo(expectEffectiveMaxRequiredBuffers); enabledTieredStorage = true; expectEffectiveMaxRequiredBuffers = isPipelinedOrHybridResultPartitionNewMode(partitionType, enabledTieredStorage) ? DEFAULT_MAX_REQUIRED_BUFFERS_PER_GATE_FOR_STREAM : DEFAULT_MAX_REQUIRED_BUFFERS_PER_GATE_FOR_BATCH; effectiveMaxRequiredBuffers = getEffectiveMaxRequiredBuffersPerGate( partitionType, emptyConfig, enabledTieredStorage); assertThat(effectiveMaxRequiredBuffers).isEqualTo(expectEffectiveMaxRequiredBuffers); } private static void checkBuffersInGate( GateBuffersSpec gateBuffersSpec, int minFloating, int maxFloating, int numExclusivePerChannel, int targetTotalBuffersPerGate) { assertThat(gateBuffersSpec.getRequiredFloatingBuffers()).isEqualTo(minFloating); assertThat(gateBuffersSpec.getTotalFloatingBuffers()).isEqualTo(maxFloating); assertThat(gateBuffersSpec.getEffectiveExclusiveBuffersPerChannel()) .isEqualTo(numExclusivePerChannel); assertThat(gateBuffersSpec.targetTotalBuffersPerGate()) .isEqualTo(targetTotalBuffersPerGate); } private static GateBuffersSpec createGateBuffersSpec( int numInputChannels, ResultPartitionType partitionType) { return createGateBuffersSpec(numInputChannels, partitionType, 2); } private static GateBuffersSpec createGateBuffersSpec( int numInputChannels, ResultPartitionType partitionType, int numExclusiveBuffersPerChannel) { return InputGateSpecUtils.createGateBuffersSpec( getMaxRequiredBuffersPerGate(partitionType), numExclusiveBuffersPerChannel, 8, partitionType, numInputChannels, false); } private static Optional<Integer> getMaxRequiredBuffersPerGate( ResultPartitionType partitionType) { return isPipelinedOrHybridResultPartition(partitionType) ? Optional.of(DEFAULT_MAX_REQUIRED_BUFFERS_PER_GATE_FOR_STREAM) : Optional.of(DEFAULT_MAX_REQUIRED_BUFFERS_PER_GATE_FOR_BATCH); } private static boolean isPipelinedOrHybridResultPartition(ResultPartitionType partitionType) { return partitionType.isPipelinedOrPipelinedBoundedResultPartition() || partitionType.isHybridResultPartition(); } private static boolean isPipelinedOrHybridResultPartitionNewMode( ResultPartitionType partitionType, Boolean enabledTieredStorage) { return partitionType.isPipelinedOrPipelinedBoundedResultPartition() || (partitionType.isHybridResultPartition() && !enabledTieredStorage); } }
GateBuffersSpecTest
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/beanparam/NestedBeanParamInSubResourcesTest.java
{ "start": 1659, "end": 1792 }
class ____ { @QueryParam("name") String name; @BeanParam Country country; } public static
City
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/context/visitor/ConfigurationReaderVisitor.java
{ "start": 1114, "end": 1444 }
class ____ extends ConfigurationMetadataWriterVisitor implements TypeElementVisitor<ConfigurationReader, Object> { @NonNull @Override public VisitorKind getVisitorKind() { return VisitorKind.ISOLATING; } @Override public void finish(VisitorContext visitorContext) { } }
ConfigurationReaderVisitor
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/convert/support/CollectionToStringConverter.java
{ "start": 1137, "end": 2388 }
class ____ implements ConditionalGenericConverter { private static final String DELIMITER = ","; private final ConversionService conversionService; public CollectionToStringConverter(ConversionService conversionService) { this.conversionService = conversionService; } @Override public Set<ConvertiblePair> getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(Collection.class, String.class)); } @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return ConversionUtils.canConvertElements( sourceType.getElementTypeDescriptor(), targetType, this.conversionService); } @Override public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (!(source instanceof Collection<?> sourceCollection)) { return null; } if (sourceCollection.isEmpty()) { return ""; } StringJoiner sj = new StringJoiner(DELIMITER); for (Object sourceElement : sourceCollection) { Object targetElement = this.conversionService.convert( sourceElement, sourceType.elementTypeDescriptor(sourceElement), targetType); sj.add(String.valueOf(targetElement)); } return sj.toString(); } }
CollectionToStringConverter