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
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/android/FragmentNotInstantiableTest.java
{ "start": 15265, "end": 15635 }
class ____ extends Fragment {} } }\ """) .addSourceLines( "CustomFragment.java", """ package com.google.errorprone.bugpatterns.android.testdata; /** * @author jasonlong@google.com (Jason Long) */ public
ImplicitlyStaticAndPublicInnerFragment
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client-jaxrs/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveEnricher.java
{ "start": 5010, "end": 5543 }
class ____ */ void forSubResourceMethod(ClassCreator subClassCreator, MethodCreator subConstructor, MethodCreator subClinit, MethodCreator subMethodCreator, ClassInfo rootInterfaceClass, ClassInfo subInterfaceClass, MethodInfo subMethod, MethodInfo rootMethod, AssignableResultHandle invocationBuilder, // sub-level IndexView index, BuildProducer<GeneratedClassBuildItem> generatedClasses, int methodIndex, int subMethodIndex, FieldDescriptor javaMethodField); }
field
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/http/impl/HttpClientImpl.java
{ "start": 1838, "end": 4828 }
class ____ { List<String> nonProxyHosts; boolean verifyHost; boolean defaultSsl; String defaultHost; int defaultPort; int maxRedirects; int initialPoolKind; } // Pattern to check we are not dealing with an absoluate URI static final Pattern ABS_URI_START_PATTERN = Pattern.compile("^\\p{Alpha}[\\p{Alpha}\\p{Digit}+.\\-]*:"); private final PoolOptions poolOptions; private final ResourceManager<EndpointKey, SharedHttpClientConnectionGroup> httpCM; private final EndpointResolverInternal endpointResolver; private final Function<HttpClientResponse, Future<RequestOptions>> redirectHandler; private long timerID; private final Handler<HttpConnection> connectHandler; private final Function<ContextInternal, ContextInternal> contextProvider; private final long maxLifetime; private final int initialPoolKind; public HttpClientImpl(VertxInternal vertx, Handler<HttpConnection> connectHandler, Function<HttpClientResponse, Future<RequestOptions>> redirectHandler, HttpChannelConnector connector, HttpClientMetrics<?, ?, ?> metrics, EndpointResolver endpointResolver, PoolOptions poolOptions, ProxyOptions defaultProxyOptions, ClientSSLOptions defaultSslOptions, Config config) { super(vertx, connector, metrics, defaultProxyOptions, defaultSslOptions, config.nonProxyHosts, config.verifyHost, config.defaultSsl, config.defaultHost, config.defaultPort, config.maxRedirects); this.endpointResolver = (EndpointResolverImpl) endpointResolver; this.connectHandler = connectHandler; this.poolOptions = poolOptions; this.httpCM = new ResourceManager<>(); this.maxLifetime = MILLISECONDS.convert(poolOptions.getMaxLifetime(), poolOptions.getMaxLifetimeUnit()); this.initialPoolKind = config.initialPoolKind; this.redirectHandler = redirectHandler != null ? redirectHandler : DEFAULT_REDIRECT_HANDLER; int eventLoopSize = poolOptions.getEventLoopSize(); if (eventLoopSize > 0) { ContextInternal[] eventLoops = new ContextInternal[eventLoopSize]; for (int i = 0;i < eventLoopSize;i++) { eventLoops[i] = vertx.createEventLoopContext(); } AtomicInteger idx = new AtomicInteger(); contextProvider = ctx -> { int i = idx.getAndIncrement(); return eventLoops[i % eventLoopSize]; }; } else { contextProvider = ConnectionPool.EVENT_LOOP_CONTEXT_PROVIDER; } // Init time if (poolOptions.getCleanerPeriod() > 0) { PoolChecker checker = new PoolChecker(this); ContextInternal timerContext = vertx.createEventLoopContext(); timerID = timerContext.setTimer(poolOptions.getCleanerPeriod(), checker); } } /** * A weak ref to the client so it can be finalized. */ private static
Config
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/propertyeditors/PropertiesEditor.java
{ "start": 1446, "end": 2525 }
class ____ extends PropertyEditorSupport { /** * Convert {@link String} into {@link Properties}, considering it as * properties content. * @param text the text to be so converted */ @Override public void setAsText(@Nullable String text) throws IllegalArgumentException { Properties props = new Properties(); if (text != null) { try { // Must use the ISO-8859-1 encoding because Properties.load(stream) expects it. props.load(new ByteArrayInputStream(text.getBytes(StandardCharsets.ISO_8859_1))); } catch (IOException ex) { // Should never happen. throw new IllegalArgumentException( "Failed to parse [" + text + "] into Properties", ex); } } setValue(props); } /** * Take {@link Properties} as-is; convert {@link Map} into {@code Properties}. */ @Override public void setValue(Object value) { if (!(value instanceof Properties) && value instanceof Map<?, ?> map) { Properties props = new Properties(); props.putAll(map); super.setValue(props); } else { super.setValue(value); } } }
PropertiesEditor
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToRadiansErrorTests.java
{ "start": 800, "end": 1390 }
class ____ extends ErrorsForCasesWithoutExamplesTestCase { @Override protected List<TestCaseSupplier> cases() { return paramsToSuppliers(ToRadiansTests.parameters()); } @Override protected Expression build(Source source, List<Expression> args) { return new ToRadians(source, args.get(0)); } @Override protected Matcher<String> expectedTypeErrorMatcher(List<Set<DataType>> validPerPosition, List<DataType> signature) { return equalTo(typeErrorMessage(false, validPerPosition, signature, (v, p) -> "numeric")); } }
ToRadiansErrorTests
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/component/properties/SpringPropertiesComponentOnExceptionRefTest.java
{ "start": 989, "end": 1327 }
class ____ extends PropertiesComponentOnExceptionTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/component/properties/SpringPropertiesComponentOnExceptionRefTest.xml"); } }
SpringPropertiesComponentOnExceptionRefTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/enhance/spi/interceptor/SessionAssociableInterceptor.java
{ "start": 323, "end": 618 }
interface ____ extends PersistentAttributeInterceptor { SharedSessionContractImplementor getLinkedSession(); void setSession(SharedSessionContractImplementor session); void unsetSession(); boolean allowLoadOutsideTransaction(); String getSessionFactoryUuid(); }
SessionAssociableInterceptor
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/ShouldBeMarkedCase_create_Test.java
{ "start": 1015, "end": 1484 }
class ____ { @Test void should_create_error_message() { // GIVEN ErrorMessageFactory factory = shouldBeMarked(new AtomicMarkableReference<>("actual", false)); // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo("[Test] %nExpecting AtomicMarkableReference[marked=false, reference=\"actual\"] to be a marked but was not".formatted()); } }
ShouldBeMarkedCase_create_Test
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/intercept/InterceptFromWithPredicateAndStopRouteTest.java
{ "start": 904, "end": 1580 }
class ____ extends InterceptFromRouteTestSupport { @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { interceptFrom().onWhen(header("foo").isEqualTo("bar")).to("mock:b").stop(); from("direct:start").to("mock:a"); } }; } @Override protected void prepareMatchingTest() { a.expectedMessageCount(0); b.expectedMessageCount(1); } @Override protected void prepareNonMatchingTest() { a.expectedMessageCount(1); b.expectedMessageCount(0); } }
InterceptFromWithPredicateAndStopRouteTest
java
google__dagger
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
{ "start": 75183, "end": 75565 }
interface ____"); }); } @Test public void missingBindingWithoutQualifier_warnAboutSimilarTypeWithQualifierExists() { Source qualifierSrc = CompilerTests.javaSource( "test.MyQualifier", "package test;", "", "import javax.inject.Qualifier;", "", "@Qualifier", "@
MyComponent
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/MessageMapping.java
{ "start": 1292, "end": 5551 }
class ____. * * <p>{@code @MessageMapping} methods support the following arguments: * <ul> * <li>{@link Payload @Payload} method argument to extract the payload of a * message and have it de-serialized to the declared target type. * {@code @Payload} arguments may also be annotated with Validation annotations * such as {@link org.springframework.validation.annotation.Validated @Validated} * and will then have JSR-303 validation applied. Keep in mind the annotation * is not required to be present as it is assumed by default for arguments not * handled otherwise. </li> * <li>{@link DestinationVariable @DestinationVariable} method argument for * access to template variable values extracted from the message destination, * for example, {@code /hotels/{hotel}}. Variable values may also be converted from * String to the declared method argument type, if needed.</li> * <li>{@link Header @Header} method argument to extract a specific message * header value and have a * {@link org.springframework.core.convert.converter.Converter Converter} * applied to it to convert the value to the declared target type.</li> * <li>{@link Headers @Headers} method argument that is also assignable to * {@link java.util.Map} for access to all headers.</li> * <li>{@link org.springframework.messaging.MessageHeaders MessageHeaders} * method argument for access to all headers.</li> * <li>{@link org.springframework.messaging.support.MessageHeaderAccessor * MessageHeaderAccessor} method argument for access to all headers. * In some processing scenarios, like STOMP over WebSocket, this may also be * a specialization such as * {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor * SimpMessageHeaderAccessor}.</li> * <li>{@link Message Message&lt;T&gt;} for access to body and headers with the body * de-serialized if necessary to match the declared type.</li> * <li>{@link java.security.Principal} method arguments are supported in * some processing scenarios such as STOMP over WebSocket. It reflects the * authenticated user.</li> * </ul> * * <p>Return value handling depends on the processing scenario: * <ul> * <li>STOMP over WebSocket -- the value is turned into a message and sent to a * default response destination or to a custom destination specified with an * {@link SendTo @SendTo} or * {@link org.springframework.messaging.simp.annotation.SendToUser @SendToUser} * annotation. * <li>RSocket -- the response is used to reply to the stream request. * </ul> * * <p>Specializations of this annotation include * {@link org.springframework.messaging.simp.annotation.SubscribeMapping @SubscribeMapping} * (for example, STOMP subscriptions) and * {@link org.springframework.messaging.rsocket.annotation.ConnectMapping @ConnectMapping} * (for example, RSocket connections). Both narrow the primary mapping further and also match * against the message type. Both can be combined with a type-level * {@code @MessageMapping} that declares a common pattern prefix (or prefixes). * * <p>For further details on the use of this annotation in different contexts, * see the following sections of the Spring Framework reference: * <ul> * <li>STOMP over WebSocket * <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#websocket-stomp-handle-annotations"> * "Annotated Controllers"</a>. * <li>RSocket * <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#rsocket-annot-responders"> * "Annotated Responders"</a>. * </ul> * * <p><b>NOTE:</b> When using controller interfaces (for example, for AOP proxying), * make sure to consistently put <i>all</i> your mapping annotations - such as * {@code @MessageMapping} and {@code @SubscribeMapping} - on * the controller <i>interface</i> rather than on the implementation class. * * @author Rossen Stoyanchev * @since 4.0 * @see org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler * @see org.springframework.messaging.rsocket.annotation.support.RSocketMessageHandler */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Reflective(MessageMappingReflectiveProcessor.class) public @
methods
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/TestingPhysicalSlotRequestBulkBuilder.java
{ "start": 1285, "end": 2824 }
class ____ { private static final BiConsumer<ExecutionVertexID, Throwable> EMPTY_CANCELLER = (r, t) -> {}; private final Map<ExecutionSlotSharingGroup, List<ExecutionVertexID>> executions = new HashMap<>(); private final Map<ExecutionSlotSharingGroup, ResourceProfile> pendingRequests = new HashMap<>(); private BiConsumer<ExecutionVertexID, Throwable> canceller = EMPTY_CANCELLER; TestingPhysicalSlotRequestBulkBuilder addPendingRequest( ExecutionSlotSharingGroup executionSlotSharingGroup, ResourceProfile resourceProfile) { pendingRequests.put(executionSlotSharingGroup, resourceProfile); executions.put( executionSlotSharingGroup, new ArrayList<>(executionSlotSharingGroup.getExecutionVertexIds())); return this; } TestingPhysicalSlotRequestBulkBuilder setCanceller( BiConsumer<ExecutionVertexID, Throwable> canceller) { this.canceller = canceller; return this; } SharingPhysicalSlotRequestBulk buildSharingPhysicalSlotRequestBulk() { return new SharingPhysicalSlotRequestBulk(executions, pendingRequests, canceller); } PhysicalSlotRequestBulkWithTimestamp buildPhysicalSlotRequestBulkWithTimestamp() { return new PhysicalSlotRequestBulkWithTimestamp(buildSharingPhysicalSlotRequestBulk()); } static TestingPhysicalSlotRequestBulkBuilder newBuilder() { return new TestingPhysicalSlotRequestBulkBuilder(); } }
TestingPhysicalSlotRequestBulkBuilder
java
grpc__grpc-java
servlet/src/main/java/io/grpc/servlet/ServletServerStream.java
{ "start": 6155, "end": 6888 }
class ____ implements WriteListener { @Override public void onError(Throwable t) { if (logger.isLoggable(FINE)) { logger.log(FINE, String.format("[{%s}] Error: ", logId), t); } // If the resp is not committed, cancel() to avoid being redirected to an error page. // Else, the container will send RST_STREAM at the end. if (!resp.isCommitted()) { cancel(Status.fromThrowable(t)); } else { transportState.runOnTransportThread( () -> transportState.transportReportStatus(Status.fromThrowable(t))); } } @Override public void onWritePossible() throws IOException { writer.onWritePossible(); } } private final
GrpcWriteListener
java
spring-projects__spring-boot
module/spring-boot-flyway/src/test/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfigurationTests.java
{ "start": 46830, "end": 47630 }
class ____ { @Bean(destroyMethod = "shutdown") EmbeddedDatabase dataSource(DataSourceProperties properties) throws SQLException { EmbeddedDatabase database = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) .setName(getDatabaseName(properties)) .build(); insertUser(database); return database; } protected abstract String getDatabaseName(DataSourceProperties properties); private void insertUser(EmbeddedDatabase database) throws SQLException { try (Connection connection = database.getConnection()) { connection.prepareStatement("CREATE USER test password 'secret'").execute(); connection.prepareStatement("ALTER USER test ADMIN TRUE").execute(); } } } @Configuration(proxyBeanMethods = false) static
AbstractUserH2DataSourceConfiguration
java
apache__kafka
streams/test-utils/src/test/java/org/apache/kafka/streams/TopologyTestDriverTest.java
{ "start": 10580, "end": 60658 }
class ____ implements ProcessorSupplier<Object, Object, Object, Object> { private final Collection<Punctuation> punctuations; private MockProcessorSupplier() { this(Collections.emptySet()); } private MockProcessorSupplier(final Collection<Punctuation> punctuations) { this.punctuations = punctuations; } @Override public Processor<Object, Object, Object, Object> get() { final MockProcessor mockProcessor = new MockProcessor(punctuations); // to keep tests simple, ignore calls from ApiUtils.checkSupplier if (!isCheckSupplierCall()) { mockProcessors.add(mockProcessor); } return mockProcessor; } /** * Used to keep tests simple, and ignore calls from {@link org.apache.kafka.streams.internals.ApiUtils#checkSupplier(Supplier)} )}. * @return true if the stack context is within a {@link org.apache.kafka.streams.internals.ApiUtils#checkSupplier(Supplier)} )} call */ public boolean isCheckSupplierCall() { return Arrays.stream(Thread.currentThread().getStackTrace()) .anyMatch(caller -> "org.apache.kafka.streams.internals.ApiUtils".equals(caller.getClassName()) && "checkSupplier".equals(caller.getMethodName())); } } @AfterEach public void tearDown() { if (testDriver != null) { testDriver.close(); } } private Topology setupSourceSinkTopology() { final Topology topology = new Topology(); final String sourceName = "source"; topology.addSource(sourceName, SOURCE_TOPIC_1); topology.addSink("sink", SINK_TOPIC_1, sourceName); return topology; } private Topology setupTopologyWithTwoSubtopologies() { final Topology topology = new Topology(); final String sourceName1 = "source-1"; final String sourceName2 = "source-2"; topology.addSource(sourceName1, SOURCE_TOPIC_1); topology.addSink("sink-1", SINK_TOPIC_1, sourceName1); topology.addSource(sourceName2, SINK_TOPIC_1); topology.addSink("sink-2", SINK_TOPIC_2, sourceName2); return topology; } private Topology setupSingleProcessorTopology() { return setupSingleProcessorTopology(-1, null, null); } private Topology setupSingleProcessorTopology(final long punctuationIntervalMs, final PunctuationType punctuationType, final Punctuator callback) { final Collection<Punctuation> punctuations; if (punctuationIntervalMs > 0 && punctuationType != null && callback != null) { punctuations = Collections.singleton(new Punctuation(punctuationIntervalMs, punctuationType, callback)); } else { punctuations = Collections.emptySet(); } final Topology topology = new Topology(); final String sourceName = "source"; topology.addSource(sourceName, SOURCE_TOPIC_1); topology.addProcessor("processor", new MockProcessorSupplier(punctuations), sourceName); return topology; } private Topology setupMultipleSourceTopology(final String... sourceTopicNames) { final Topology topology = new Topology(); final String[] processorNames = new String[sourceTopicNames.length]; int i = 0; for (final String sourceTopicName : sourceTopicNames) { final String sourceName = sourceTopicName + "-source"; final String processorName = sourceTopicName + "-processor"; topology.addSource(sourceName, sourceTopicName); processorNames[i++] = processorName; topology.addProcessor(processorName, new MockProcessorSupplier(), sourceName); } topology.addSink("sink-topic", SINK_TOPIC_1, processorNames); return topology; } private Topology setupGlobalStoreTopology(final String... sourceTopicNames) { if (sourceTopicNames.length == 0) { throw new IllegalArgumentException("sourceTopicNames cannot be empty"); } final Topology topology = new Topology(); for (final String sourceTopicName : sourceTopicNames) { topology.addGlobalStore( Stores.keyValueStoreBuilder( Stores.inMemoryKeyValueStore( sourceTopicName + "-globalStore"), null, null) .withLoggingDisabled(), sourceTopicName, null, null, sourceTopicName, sourceTopicName + "-processor", () -> new Processor<Object, Object, Void, Void>() { KeyValueStore<Object, Object> store; @SuppressWarnings("unchecked") @Override public void init(final ProcessorContext<Void, Void> context) { store = context.getStateStore(sourceTopicName + "-globalStore"); } @Override public void process(final Record<Object, Object> record) { store.put(record.key(), record.value()); } } ); } return topology; } private Topology setupTopologyWithInternalTopic(final String firstTableName, final String secondTableName, final String joinName) { final StreamsBuilder builder = new StreamsBuilder(); final KTable<Object, Long> t1 = builder.stream(SOURCE_TOPIC_1) .selectKey((k, v) -> v) .groupByKey() .count(Materialized.as(firstTableName)); builder.table(SOURCE_TOPIC_2, Materialized.as(secondTableName)) .join(t1, v -> v, (v1, v2) -> v2, TableJoined.as(joinName)); return builder.build(config); } @Test public void shouldNotRequireParameters() { new TopologyTestDriver(setupSingleProcessorTopology(), config); } @Test public void shouldInitProcessor() { testDriver = new TopologyTestDriver(setupSingleProcessorTopology(), config); assertTrue(mockProcessors.get(0).initialized); } @Test public void shouldCloseProcessor() { testDriver = new TopologyTestDriver(setupSingleProcessorTopology(), config); testDriver.close(); assertTrue(mockProcessors.get(0).closed); // As testDriver is already closed, bypassing @AfterEach tearDown testDriver.close(). testDriver = null; } @Test public void shouldThrowForUnknownTopic() { testDriver = new TopologyTestDriver(new Topology()); assertThrows( IllegalArgumentException.class, () -> testDriver.pipeRecord( "unknownTopic", new TestRecord<>((byte[]) null), new ByteArraySerializer(), new ByteArraySerializer(), Instant.now()) ); } @Test public void shouldThrowForMissingTime() { testDriver = new TopologyTestDriver(new Topology()); assertThrows( IllegalStateException.class, () -> testDriver.pipeRecord( SINK_TOPIC_1, new TestRecord<>("value"), new StringSerializer(), new StringSerializer(), null)); } @Test public void shouldThrowNoSuchElementExceptionForUnusedOutputTopicWithDynamicRouting() { testDriver = new TopologyTestDriver(setupSourceSinkTopology(), config); final TestOutputTopic<String, String> outputTopic = new TestOutputTopic<>( testDriver, "unused-topic", new StringDeserializer(), new StringDeserializer() ); assertTrue(outputTopic.isEmpty()); assertThrows(NoSuchElementException.class, outputTopic::readRecord); } @Test public void shouldCaptureSinkTopicNamesIfWrittenInto() { testDriver = new TopologyTestDriver(setupSourceSinkTopology(), config); assertThat(testDriver.producedTopicNames(), is(Collections.emptySet())); pipeRecord(SOURCE_TOPIC_1, testRecord1); assertThat(testDriver.producedTopicNames(), hasItem(SINK_TOPIC_1)); } @Test public void shouldCaptureInternalTopicNamesIfWrittenInto() { testDriver = new TopologyTestDriver( setupTopologyWithInternalTopic("table1", "table2", "join"), config ); assertThat(testDriver.producedTopicNames(), is(Collections.emptySet())); pipeRecord(SOURCE_TOPIC_1, testRecord1); assertThat( testDriver.producedTopicNames(), equalTo(Set.of( config.getProperty(StreamsConfig.APPLICATION_ID_CONFIG) + "-table1-repartition", config.getProperty(StreamsConfig.APPLICATION_ID_CONFIG) + "-table1-changelog" )) ); pipeRecord(SOURCE_TOPIC_2, testRecord1); assertThat( testDriver.producedTopicNames(), equalTo(Set.of( config.getProperty(StreamsConfig.APPLICATION_ID_CONFIG) + "-table1-repartition", config.getProperty(StreamsConfig.APPLICATION_ID_CONFIG) + "-table1-changelog", config.getProperty(StreamsConfig.APPLICATION_ID_CONFIG) + "-table2-changelog", config.getProperty(StreamsConfig.APPLICATION_ID_CONFIG) + "-join-subscription-registration-topic", config.getProperty(StreamsConfig.APPLICATION_ID_CONFIG) + "-join-subscription-store-changelog", config.getProperty(StreamsConfig.APPLICATION_ID_CONFIG) + "-join-subscription-response-topic" )) ); } @Test public void shouldCaptureGlobalTopicNameIfWrittenInto() { final StreamsBuilder builder = new StreamsBuilder(); builder.globalTable(SOURCE_TOPIC_1, Materialized.as("globalTable")); builder.stream(SOURCE_TOPIC_2).to(SOURCE_TOPIC_1); testDriver = new TopologyTestDriver(builder.build(), config); assertThat(testDriver.producedTopicNames(), is(Collections.emptySet())); pipeRecord(SOURCE_TOPIC_2, testRecord1); assertThat( testDriver.producedTopicNames(), equalTo(Collections.singleton(SOURCE_TOPIC_1)) ); } @Test public void shouldProcessRecordForTopic() { testDriver = new TopologyTestDriver(setupSourceSinkTopology(), config); pipeRecord(SOURCE_TOPIC_1, testRecord1); final ProducerRecord<byte[], byte[]> outputRecord = testDriver.readRecord(SINK_TOPIC_1); assertArrayEquals(key1, outputRecord.key()); assertArrayEquals(value1, outputRecord.value()); assertEquals(SINK_TOPIC_1, outputRecord.topic()); } @Test public void shouldSetRecordMetadata() { testDriver = new TopologyTestDriver(setupSingleProcessorTopology(), config); pipeRecord(SOURCE_TOPIC_1, testRecord1); final List<TTDTestRecord> processedRecords = mockProcessors.get(0).processedRecords; assertEquals(1, processedRecords.size()); final TTDTestRecord record = processedRecords.get(0); final TTDTestRecord expectedResult = new TTDTestRecord(SOURCE_TOPIC_1, testRecord1, 0L); assertThat(record, equalTo(expectedResult)); } private void pipeRecord(final String topic, final TestRecord<byte[], byte[]> record) { testDriver.pipeRecord(topic, record, new ByteArraySerializer(), new ByteArraySerializer(), null); } @Test public void shouldSendRecordViaCorrectSourceTopic() { testDriver = new TopologyTestDriver(setupMultipleSourceTopology(SOURCE_TOPIC_1, SOURCE_TOPIC_2), config); final List<TTDTestRecord> processedRecords1 = mockProcessors.get(0).processedRecords; final List<TTDTestRecord> processedRecords2 = mockProcessors.get(1).processedRecords; final TestInputTopic<byte[], byte[]> inputTopic1 = testDriver.createInputTopic(SOURCE_TOPIC_1, new ByteArraySerializer(), new ByteArraySerializer()); final TestInputTopic<byte[], byte[]> inputTopic2 = testDriver.createInputTopic(SOURCE_TOPIC_2, new ByteArraySerializer(), new ByteArraySerializer()); inputTopic1.pipeInput(new TestRecord<>(key1, value1, headers, timestamp1)); assertEquals(1, processedRecords1.size()); assertEquals(0, processedRecords2.size()); TTDTestRecord record = processedRecords1.get(0); TTDTestRecord expectedResult = new TTDTestRecord(key1, value1, headers, timestamp1, 0L, SOURCE_TOPIC_1); assertThat(record, equalTo(expectedResult)); inputTopic2.pipeInput(new TestRecord<>(key2, value2, Instant.ofEpochMilli(timestamp2))); assertEquals(1, processedRecords1.size()); assertEquals(1, processedRecords2.size()); record = processedRecords2.get(0); expectedResult = new TTDTestRecord(key2, value2, new RecordHeaders((Iterable<Header>) null), timestamp2, 0L, SOURCE_TOPIC_2); assertThat(record, equalTo(expectedResult)); } @Test public void shouldUseSourceSpecificDeserializers() { final Topology topology = new Topology(); final String sourceName1 = "source-1"; final String sourceName2 = "source-2"; final String processor = "processor"; topology.addSource(sourceName1, Serdes.Long().deserializer(), Serdes.String().deserializer(), SOURCE_TOPIC_1); topology.addSource(sourceName2, Serdes.Integer().deserializer(), Serdes.Double().deserializer(), SOURCE_TOPIC_2); topology.addProcessor(processor, new MockProcessorSupplier(), sourceName1, sourceName2); topology.addSink( "sink", SINK_TOPIC_1, (topic, data) -> { if (data instanceof Long) { return Serdes.Long().serializer().serialize(topic, (Long) data); } return Serdes.Integer().serializer().serialize(topic, (Integer) data); }, (topic, data) -> { if (data instanceof String) { return Serdes.String().serializer().serialize(topic, (String) data); } return Serdes.Double().serializer().serialize(topic, (Double) data); }, processor); testDriver = new TopologyTestDriver(topology); final Long source1Key = 42L; final String source1Value = "anyString"; final Integer source2Key = 73; final Double source2Value = 3.14; final TestRecord<Long, String> consumerRecord1 = new TestRecord<>(source1Key, source1Value); final TestRecord<Integer, Double> consumerRecord2 = new TestRecord<>(source2Key, source2Value); testDriver.pipeRecord(SOURCE_TOPIC_1, consumerRecord1, Serdes.Long().serializer(), Serdes.String().serializer(), Instant.now()); final TestRecord<Long, String> result1 = testDriver.readRecord(SINK_TOPIC_1, Serdes.Long().deserializer(), Serdes.String().deserializer()); assertThat(result1.getKey(), equalTo(source1Key)); assertThat(result1.getValue(), equalTo(source1Value)); testDriver.pipeRecord(SOURCE_TOPIC_2, consumerRecord2, Serdes.Integer().serializer(), Serdes.Double().serializer(), Instant.now()); final TestRecord<Integer, Double> result2 = testDriver.readRecord(SINK_TOPIC_1, Serdes.Integer().deserializer(), Serdes.Double().deserializer()); assertThat(result2.getKey(), equalTo(source2Key)); assertThat(result2.getValue(), equalTo(source2Value)); } @Test public void shouldPassRecordHeadersIntoSerializersAndDeserializers() { testDriver = new TopologyTestDriver(setupSourceSinkTopology(), config); final AtomicBoolean passedHeadersToKeySerializer = new AtomicBoolean(false); final AtomicBoolean passedHeadersToValueSerializer = new AtomicBoolean(false); final AtomicBoolean passedHeadersToKeyDeserializer = new AtomicBoolean(false); final AtomicBoolean passedHeadersToValueDeserializer = new AtomicBoolean(false); final Serializer<byte[]> keySerializer = new ByteArraySerializer() { @Override public byte[] serialize(final String topic, final Headers headers, final byte[] data) { passedHeadersToKeySerializer.set(true); return serialize(topic, data); } }; final Serializer<byte[]> valueSerializer = new ByteArraySerializer() { @Override public byte[] serialize(final String topic, final Headers headers, final byte[] data) { passedHeadersToValueSerializer.set(true); return serialize(topic, data); } }; final Deserializer<byte[]> keyDeserializer = new ByteArrayDeserializer() { @Override public byte[] deserialize(final String topic, final Headers headers, final byte[] data) { passedHeadersToKeyDeserializer.set(true); return deserialize(topic, data); } }; final Deserializer<byte[]> valueDeserializer = new ByteArrayDeserializer() { @Override public byte[] deserialize(final String topic, final Headers headers, final byte[] data) { passedHeadersToValueDeserializer.set(true); return deserialize(topic, data); } }; final TestInputTopic<byte[], byte[]> inputTopic = testDriver.createInputTopic(SOURCE_TOPIC_1, keySerializer, valueSerializer); final TestOutputTopic<byte[], byte[]> outputTopic = testDriver.createOutputTopic(SINK_TOPIC_1, keyDeserializer, valueDeserializer); inputTopic.pipeInput(testRecord1); outputTopic.readRecord(); assertThat(passedHeadersToKeySerializer.get(), equalTo(true)); assertThat(passedHeadersToValueSerializer.get(), equalTo(true)); assertThat(passedHeadersToKeyDeserializer.get(), equalTo(true)); assertThat(passedHeadersToValueDeserializer.get(), equalTo(true)); } @Test public void shouldUseSinkSpecificSerializers() { final Topology topology = new Topology(); final String sourceName1 = "source-1"; final String sourceName2 = "source-2"; topology.addSource(sourceName1, Serdes.Long().deserializer(), Serdes.String().deserializer(), SOURCE_TOPIC_1); topology.addSource(sourceName2, Serdes.Integer().deserializer(), Serdes.Double().deserializer(), SOURCE_TOPIC_2); topology.addSink("sink-1", SINK_TOPIC_1, Serdes.Long().serializer(), Serdes.String().serializer(), sourceName1); topology.addSink("sink-2", SINK_TOPIC_2, Serdes.Integer().serializer(), Serdes.Double().serializer(), sourceName2); testDriver = new TopologyTestDriver(topology); final Long source1Key = 42L; final String source1Value = "anyString"; final Integer source2Key = 73; final Double source2Value = 3.14; final TestRecord<Long, String> consumerRecord1 = new TestRecord<>(source1Key, source1Value); final TestRecord<Integer, Double> consumerRecord2 = new TestRecord<>(source2Key, source2Value); testDriver.pipeRecord(SOURCE_TOPIC_1, consumerRecord1, Serdes.Long().serializer(), Serdes.String().serializer(), Instant.now()); final TestRecord<Long, String> result1 = testDriver.readRecord(SINK_TOPIC_1, Serdes.Long().deserializer(), Serdes.String().deserializer()); assertThat(result1.getKey(), equalTo(source1Key)); assertThat(result1.getValue(), equalTo(source1Value)); testDriver.pipeRecord(SOURCE_TOPIC_2, consumerRecord2, Serdes.Integer().serializer(), Serdes.Double().serializer(), Instant.now()); final TestRecord<Integer, Double> result2 = testDriver.readRecord(SINK_TOPIC_2, Serdes.Integer().deserializer(), Serdes.Double().deserializer()); assertThat(result2.getKey(), equalTo(source2Key)); assertThat(result2.getValue(), equalTo(source2Value)); } @Test public void shouldForwardRecordsFromSubtopologyToSubtopology() { testDriver = new TopologyTestDriver(setupTopologyWithTwoSubtopologies(), config); pipeRecord(SOURCE_TOPIC_1, testRecord1); ProducerRecord<byte[], byte[]> outputRecord = testDriver.readRecord(SINK_TOPIC_1); assertArrayEquals(key1, outputRecord.key()); assertArrayEquals(value1, outputRecord.value()); assertEquals(SINK_TOPIC_1, outputRecord.topic()); outputRecord = testDriver.readRecord(SINK_TOPIC_2); assertArrayEquals(key1, outputRecord.key()); assertArrayEquals(value1, outputRecord.value()); assertEquals(SINK_TOPIC_2, outputRecord.topic()); } @Test public void shouldPopulateGlobalStore() { testDriver = new TopologyTestDriver(setupGlobalStoreTopology(SOURCE_TOPIC_1), config); final KeyValueStore<byte[], byte[]> globalStore = testDriver.getKeyValueStore(SOURCE_TOPIC_1 + "-globalStore"); assertNotNull(globalStore); assertNotNull(testDriver.getAllStateStores().get(SOURCE_TOPIC_1 + "-globalStore")); pipeRecord(SOURCE_TOPIC_1, testRecord1); assertThat(globalStore.get(testRecord1.key()), is(testRecord1.value())); } @Test public void shouldPunctuateOnStreamsTime() { final MockPunctuator mockPunctuator = new MockPunctuator(); testDriver = new TopologyTestDriver( setupSingleProcessorTopology(10L, PunctuationType.STREAM_TIME, mockPunctuator), config ); final List<Long> expectedPunctuations = new LinkedList<>(); expectedPunctuations.add(42L); pipeRecord(SOURCE_TOPIC_1, new TestRecord<>(key1, value1, null, 42L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); pipeRecord(SOURCE_TOPIC_1, new TestRecord<>(key1, value1, null, 42L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); expectedPunctuations.add(51L); pipeRecord(SOURCE_TOPIC_1, new TestRecord<>(key1, value1, null, 51L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); pipeRecord(SOURCE_TOPIC_1, new TestRecord<>(key1, value1, null, 52L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); expectedPunctuations.add(61L); pipeRecord(SOURCE_TOPIC_1, new TestRecord<>(key1, value1, null, 61L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); pipeRecord(SOURCE_TOPIC_1, new TestRecord<>(key1, value1, null, 65L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); expectedPunctuations.add(71L); pipeRecord(SOURCE_TOPIC_1, new TestRecord<>(key1, value1, null, 71L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); pipeRecord(SOURCE_TOPIC_1, new TestRecord<>(key1, value1, null, 72L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); expectedPunctuations.add(95L); pipeRecord(SOURCE_TOPIC_1, new TestRecord<>(key1, value1, null, 95L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); expectedPunctuations.add(101L); pipeRecord(SOURCE_TOPIC_1, new TestRecord<>(key1, value1, null, 101L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); pipeRecord(SOURCE_TOPIC_1, new TestRecord<>(key1, value1, null, 102L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); } @Test public void shouldPunctuateOnWallClockTime() { final MockPunctuator mockPunctuator = new MockPunctuator(); testDriver = new TopologyTestDriver( setupSingleProcessorTopology(10L, PunctuationType.WALL_CLOCK_TIME, mockPunctuator), config, Instant.ofEpochMilli(0L)); final List<Long> expectedPunctuations = new LinkedList<>(); testDriver.advanceWallClockTime(Duration.ofMillis(5L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); expectedPunctuations.add(14L); testDriver.advanceWallClockTime(Duration.ofMillis(9L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); testDriver.advanceWallClockTime(Duration.ofMillis(1L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); expectedPunctuations.add(35L); testDriver.advanceWallClockTime(Duration.ofMillis(20L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); expectedPunctuations.add(40L); testDriver.advanceWallClockTime(Duration.ofMillis(5L)); assertThat(mockPunctuator.punctuatedAt, equalTo(expectedPunctuations)); } @Test public void shouldReturnAllStores() { final Topology topology = setupSourceSinkTopology(); topology.addProcessor("processor", new MockProcessorSupplier(), "source"); topology.addStateStore( new KeyValueStoreBuilder<>( Stores.inMemoryKeyValueStore("store"), Serdes.ByteArray(), Serdes.ByteArray(), Time.SYSTEM), "processor"); topology.addGlobalStore( new KeyValueStoreBuilder<>( Stores.inMemoryKeyValueStore("globalStore"), Serdes.ByteArray(), Serdes.ByteArray(), Time.SYSTEM).withLoggingDisabled(), "sourceProcessorName", Serdes.ByteArray().deserializer(), Serdes.ByteArray().deserializer(), "globalTopicName", "globalProcessorName", voidProcessorSupplier); testDriver = new TopologyTestDriver(topology, config); final Set<String> expectedStoreNames = new HashSet<>(); expectedStoreNames.add("store"); expectedStoreNames.add("globalStore"); final Map<String, StateStore> allStores = testDriver.getAllStateStores(); assertThat(allStores.keySet(), equalTo(expectedStoreNames)); for (final StateStore store : allStores.values()) { assertNotNull(store); } } @Test public void shouldReturnCorrectPersistentStoreTypeOnly() { shouldReturnCorrectStoreTypeOnly(true); } @Test public void shouldReturnCorrectInMemoryStoreTypeOnly() { shouldReturnCorrectStoreTypeOnly(false); } private void shouldReturnCorrectStoreTypeOnly(final boolean persistent) { final String keyValueStoreName = "keyValueStore"; final String timestampedKeyValueStoreName = "keyValueTimestampStore"; final String versionedKeyValueStoreName = "keyValueVersionedStore"; final String windowStoreName = "windowStore"; final String timestampedWindowStoreName = "windowTimestampStore"; final String sessionStoreName = "sessionStore"; final String globalKeyValueStoreName = "globalKeyValueStore"; final String globalTimestampedKeyValueStoreName = "globalKeyValueTimestampStore"; final String globalVersionedKeyValueStoreName = "globalKeyValueVersionedStore"; final Topology topology = setupSingleProcessorTopology(); addStoresToTopology( topology, persistent, keyValueStoreName, timestampedKeyValueStoreName, versionedKeyValueStoreName, windowStoreName, timestampedWindowStoreName, sessionStoreName, globalKeyValueStoreName, globalTimestampedKeyValueStoreName, globalVersionedKeyValueStoreName); testDriver = new TopologyTestDriver(topology, config); // verify state stores assertNotNull(testDriver.getKeyValueStore(keyValueStoreName)); assertNull(testDriver.getTimestampedKeyValueStore(keyValueStoreName)); assertNull(testDriver.getVersionedKeyValueStore(keyValueStoreName)); assertNull(testDriver.getWindowStore(keyValueStoreName)); assertNull(testDriver.getTimestampedWindowStore(keyValueStoreName)); assertNull(testDriver.getSessionStore(keyValueStoreName)); assertNotNull(testDriver.getKeyValueStore(timestampedKeyValueStoreName)); assertNotNull(testDriver.getTimestampedKeyValueStore(timestampedKeyValueStoreName)); assertNull(testDriver.getVersionedKeyValueStore(timestampedKeyValueStoreName)); assertNull(testDriver.getWindowStore(timestampedKeyValueStoreName)); assertNull(testDriver.getTimestampedWindowStore(timestampedKeyValueStoreName)); assertNull(testDriver.getSessionStore(timestampedKeyValueStoreName)); if (persistent) { // versioned stores do not offer an in-memory version yet, so nothing to test/verify unless persistent assertNull(testDriver.getKeyValueStore(versionedKeyValueStoreName)); assertNull(testDriver.getTimestampedKeyValueStore(versionedKeyValueStoreName)); assertNotNull(testDriver.getVersionedKeyValueStore(versionedKeyValueStoreName)); assertNull(testDriver.getWindowStore(versionedKeyValueStoreName)); assertNull(testDriver.getTimestampedWindowStore(versionedKeyValueStoreName)); assertNull(testDriver.getSessionStore(versionedKeyValueStoreName)); } assertNull(testDriver.getKeyValueStore(windowStoreName)); assertNull(testDriver.getTimestampedKeyValueStore(windowStoreName)); assertNull(testDriver.getVersionedKeyValueStore(windowStoreName)); assertNotNull(testDriver.getWindowStore(windowStoreName)); assertNull(testDriver.getTimestampedWindowStore(windowStoreName)); assertNull(testDriver.getSessionStore(windowStoreName)); assertNull(testDriver.getKeyValueStore(timestampedWindowStoreName)); assertNull(testDriver.getTimestampedKeyValueStore(timestampedWindowStoreName)); assertNull(testDriver.getVersionedKeyValueStore(timestampedWindowStoreName)); assertNotNull(testDriver.getWindowStore(timestampedWindowStoreName)); assertNotNull(testDriver.getTimestampedWindowStore(timestampedWindowStoreName)); assertNull(testDriver.getSessionStore(timestampedWindowStoreName)); assertNull(testDriver.getKeyValueStore(sessionStoreName)); assertNull(testDriver.getTimestampedKeyValueStore(sessionStoreName)); assertNull(testDriver.getVersionedKeyValueStore(sessionStoreName)); assertNull(testDriver.getWindowStore(sessionStoreName)); assertNull(testDriver.getTimestampedWindowStore(sessionStoreName)); assertNotNull(testDriver.getSessionStore(sessionStoreName)); // verify global stores assertNotNull(testDriver.getKeyValueStore(globalKeyValueStoreName)); assertNull(testDriver.getTimestampedKeyValueStore(globalKeyValueStoreName)); assertNull(testDriver.getVersionedKeyValueStore(globalKeyValueStoreName)); assertNull(testDriver.getWindowStore(globalKeyValueStoreName)); assertNull(testDriver.getTimestampedWindowStore(globalKeyValueStoreName)); assertNull(testDriver.getSessionStore(globalKeyValueStoreName)); assertNotNull(testDriver.getKeyValueStore(globalTimestampedKeyValueStoreName)); assertNotNull(testDriver.getTimestampedKeyValueStore(globalTimestampedKeyValueStoreName)); assertNull(testDriver.getVersionedKeyValueStore(globalTimestampedKeyValueStoreName)); assertNull(testDriver.getWindowStore(globalTimestampedKeyValueStoreName)); assertNull(testDriver.getTimestampedWindowStore(globalTimestampedKeyValueStoreName)); assertNull(testDriver.getSessionStore(globalTimestampedKeyValueStoreName)); if (persistent) { // versioned stores do not offer an in-memory version yet, so nothing to test/verify unless persistent assertNull(testDriver.getKeyValueStore(globalVersionedKeyValueStoreName)); assertNull(testDriver.getTimestampedKeyValueStore(globalVersionedKeyValueStoreName)); assertNotNull(testDriver.getVersionedKeyValueStore(globalVersionedKeyValueStoreName)); assertNull(testDriver.getWindowStore(globalVersionedKeyValueStoreName)); assertNull(testDriver.getTimestampedWindowStore(globalVersionedKeyValueStoreName)); assertNull(testDriver.getSessionStore(globalVersionedKeyValueStoreName)); } } @Test public void shouldThrowIfInMemoryBuiltInStoreIsAccessedWithUntypedMethod() { shouldThrowIfBuiltInStoreIsAccessedWithUntypedMethod(false); } @Test public void shouldThrowIfPersistentBuiltInStoreIsAccessedWithUntypedMethod() { shouldThrowIfBuiltInStoreIsAccessedWithUntypedMethod(true); } private void shouldThrowIfBuiltInStoreIsAccessedWithUntypedMethod(final boolean persistent) { final String keyValueStoreName = "keyValueStore"; final String timestampedKeyValueStoreName = "keyValueTimestampStore"; final String versionedKeyValueStoreName = "keyValueVersionedStore"; final String windowStoreName = "windowStore"; final String timestampedWindowStoreName = "windowTimestampStore"; final String sessionStoreName = "sessionStore"; final String globalKeyValueStoreName = "globalKeyValueStore"; final String globalTimestampedKeyValueStoreName = "globalKeyValueTimestampStore"; final String globalVersionedKeyValueStoreName = "globalKeyValueVersionedStore"; final Topology topology = setupSingleProcessorTopology(); addStoresToTopology( topology, persistent, keyValueStoreName, timestampedKeyValueStoreName, versionedKeyValueStoreName, windowStoreName, timestampedWindowStoreName, sessionStoreName, globalKeyValueStoreName, globalTimestampedKeyValueStoreName, globalVersionedKeyValueStoreName); testDriver = new TopologyTestDriver(topology, config); { final IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> testDriver.getStateStore(keyValueStoreName)); assertThat( e.getMessage(), equalTo("Store " + keyValueStoreName + " is a key-value store and should be accessed via `getKeyValueStore()`")); } { final IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> testDriver.getStateStore(timestampedKeyValueStoreName)); assertThat( e.getMessage(), equalTo("Store " + timestampedKeyValueStoreName + " is a timestamped key-value store and should be accessed via `getTimestampedKeyValueStore()`")); } if (persistent) { // versioned stores do not offer an in-memory version yet, so nothing to test/verify unless persistent final IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> testDriver.getStateStore(versionedKeyValueStoreName)); assertThat( e.getMessage(), equalTo("Store " + versionedKeyValueStoreName + " is a versioned key-value store and should be accessed via `getVersionedKeyValueStore()`")); } { final IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> testDriver.getStateStore(windowStoreName)); assertThat( e.getMessage(), equalTo("Store " + windowStoreName + " is a window store and should be accessed via `getWindowStore()`")); } { final IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> testDriver.getStateStore(timestampedWindowStoreName)); assertThat( e.getMessage(), equalTo("Store " + timestampedWindowStoreName + " is a timestamped window store and should be accessed via `getTimestampedWindowStore()`")); } { final IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> testDriver.getStateStore(sessionStoreName)); assertThat( e.getMessage(), equalTo("Store " + sessionStoreName + " is a session store and should be accessed via `getSessionStore()`")); } { final IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> testDriver.getStateStore(globalKeyValueStoreName)); assertThat( e.getMessage(), equalTo("Store " + globalKeyValueStoreName + " is a key-value store and should be accessed via `getKeyValueStore()`")); } { final IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> testDriver.getStateStore(globalTimestampedKeyValueStoreName)); assertThat( e.getMessage(), equalTo("Store " + globalTimestampedKeyValueStoreName + " is a timestamped key-value store and should be accessed via `getTimestampedKeyValueStore()`")); } if (persistent) { // versioned stores do not offer an in-memory version yet, so nothing to test/verify unless persistent final IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> testDriver.getStateStore(globalVersionedKeyValueStoreName)); assertThat( e.getMessage(), equalTo("Store " + globalVersionedKeyValueStoreName + " is a versioned key-value store and should be accessed via `getVersionedKeyValueStore()`")); } } final ProcessorSupplier<byte[], byte[], Void, Void> voidProcessorSupplier = () -> new Processor<byte[], byte[], Void, Void>() { @Override public void process(final Record<byte[], byte[]> record) { } }; private void addStoresToTopology(final Topology topology, final boolean persistent, final String keyValueStoreName, final String timestampedKeyValueStoreName, final String versionedKeyValueStoreName, final String windowStoreName, final String timestampedWindowStoreName, final String sessionStoreName, final String globalKeyValueStoreName, final String globalTimestampedKeyValueStoreName, final String globalVersionedKeyValueStoreName) { // add state stores topology.addStateStore( Stores.keyValueStoreBuilder( persistent ? Stores.persistentKeyValueStore(keyValueStoreName) : Stores.inMemoryKeyValueStore(keyValueStoreName), Serdes.ByteArray(), Serdes.ByteArray() ), "processor"); topology.addStateStore( Stores.timestampedKeyValueStoreBuilder( persistent ? Stores.persistentTimestampedKeyValueStore(timestampedKeyValueStoreName) : Stores.inMemoryKeyValueStore(timestampedKeyValueStoreName), Serdes.ByteArray(), Serdes.ByteArray() ), "processor"); if (persistent) { // versioned stores do not offer an in-memory version yet topology.addStateStore( Stores.versionedKeyValueStoreBuilder( Stores.persistentVersionedKeyValueStore(versionedKeyValueStoreName, Duration.ofMillis(1000L)), Serdes.ByteArray(), Serdes.ByteArray() ), "processor"); } topology.addStateStore( Stores.windowStoreBuilder( persistent ? Stores.persistentWindowStore(windowStoreName, Duration.ofMillis(1000L), Duration.ofMillis(100L), false) : Stores.inMemoryWindowStore(windowStoreName, Duration.ofMillis(1000L), Duration.ofMillis(100L), false), Serdes.ByteArray(), Serdes.ByteArray() ), "processor"); topology.addStateStore( Stores.timestampedWindowStoreBuilder( persistent ? Stores.persistentTimestampedWindowStore(timestampedWindowStoreName, Duration.ofMillis(1000L), Duration.ofMillis(100L), false) : Stores.inMemoryWindowStore(timestampedWindowStoreName, Duration.ofMillis(1000L), Duration.ofMillis(100L), false), Serdes.ByteArray(), Serdes.ByteArray() ), "processor"); topology.addStateStore( persistent ? Stores.sessionStoreBuilder( Stores.persistentSessionStore(sessionStoreName, Duration.ofMillis(1000L)), Serdes.ByteArray(), Serdes.ByteArray()) : Stores.sessionStoreBuilder( Stores.inMemorySessionStore(sessionStoreName, Duration.ofMillis(1000L)), Serdes.ByteArray(), Serdes.ByteArray()), "processor"); // add global stores topology.addGlobalStore( persistent ? Stores.keyValueStoreBuilder( Stores.persistentKeyValueStore(globalKeyValueStoreName), Serdes.ByteArray(), Serdes.ByteArray() ).withLoggingDisabled() : Stores.keyValueStoreBuilder( Stores.inMemoryKeyValueStore(globalKeyValueStoreName), Serdes.ByteArray(), Serdes.ByteArray() ).withLoggingDisabled(), "sourceDummy1", Serdes.ByteArray().deserializer(), Serdes.ByteArray().deserializer(), "topicDummy1", "processorDummy1", voidProcessorSupplier); topology.addGlobalStore( persistent ? Stores.timestampedKeyValueStoreBuilder( Stores.persistentTimestampedKeyValueStore(globalTimestampedKeyValueStoreName), Serdes.ByteArray(), Serdes.ByteArray() ).withLoggingDisabled() : Stores.timestampedKeyValueStoreBuilder( Stores.inMemoryKeyValueStore(globalTimestampedKeyValueStoreName), Serdes.ByteArray(), Serdes.ByteArray() ).withLoggingDisabled(), "sourceDummy2", Serdes.ByteArray().deserializer(), Serdes.ByteArray().deserializer(), "topicDummy2", "processorDummy2", voidProcessorSupplier); if (persistent) { // versioned stores do not offer an in-memory version yet topology.addGlobalStore( Stores.versionedKeyValueStoreBuilder( Stores.persistentVersionedKeyValueStore(globalVersionedKeyValueStoreName, Duration.ofMillis(1000L)), Serdes.ByteArray(), Serdes.ByteArray() ).withLoggingDisabled(), "sourceDummy3", Serdes.ByteArray().deserializer(), Serdes.ByteArray().deserializer(), "topicDummy3", "processorDummy3", voidProcessorSupplier); } } @Test public void shouldReturnAllStoresNames() { final Topology topology = setupSourceSinkTopology(); topology.addStateStore( new KeyValueStoreBuilder<>( Stores.inMemoryKeyValueStore("store"), Serdes.ByteArray(), Serdes.ByteArray(), Time.SYSTEM)); topology.addGlobalStore( new KeyValueStoreBuilder<>( Stores.inMemoryKeyValueStore("globalStore"), Serdes.ByteArray(), Serdes.ByteArray(), Time.SYSTEM).withLoggingDisabled(), "sourceProcessorName", Serdes.ByteArray().deserializer(), Serdes.ByteArray().deserializer(), "globalTopicName", "globalProcessorName", voidProcessorSupplier); testDriver = new TopologyTestDriver(topology, config); final Set<String> expectedStoreNames = new HashSet<>(); expectedStoreNames.add("store"); expectedStoreNames.add("globalStore"); assertThat(testDriver.getAllStateStores().keySet(), equalTo(expectedStoreNames)); } private void setup() { setup(Stores.inMemoryKeyValueStore("aggStore")); } private void setup(final KeyValueBytesStoreSupplier storeSupplier) { final Topology topology = new Topology(); topology.addSource("sourceProcessor", "input-topic"); topology.addProcessor("aggregator", new CustomMaxAggregatorSupplier(), "sourceProcessor"); topology.addStateStore(Stores.keyValueStoreBuilder( storeSupplier, Serdes.String(), Serdes.Long()), "aggregator"); topology.addSink("sinkProcessor", "result-topic", "aggregator"); config.setProperty(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); config.setProperty(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.Long().getClass().getName()); testDriver = new TopologyTestDriver(topology, config); store = testDriver.getKeyValueStore("aggStore"); store.put("a", 21L); } private void pipeInput(final String topic, final String key, final Long value, final Long time) { testDriver.pipeRecord(topic, new TestRecord<>(key, value, null, time), new StringSerializer(), new LongSerializer(), null); } private void compareKeyValue(final TestRecord<String, Long> record, final String key, final Long value) { assertThat(record.getKey(), equalTo(key)); assertThat(record.getValue(), equalTo(value)); } @Test public void shouldFlushStoreForFirstInput() { setup(); pipeInput("input-topic", "a", 1L, 9999L); compareKeyValue(testDriver.readRecord("result-topic", stringDeserializer, longDeserializer), "a", 21L); assertTrue(testDriver.isEmpty("result-topic")); } @Test public void shouldNotUpdateStoreForSmallerValue() { setup(); pipeInput("input-topic", "a", 1L, 9999L); assertThat(store.get("a"), equalTo(21L)); compareKeyValue(testDriver.readRecord("result-topic", stringDeserializer, longDeserializer), "a", 21L); assertTrue(testDriver.isEmpty("result-topic")); } @Test public void shouldNotUpdateStoreForLargerValue() { setup(); pipeInput("input-topic", "a", 42L, 9999L); assertThat(store.get("a"), equalTo(42L)); compareKeyValue(testDriver.readRecord("result-topic", stringDeserializer, longDeserializer), "a", 42L); assertTrue(testDriver.isEmpty("result-topic")); } @Test public void shouldUpdateStoreForNewKey() { setup(); pipeInput("input-topic", "b", 21L, 9999L); assertThat(store.get("b"), equalTo(21L)); compareKeyValue(testDriver.readRecord("result-topic", stringDeserializer, longDeserializer), "a", 21L); compareKeyValue(testDriver.readRecord("result-topic", stringDeserializer, longDeserializer), "b", 21L); assertTrue(testDriver.isEmpty("result-topic")); } @Test public void shouldPunctuateIfEvenTimeAdvances() { setup(); pipeInput("input-topic", "a", 1L, 9999L); compareKeyValue(testDriver.readRecord("result-topic", stringDeserializer, longDeserializer), "a", 21L); pipeInput("input-topic", "a", 1L, 9999L); assertTrue(testDriver.isEmpty("result-topic")); pipeInput("input-topic", "a", 1L, 10000L); compareKeyValue(testDriver.readRecord("result-topic", stringDeserializer, longDeserializer), "a", 21L); assertTrue(testDriver.isEmpty("result-topic")); } @Test public void shouldPunctuateIfWallClockTimeAdvances() { setup(); testDriver.advanceWallClockTime(Duration.ofMillis(60000)); compareKeyValue(testDriver.readRecord("result-topic", stringDeserializer, longDeserializer), "a", 21L); assertTrue(testDriver.isEmpty("result-topic")); } private static
MockProcessorSupplier
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/SingLeTableWithEmbeddedIdTest.java
{ "start": 2451, "end": 2765 }
class ____ { @Id Long id; @Column String field; public Entity1() { } public Entity1(Long id, String field) { this.id = id; this.field = field; } public Long getId() { return id; } public String getField() { return field; } } @Entity(name = "Entity2") public static
Entity1
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/authorization/AuthorizationManagers.java
{ "start": 6018, "end": 6379 }
class ____ extends AuthorizationDecision { private final AuthorizationResult result; private NotAuthorizationDecision(AuthorizationResult result) { super(!result.isGranted()); this.result = result; } @Override public String toString() { return "NotAuthorizationDecision [result=" + this.result + ']'; } } private
NotAuthorizationDecision
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ser/std/StdContainerSerializer.java
{ "start": 646, "end": 6539 }
class ____<T> extends StdSerializer<T> { /** * Property that contains values handled by this serializer, if known; `null` * for root value serializers (ones directly called by {@link ObjectMapper} and * {@link ObjectWriter}). * * @since 3.0 */ protected final BeanProperty _property; /** * If value type cannot be statically determined, mapping from * runtime value types to serializers are stored in this object. * * @since 3.0 (in 2.x subtypes contained it) */ protected PropertySerializerMap _dynamicValueSerializers; /* /********************************************************************** /* Construction, initialization /********************************************************************** */ protected StdContainerSerializer(Class<?> t) { this(t, null); } protected StdContainerSerializer(Class<?> t, BeanProperty prop) { super(t); _property = prop; _dynamicValueSerializers = PropertySerializerMap.emptyForProperties(); } protected StdContainerSerializer(JavaType fullType, BeanProperty prop) { super(fullType); _property = prop; _dynamicValueSerializers = PropertySerializerMap.emptyForProperties(); } protected StdContainerSerializer(StdContainerSerializer<?> src) { this(src, src._property); } protected StdContainerSerializer(StdContainerSerializer<?> src, BeanProperty prop) { super(src._handledType); _property = prop; // 16-Apr-2018, tatu: Could retain, possibly, in some cases... but may be // dangerous as general practice so reset _dynamicValueSerializers = PropertySerializerMap.emptyForProperties(); } /** * Factory(-like) method that can be used to construct a new container * serializer that uses specified {@link TypeSerializer} for decorating * contained values with additional type information. * * @param vts Type serializer to use for contained values; can be null, * in which case 'this' serializer is returned as is * @return Serializer instance that uses given type serializer for values if * that is possible (or if not, just 'this' serializer) */ public StdContainerSerializer<?> withValueTypeSerializer(TypeSerializer vts) { if (vts == null) return this; return _withValueTypeSerializer(vts); } /* /********************************************************************** /* Extended API /********************************************************************** */ /** * Accessor for finding declared (static) element type for * type this serializer is used for. */ public abstract JavaType getContentType(); /** * Accessor for serializer used for serializing contents * (List and array elements, Map values etc) of the * container for which this serializer is used, if it is * known statically. * Note that for dynamic types this may return null; if so, * caller has to instead use {@link #getContentType()} and * {@link tools.jackson.databind.SerializationContext#findContentValueSerializer}. */ public abstract ValueSerializer<?> getContentSerializer(); /* /********************************************************************** /* Abstract methods for sub-classes to implement /********************************************************************** */ @Override public abstract boolean isEmpty(SerializationContext prov, T value); /** * Method called to determine if the given value (of type handled by * this serializer) contains exactly one element. *<p> * Note: although it might seem sensible to instead define something * like "getElementCount()" method, this would not work well for * containers that do not keep track of size (like linked lists may * not). *<p> * Note, too, that this method is only called by serializer * itself; and specifically is not used for non-array/collection types * like <code>Map</code> or <code>Map.Entry</code> instances. */ public abstract boolean hasSingleElement(T value); /* /********************************************************************** /* Helper methods for locating, caching element/value serializers /********************************************************************** */ /** * Method that needs to be implemented to allow construction of a new * serializer object with given {@link TypeSerializer}, used when * addition type information is to be embedded. */ protected abstract StdContainerSerializer<?> _withValueTypeSerializer(TypeSerializer vts); /** * @since 3.0 */ protected ValueSerializer<Object> _findAndAddDynamic(SerializationContext ctxt, Class<?> type) { PropertySerializerMap map = _dynamicValueSerializers; PropertySerializerMap.SerializerAndMapResult result = map.findAndAddSecondarySerializer(type, ctxt, _property); // did we get a new map of serializers? If so, start using it if (map != result.map) { _dynamicValueSerializers = result.map; } return result.serializer; } /** * @since 3.0 */ protected ValueSerializer<Object> _findAndAddDynamic(SerializationContext ctxt, JavaType type) { PropertySerializerMap map = _dynamicValueSerializers; PropertySerializerMap.SerializerAndMapResult result = map.findAndAddSecondarySerializer(type, ctxt, _property); // did we get a new map of serializers? If so, start using it if (map != result.map) { _dynamicValueSerializers = result.map; } return result.serializer; } }
StdContainerSerializer
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/HelloClient.java
{ "start": 219, "end": 357 }
interface ____ { @POST @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.TEXT_PLAIN) String echo(String name); }
HelloClient
java
alibaba__nacos
core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java
{ "start": 4613, "end": 19433 }
class ____ implements NacosMemberManager { private final NacosAsyncRestTemplate asyncRestTemplate = HttpClientBeanHolder.getNacosAsyncRestTemplate( Loggers.CORE); private static final int DEFAULT_SERVER_PORT = 8848; private static final String SERVER_PORT_PROPERTY = "nacos.server.main.port"; private static final String MEMBER_CHANGE_EVENT_QUEUE_SIZE_PROPERTY = "nacos.member-change-event.queue.size"; private static final int DEFAULT_MEMBER_CHANGE_EVENT_QUEUE_SIZE = 128; private static final long DEFAULT_TASK_DELAY_TIME = 5_000L; /** * Cluster node list. */ private volatile ConcurrentSkipListMap<String, Member> serverList; /** * Is this node in the cluster list. */ private static volatile boolean isInIpList = true; /** * port. */ private int port; /** * Address information for the local node. */ private String localAddress; /** * Addressing pattern instances. */ private MemberLookup lookup; /** * self member obj. */ private volatile Member self; private volatile long memberReportTs = System.currentTimeMillis(); /** * here is always the node information of the "UP" state. */ private volatile Set<String> memberAddressInfos = new ConcurrentHashSet<>(); /** * Broadcast this node element information task. */ private final MemberInfoReportTask infoReportTask = new MemberInfoReportTask(); private final UnhealthyMemberInfoReportTask unhealthyMemberInfoReportTask = new UnhealthyMemberInfoReportTask(); public ServerMemberManager() throws Exception { this.serverList = new ConcurrentSkipListMap<>(); init(); } protected void init() throws NacosException { Loggers.CORE.info("Nacos-related cluster resource initialization"); this.port = EnvUtil.getProperty(SERVER_PORT_PROPERTY, Integer.class, DEFAULT_SERVER_PORT); this.localAddress = InetUtils.getSelfIP() + ":" + port; this.self = MemberUtil.singleParse(this.localAddress); this.self.setExtendVal(MemberMetaDataConstants.VERSION, VersionUtils.version); //works for gray model upgrade,can delete after compatibility period. this.self.setExtendVal(MemberMetaDataConstants.SUPPORT_GRAY_MODEL, true); this.self.setGrpcReportEnabled(true); // init abilities. this.self.setAbilities(initMemberAbilities()); serverList.put(self.getAddress(), self); // register NodeChangeEvent publisher to NotifyManager registerClusterEvent(); // Initializes the lookup mode initAndStartLookup(); if (serverList.isEmpty()) { throw new NacosException(NacosException.SERVER_ERROR, "cannot get serverlist, so exit."); } Loggers.CORE.info("The cluster resource is initialized"); } /** * Init the ability of current node. * * @return ServerAbilities * @deprecated ability of current node and event cluster can be managed by {@link ServerAbilityControlManager} */ private ServerAbilities initMemberAbilities() { ServerAbilities serverAbilities = new ServerAbilities(); for (ServerAbilityInitializer each : ServerAbilityInitializerHolder.getInstance().getInitializers()) { each.initialize(serverAbilities); } return serverAbilities; } private void registerClusterEvent() { // Register node change events NotifyCenter.registerToPublisher(MembersChangeEvent.class, EnvUtil.getProperty(MEMBER_CHANGE_EVENT_QUEUE_SIZE_PROPERTY, Integer.class, DEFAULT_MEMBER_CHANGE_EVENT_QUEUE_SIZE)); // The address information of this node needs to be dynamically modified // when registering the IP change of this node NotifyCenter.registerSubscriber(new Subscriber<InetUtils.IPChangeEvent>() { @Override public void onEvent(InetUtils.IPChangeEvent event) { String newAddress = event.getNewIP() + ":" + port; ServerMemberManager.this.localAddress = newAddress; EnvUtil.setLocalAddress(localAddress); Member self = ServerMemberManager.this.self; self.setIp(event.getNewIP()); String oldAddress = event.getOldIP() + ":" + port; ServerMemberManager.this.serverList.remove(oldAddress); ServerMemberManager.this.serverList.put(newAddress, self); ServerMemberManager.this.memberAddressInfos.remove(oldAddress); ServerMemberManager.this.memberAddressInfos.add(newAddress); } @Override public Class<? extends Event> subscribeType() { return InetUtils.IPChangeEvent.class; } }); } private void initAndStartLookup() throws NacosException { this.lookup = LookupFactory.createLookUp(this); this.lookup.useAddressServer(); this.lookup.start(); } /** * switch look up. * * @param name look up name. * @throws NacosException exception. */ public void switchLookup(String name) throws NacosException { this.lookup = LookupFactory.switchLookup(name, this); this.lookup.useAddressServer(); this.lookup.start(); } /** * member information update. * * @param newMember {@link Member} * @return update is success */ public boolean update(Member newMember) { Loggers.CLUSTER.debug("member information update : {}", newMember); String address = newMember.getAddress(); if (!serverList.containsKey(address)) { Loggers.CLUSTER.warn("address {} want to update Member, but not in member list!", newMember.getAddress()); return false; } serverList.computeIfPresent(address, (s, member) -> { if (NodeState.DOWN.equals(newMember.getState())) { memberAddressInfos.remove(newMember.getAddress()); } boolean isPublishChangeEvent = MemberUtil.isBasicInfoChanged(newMember, member); newMember.setExtendVal(MemberMetaDataConstants.LAST_REFRESH_TIME, System.currentTimeMillis()); MemberUtil.copy(newMember, member); if (isPublishChangeEvent) { // member basic data changes and all listeners need to be notified notifyMemberChange(member); } return member; }); return true; } void notifyMemberChange(Member member) { NotifyCenter.publishEvent(MembersChangeEvent.builder().trigger(member).members(allMembers()).build()); } /** * Whether the node exists within the cluster. * * @param address ip:port * @return is exists */ public boolean hasMember(String address) { boolean result = serverList.containsKey(address); if (result) { return true; } // If only IP information is passed in, a fuzzy match is required for (Map.Entry<String, Member> entry : serverList.entrySet()) { if (StringUtils.contains(entry.getKey(), address)) { result = true; break; } } return result; } public List<String> getServerListUnhealth() { List<String> unhealthyMembers = new ArrayList<>(); for (Member member : this.allMembers()) { NodeState state = member.getState(); if (state.equals(NodeState.DOWN)) { unhealthyMembers.add(member.getAddress()); } } return unhealthyMembers; } public MemberLookup getLookup() { return lookup; } public Member getSelf() { return this.self; } public Member find(String address) { return serverList.get(address); } /** * return this cluster all members. * * @return {@link Collection} all member */ @Override public Collection<Member> allMembers() { // We need to do a copy to avoid affecting the real data HashSet<Member> set = new HashSet<>(serverList.values()); set.add(self); return set; } /** * return this cluster all members without self. * * @return {@link Collection} all member without self */ public List<Member> allMembersWithoutSelf() { List<Member> members = new ArrayList<>(serverList.values()); members.remove(self); return members; } @Override public synchronized boolean memberChange(Collection<Member> members) { if (members == null || members.isEmpty()) { return false; } boolean isContainSelfIp = members.stream() .anyMatch(ipPortTmp -> Objects.equals(localAddress, ipPortTmp.getAddress())); if (isContainSelfIp) { isInIpList = true; } else { isInIpList = false; members.add(this.self); Loggers.CLUSTER.warn("[serverlist] self ip {} not in serverlist {}", self, members); } // If the number of old and new clusters is different, the cluster information // must have changed; if the number of clusters is the same, then compare whether // there is a difference; if there is a difference, then the cluster node changes // are involved and all recipients need to be notified of the node change event boolean hasChange = members.size() != serverList.size(); ConcurrentSkipListMap<String, Member> tmpMap = new ConcurrentSkipListMap<>(); Set<String> tmpAddressInfo = new ConcurrentHashSet<>(); for (Member member : members) { final String address = member.getAddress(); Member existMember = serverList.get(address); if (existMember == null) { hasChange = true; tmpMap.put(address, member); } else { //to keep extendInfo and abilities that report dynamically. tmpMap.put(address, existMember); } if (NodeState.UP.equals(member.getState())) { tmpAddressInfo.add(address); } } serverList = tmpMap; memberAddressInfos = tmpAddressInfo; Collection<Member> finalMembers = allMembers(); // Persist the current cluster node information to cluster.conf // <important> need to put the event publication into a synchronized block to ensure // that the event publication is sequential if (hasChange) { Loggers.CLUSTER.info("[serverlist] changed to : {}", finalMembers); MemberUtil.syncToFile(finalMembers); Event event = MembersChangeEvent.builder().members(finalMembers).build(); NotifyCenter.publishEvent(event); } else { if (Loggers.CLUSTER.isDebugEnabled()) { Loggers.CLUSTER.debug("[serverlist] not updated, is still : {}", finalMembers); } } return hasChange; } /** * members join this cluster. * * @param members {@link Collection} new members * @return is success */ public synchronized boolean memberJoin(Collection<Member> members) { Set<Member> set = new HashSet<>(members); set.addAll(allMembers()); return memberChange(set); } /** * members leave this cluster. * * @param members {@link Collection} wait leave members * @return is success */ public synchronized boolean memberLeave(Collection<Member> members) { Set<Member> set = new HashSet<>(allMembers()); set.removeAll(members); return memberChange(set); } /** * check this member whether is in the specific status. * * @param address ip:port * @return is health */ public boolean stateCheck(String address, List<NodeState> nodeStates) { Member member = serverList.get(address); if (member == null) { return false; } for (NodeState nodeState : nodeStates) { if (nodeState.equals(member.getState())) { return true; } } return false; } /** * this member {@link Member#getState()} is health. * * @param address ip:port * @return is health */ public boolean isUnHealth(String address) { Member member = serverList.get(address); if (member == null) { return false; } return !NodeState.UP.equals(member.getState()); } public boolean isFirstIp() { return Objects.equals(serverList.firstKey(), this.localAddress); } public void setSelfReady(int port) { getSelf().setState(NodeState.UP); if (!EnvUtil.getStandaloneMode()) { GlobalExecutor.scheduleByCommon(this.infoReportTask, DEFAULT_TASK_DELAY_TIME); GlobalExecutor.scheduleByCommon(this.unhealthyMemberInfoReportTask, DEFAULT_TASK_DELAY_TIME); } EnvUtil.setPort(port); EnvUtil.setLocalAddress(this.localAddress); Loggers.CLUSTER.info("This node is ready to provide external services"); } /** * ServerMemberManager shutdown. * * @throws NacosException NacosException */ @PreDestroy public void shutdown() throws NacosException { serverList.clear(); memberAddressInfos.clear(); infoReportTask.shutdown(); LookupFactory.destroy(); } public Set<String> getMemberAddressInfos() { return memberAddressInfos; } @JustForTest public void updateMember(Member member) { serverList.put(member.getAddress(), member); } @JustForTest public MemberInfoReportTask getInfoReportTask() { return infoReportTask; } public Map<String, Member> getServerList() { return Collections.unmodifiableMap(serverList); } public static boolean isInIpList() { return isInIpList; } // Synchronize the metadata information of a node // A health check of the target node is also attached
ServerMemberManager
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/LoadEntityGraphWithCompositeKeyCollectionsTest.java
{ "start": 9694, "end": 10569 }
class ____ { @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({@JoinColumn(name = "exercise_id", referencedColumnName = "exercise_id"), @JoinColumn( name = "activity_id", referencedColumnName = "activity_id")}) private Activity activity; @Column(name = "question_id") private String questionId; public ActivityDocumentId() { } public ActivityDocumentId(Activity activity, String questionId) { this.activity = activity; this.questionId = questionId; } @Override public boolean equals(Object o) { if ( o == null || getClass() != o.getClass() ) { return false; } ActivityDocumentId that = (ActivityDocumentId) o; return Objects.equals( activity, that.activity ) && Objects.equals( questionId, that.questionId ); } @Override public int hashCode() { return Objects.hash( activity, questionId ); } } }
ActivityDocumentId
java
greenrobot__EventBus
EventBusTest/src/org/greenrobot/eventbus/AbstractAndroidEventBusTest.java
{ "start": 1050, "end": 1697 }
class ____ extends AbstractEventBusTest { private EventPostHandler mainPoster; public AbstractAndroidEventBusTest() { this(false); } public AbstractAndroidEventBusTest(boolean collectEventsReceived) { super(collectEventsReceived); } @Before public void setUpAndroid() throws Exception { mainPoster = new EventPostHandler(Looper.getMainLooper()); assertFalse(Looper.getMainLooper().getThread().equals(Thread.currentThread())); } protected void postInMainThread(Object event) { mainPoster.post(event); } @SuppressLint("HandlerLeak")
AbstractAndroidEventBusTest
java
google__guava
android/guava/src/com/google/common/collect/FilteredKeyMultimap.java
{ "start": 1385, "end": 3356 }
class ____<K extends @Nullable Object, V extends @Nullable Object> extends AbstractMultimap<K, V> implements FilteredMultimap<K, V> { final Multimap<K, V> unfiltered; final Predicate<? super K> keyPredicate; FilteredKeyMultimap(Multimap<K, V> unfiltered, Predicate<? super K> keyPredicate) { this.unfiltered = checkNotNull(unfiltered); this.keyPredicate = checkNotNull(keyPredicate); } @Override public Multimap<K, V> unfiltered() { return unfiltered; } @Override public Predicate<? super Entry<K, V>> entryPredicate() { return Maps.keyPredicateOnEntries(keyPredicate); } @Override public int size() { int size = 0; for (Collection<V> collection : asMap().values()) { size += collection.size(); } return size; } @Override public boolean containsKey(@Nullable Object key) { if (unfiltered.containsKey(key)) { @SuppressWarnings("unchecked") // k is equal to a K, if not one itself K k = (K) key; return keyPredicate.apply(k); } return false; } @Override public Collection<V> removeAll(@Nullable Object key) { return containsKey(key) ? unfiltered.removeAll(key) : unmodifiableEmptyCollection(); } @SuppressWarnings("EmptyList") // ImmutableList doesn't support nullable element types Collection<V> unmodifiableEmptyCollection() { if (unfiltered instanceof SetMultimap) { return emptySet(); } else { return emptyList(); } } @Override public void clear() { keySet().clear(); } @Override Set<K> createKeySet() { return Sets.filter(unfiltered.keySet(), keyPredicate); } @Override public Collection<V> get(@ParametricNullness K key) { if (keyPredicate.apply(key)) { return unfiltered.get(key); } else if (unfiltered instanceof SetMultimap) { return new AddRejectingSet<>(key); } else { return new AddRejectingList<>(key); } } private static final
FilteredKeyMultimap
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh14916/Book.java
{ "start": 607, "end": 1019 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long bookId; @Column public String name; @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "author_id", nullable = false) public Author author; @OneToMany(fetch = FetchType.LAZY, mappedBy = "book", orphanRemoval = true, cascade = CascadeType.ALL) public List<Chapter> chapters = new ArrayList<>(); }
Book
java
google__auto
factory/src/test/resources/good/ProviderArgumentToCreateMethod.java
{ "start": 767, "end": 973 }
class ____ { private final Provider<String> stringProvider; ProviderArgumentToCreateMethod(Provider<String> stringProvider) { this.stringProvider = stringProvider; }
ProviderArgumentToCreateMethod
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/LambdaExtractionTest.java
{ "start": 2178, "end": 4455 }
class ____ { private static final TypeInformation<Tuple2<Tuple1<Integer>, Boolean>> NESTED_TUPLE_BOOLEAN_TYPE = new TypeHint<Tuple2<Tuple1<Integer>, Boolean>>() {}.getTypeInfo(); private static final TypeInformation<Tuple2<Tuple1<Integer>, Double>> NESTED_TUPLE_DOUBLE_TYPE = new TypeHint<Tuple2<Tuple1<Integer>, Double>>() {}.getTypeInfo(); @Test @SuppressWarnings({"Convert2Lambda", "Anonymous2MethodRef"}) void testIdentifyLambdas() throws TypeExtractionException { MapFunction<?, ?> anonymousFromInterface = new MapFunction<String, Integer>() { @Override public Integer map(String value) { return Integer.parseInt(value); } }; MapFunction<?, ?> anonymousFromClass = new RichMapFunction<String, Integer>() { @Override public Integer map(String value) { return Integer.parseInt(value); } }; MapFunction<?, ?> fromProperClass = new StaticMapper(); MapFunction<?, ?> fromDerived = new ToTuple<Integer>() { @Override public Tuple2<Integer, Long> map(Integer value) { return new Tuple2<>(value, 1L); } }; MapFunction<String, Integer> staticLambda = Integer::parseInt; MapFunction<Integer, String> instanceLambda = Object::toString; MapFunction<String, Integer> constructorLambda = Integer::new; assertThat(checkAndExtractLambda(anonymousFromInterface)).isNull(); assertThat(checkAndExtractLambda(anonymousFromClass)).isNull(); assertThat(checkAndExtractLambda(fromProperClass)).isNull(); assertThat(checkAndExtractLambda(fromDerived)).isNull(); assertThat(checkAndExtractLambda(staticLambda)).isNotNull(); assertThat(checkAndExtractLambda(instanceLambda)).isNotNull(); assertThat(checkAndExtractLambda(constructorLambda)).isNotNull(); assertThat(checkAndExtractLambda(STATIC_LAMBDA)).isNotNull(); } private static
LambdaExtractionTest
java
apache__camel
components/camel-zookeeper/src/generated/java/org/apache/camel/component/zookeeper/cloud/ZooKeeperServiceDiscoveryFactoryConfigurer.java
{ "start": 752, "end": 8660 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.zookeeper.cloud.ZooKeeperServiceDiscoveryFactory target = (org.apache.camel.component.zookeeper.cloud.ZooKeeperServiceDiscoveryFactory) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "authinfolist": case "authInfoList": target.setAuthInfoList(property(camelContext, java.util.List.class, value)); return true; case "basepath": case "basePath": target.setBasePath(property(camelContext, java.lang.String.class, value)); return true; case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.zookeeper.ZooKeeperCuratorConfiguration.class, value)); return true; case "connectiontimeout": case "connectionTimeout": target.setConnectionTimeout(property(camelContext, long.class, value)); return true; case "connectiontimeoutunit": case "connectionTimeoutUnit": target.setConnectionTimeoutUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true; case "curatorframework": case "curatorFramework": target.setCuratorFramework(property(camelContext, org.apache.curator.framework.CuratorFramework.class, value)); return true; case "maxclosewait": case "maxCloseWait": target.setMaxCloseWait(property(camelContext, long.class, value)); return true; case "maxclosewaitunit": case "maxCloseWaitUnit": target.setMaxCloseWaitUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true; case "namespace": target.setNamespace(property(camelContext, java.lang.String.class, value)); return true; case "nodes": target.setNodes(property(camelContext, java.lang.String.class, value)); return true; case "reconnectbasesleeptime": case "reconnectBaseSleepTime": target.setReconnectBaseSleepTime(property(camelContext, long.class, value)); return true; case "reconnectbasesleeptimeunit": case "reconnectBaseSleepTimeUnit": target.setReconnectBaseSleepTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true; case "reconnectmaxretries": case "reconnectMaxRetries": target.setReconnectMaxRetries(property(camelContext, int.class, value)); return true; case "reconnectmaxsleeptime": case "reconnectMaxSleepTime": target.setReconnectMaxSleepTime(property(camelContext, long.class, value)); return true; case "reconnectmaxsleeptimeunit": case "reconnectMaxSleepTimeUnit": target.setReconnectMaxSleepTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true; case "retrypolicy": case "retryPolicy": target.setRetryPolicy(property(camelContext, org.apache.curator.RetryPolicy.class, value)); return true; case "sessiontimeout": case "sessionTimeout": target.setSessionTimeout(property(camelContext, long.class, value)); return true; case "sessiontimeoutunit": case "sessionTimeoutUnit": target.setSessionTimeoutUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "authinfolist": case "authInfoList": return java.util.List.class; case "basepath": case "basePath": return java.lang.String.class; case "configuration": return org.apache.camel.component.zookeeper.ZooKeeperCuratorConfiguration.class; case "connectiontimeout": case "connectionTimeout": return long.class; case "connectiontimeoutunit": case "connectionTimeoutUnit": return java.util.concurrent.TimeUnit.class; case "curatorframework": case "curatorFramework": return org.apache.curator.framework.CuratorFramework.class; case "maxclosewait": case "maxCloseWait": return long.class; case "maxclosewaitunit": case "maxCloseWaitUnit": return java.util.concurrent.TimeUnit.class; case "namespace": return java.lang.String.class; case "nodes": return java.lang.String.class; case "reconnectbasesleeptime": case "reconnectBaseSleepTime": return long.class; case "reconnectbasesleeptimeunit": case "reconnectBaseSleepTimeUnit": return java.util.concurrent.TimeUnit.class; case "reconnectmaxretries": case "reconnectMaxRetries": return int.class; case "reconnectmaxsleeptime": case "reconnectMaxSleepTime": return long.class; case "reconnectmaxsleeptimeunit": case "reconnectMaxSleepTimeUnit": return java.util.concurrent.TimeUnit.class; case "retrypolicy": case "retryPolicy": return org.apache.curator.RetryPolicy.class; case "sessiontimeout": case "sessionTimeout": return long.class; case "sessiontimeoutunit": case "sessionTimeoutUnit": return java.util.concurrent.TimeUnit.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.zookeeper.cloud.ZooKeeperServiceDiscoveryFactory target = (org.apache.camel.component.zookeeper.cloud.ZooKeeperServiceDiscoveryFactory) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "authinfolist": case "authInfoList": return target.getAuthInfoList(); case "basepath": case "basePath": return target.getBasePath(); case "configuration": return target.getConfiguration(); case "connectiontimeout": case "connectionTimeout": return target.getConnectionTimeout(); case "connectiontimeoutunit": case "connectionTimeoutUnit": return target.getConnectionTimeoutUnit(); case "curatorframework": case "curatorFramework": return target.getCuratorFramework(); case "maxclosewait": case "maxCloseWait": return target.getMaxCloseWait(); case "maxclosewaitunit": case "maxCloseWaitUnit": return target.getMaxCloseWaitUnit(); case "namespace": return target.getNamespace(); case "nodes": return target.getNodes(); case "reconnectbasesleeptime": case "reconnectBaseSleepTime": return target.getReconnectBaseSleepTime(); case "reconnectbasesleeptimeunit": case "reconnectBaseSleepTimeUnit": return target.getReconnectBaseSleepTimeUnit(); case "reconnectmaxretries": case "reconnectMaxRetries": return target.getReconnectMaxRetries(); case "reconnectmaxsleeptime": case "reconnectMaxSleepTime": return target.getReconnectMaxSleepTime(); case "reconnectmaxsleeptimeunit": case "reconnectMaxSleepTimeUnit": return target.getReconnectMaxSleepTimeUnit(); case "retrypolicy": case "retryPolicy": return target.getRetryPolicy(); case "sessiontimeout": case "sessionTimeout": return target.getSessionTimeout(); case "sessiontimeoutunit": case "sessionTimeoutUnit": return target.getSessionTimeoutUnit(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "authinfolist": case "authInfoList": return org.apache.curator.framework.AuthInfo.class; default: return null; } } }
ZooKeeperServiceDiscoveryFactoryConfigurer
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/file/TestAllCodecs.java
{ "start": 1135, "end": 4307 }
class ____ { @ParameterizedTest @MethodSource("codecTypes") void codec(String codec, Class<? extends Codec> codecClass) throws IOException { int inputSize = 500_000; byte[] input = generateTestData(inputSize); Codec codecInstance = CodecFactory.fromString(codec).createInstance(); Assertions.assertTrue(codecClass.isInstance(codecInstance)); Assertions.assertTrue(codecInstance.getName().equals(codec)); ByteBuffer inputByteBuffer = ByteBuffer.wrap(input); ByteBuffer compressedBuffer = codecInstance.compress(inputByteBuffer); int compressedSize = compressedBuffer.remaining(); // Make sure something returned Assertions.assertTrue(compressedSize > 0); // While the compressed size could in many real cases // *increase* compared to the input size, our input data // is extremely easy to compress and all Avro's compression algorithms // should have a compression ratio greater than 1 (except 'null'). Assertions.assertTrue(compressedSize < inputSize || codec.equals("null")); // Decompress the data ByteBuffer decompressedBuffer = codecInstance.decompress(compressedBuffer); // Validate the the input and output are equal. inputByteBuffer.rewind(); Assertions.assertEquals(inputByteBuffer, decompressedBuffer); } @ParameterizedTest @MethodSource("codecTypes") void codecSlice(String codec, Class<? extends Codec> codecClass) throws IOException { int inputSize = 500_000; byte[] input = generateTestData(inputSize); Codec codecInstance = CodecFactory.fromString(codec).createInstance(); Assertions.assertTrue(codecClass.isInstance(codecInstance)); ByteBuffer partialBuffer = ByteBuffer.wrap(input); partialBuffer.position(17); ByteBuffer inputByteBuffer = partialBuffer.slice(); ByteBuffer compressedBuffer = codecInstance.compress(inputByteBuffer); int compressedSize = compressedBuffer.remaining(); // Make sure something returned Assertions.assertTrue(compressedSize > 0); // Create a slice from the compressed buffer ByteBuffer sliceBuffer = ByteBuffer.allocate(compressedSize + 100); sliceBuffer.position(50); sliceBuffer.put(compressedBuffer); sliceBuffer.limit(compressedSize + 50); sliceBuffer.position(50); // Decompress the data ByteBuffer decompressedBuffer = codecInstance.decompress(sliceBuffer.slice()); // Validate the the input and output are equal. inputByteBuffer.rewind(); Assertions.assertEquals(inputByteBuffer, decompressedBuffer); } public static Stream<Arguments> codecTypes() { return Stream.of(Arguments.of("bzip2", BZip2Codec.class), Arguments.of("zstandard", ZstandardCodec.class), Arguments.of("null", NullCodec.class), Arguments.of("xz", XZCodec.class), Arguments.of("snappy", SnappyCodec.class), Arguments.of("deflate", DeflateCodec.class)); } // Generate some test data that will compress easily public static byte[] generateTestData(int inputSize) { byte[] arr = new byte[inputSize]; for (int i = 0; i < arr.length; i++) { arr[i] = (byte) (65 + i % 10); } return arr; } }
TestAllCodecs
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/LoopOverCharArray.java
{ "start": 1750, "end": 3675 }
class ____ extends BugChecker implements BugChecker.EnhancedForLoopTreeMatcher { private static final Matcher<ExpressionTree> TO_CHAR_ARRAY = instanceMethod().onExactClass("java.lang.String").named("toCharArray"); @Override public Description matchEnhancedForLoop(EnhancedForLoopTree tree, VisitorState state) { if (!TO_CHAR_ARRAY.matches(tree.getExpression(), state)) { return NO_MATCH; } ExpressionTree receiver = ASTHelpers.getReceiver(tree.getExpression()); if (!(receiver instanceof IdentifierTree)) { return NO_MATCH; } StatementTree body = tree.getStatement(); if (!(body instanceof BlockTree blockTree)) { return NO_MATCH; } List<? extends StatementTree> statements = blockTree.getStatements(); if (statements.isEmpty()) { return NO_MATCH; } Description.Builder description = buildDescription(tree); // The fix uses `i` as the loop index variable, so give up if there's already an `i` in scope if (!alreadyDefinesIdentifier(tree)) { description.addFix( SuggestedFix.replace( getStartPosition(tree), getStartPosition(statements.getFirst()), String.format( "for (int i = 0; i < %s.length(); i++) { char %s = %s.charAt(i);", state.getSourceForNode(receiver), tree.getVariable().getName(), state.getSourceForNode(receiver)))); } return description.build(); } private static boolean alreadyDefinesIdentifier(Tree tree) { boolean[] result = {false}; new TreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree node, Void unused) { if (node.getName().contentEquals("i")) { result[0] = true; } return super.visitIdentifier(node, null); } }.scan(tree, null); return result[0]; } }
LoopOverCharArray
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/authentication/RememberMeAuthenticationProvider.java
{ "start": 1453, "end": 2769 }
class ____ implements AuthenticationProvider, InitializingBean, MessageSourceAware { protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); private String key; public RememberMeAuthenticationProvider(String key) { Assert.hasLength(key, "key must have a length"); this.key = key; } @Override public void afterPropertiesSet() { Assert.notNull(this.messages, "A message source must be set"); } @Override public @Nullable Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; } if (this.key.hashCode() != ((RememberMeAuthenticationToken) authentication).getKeyHash()) { throw new BadCredentialsException(this.messages.getMessage("RememberMeAuthenticationProvider.incorrectKey", "The presented RememberMeAuthenticationToken does not contain the expected key")); } return authentication; } public String getKey() { return this.key; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } @Override public boolean supports(Class<?> authentication) { return (RememberMeAuthenticationToken.class.isAssignableFrom(authentication)); } }
RememberMeAuthenticationProvider
java
apache__camel
components/camel-aws/camel-aws2-ddb/src/main/java/org/apache/camel/component/aws2/ddbstream/Ddb2StreamConsumer.java
{ "start": 1618, "end": 6114 }
class ____ extends ScheduledBatchPollingConsumer { private static final Logger LOG = LoggerFactory.getLogger(Ddb2StreamConsumer.class); private final ShardIteratorHandler shardIteratorHandler; private final Map<String, String> lastSeenSequenceNumbers = new HashMap<>(); public Ddb2StreamConsumer(Ddb2StreamEndpoint endpoint, Processor processor) { this(endpoint, processor, new ShardIteratorHandler(endpoint)); } Ddb2StreamConsumer(Ddb2StreamEndpoint endpoint, Processor processor, ShardIteratorHandler shardIteratorHandler) { super(endpoint, processor); this.shardIteratorHandler = shardIteratorHandler; } @Override protected int poll() throws Exception { int processedExchangeCount = 0; Map<String, String> shardIterators = shardIteratorHandler.getShardIterators(); // okay we have some response from azure so lets mark the consumer as ready forceConsumerAsReady(); for (Entry<String, String> shardIteratorEntry : shardIterators.entrySet()) { int limitPerRecordsRequest = Math.max(1, getEndpoint().getConfiguration().getMaxResultsPerRequest() / shardIterators.size()); String shardId = shardIteratorEntry.getKey(); String shardIterator = shardIteratorEntry.getValue(); GetRecordsResponse result; try { GetRecordsRequest req = GetRecordsRequest.builder() .shardIterator(shardIterator) .limit(limitPerRecordsRequest) .build(); result = getEndpoint().getClient().getRecords(req); } catch (ExpiredIteratorException e) { String lastSeenSequenceNumber = lastSeenSequenceNumbers.get(shardId); LOG.warn("Expired Shard Iterator, attempting to resume from {}", lastSeenSequenceNumber, e); GetRecordsRequest req = GetRecordsRequest.builder() .shardIterator(shardIteratorHandler.requestFreshShardIterator(shardId, lastSeenSequenceNumber)) .limit(limitPerRecordsRequest) .build(); result = getEndpoint().getClient().getRecords(req); } List<Record> records = result.records(); Queue<Exchange> exchanges = new ArrayDeque<>(); for (Record polledRecord : records) { exchanges.add(createExchange(polledRecord)); } processedExchangeCount += processBatch(CastUtils.cast(exchanges)); shardIteratorHandler.updateShardIterator(shardId, result.nextShardIterator()); if (!records.isEmpty()) { lastSeenSequenceNumbers.put(shardId, records.get(records.size() - 1).dynamodb().sequenceNumber()); } } return processedExchangeCount; } @Override public int processBatch(Queue<Object> exchanges) throws Exception { int total = exchanges.size(); int answer = 0; for (int index = 0; index < total && isBatchAllowed(); index++) { // only loop if we are started (allowed to run) // use poll to remove the head so it does not consume memory even // after we have processed it Exchange exchange = (Exchange) exchanges.poll(); // add current index and total as properties exchange.setProperty(ExchangePropertyKey.BATCH_INDEX, index); exchange.setProperty(ExchangePropertyKey.BATCH_SIZE, total); exchange.setProperty(ExchangePropertyKey.BATCH_COMPLETE, index == total - 1); // update pending number of exchanges pendingExchanges = total - index - 1; // use default consumer callback AsyncCallback cb = defaultConsumerCallback(exchange, true); getAsyncProcessor().process(exchange, cb); answer++; } return answer; } protected Exchange createExchange(Record record) { Exchange ex = createExchange(true); ex.getMessage().setBody(record, Record.class); ex.getMessage().setHeader(Ddb2StreamConstants.EVENT_SOURCE, record.eventSource()); ex.getMessage().setHeader(Ddb2StreamConstants.EVENT_ID, record.eventID()); return ex; } @Override public Ddb2StreamEndpoint getEndpoint() { return (Ddb2StreamEndpoint) super.getEndpoint(); } }
Ddb2StreamConsumer
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferUtils.java
{ "start": 42695, "end": 43277 }
class ____ implements OutputStreamPublisher.ByteMapper<DataBuffer> { private final DataBufferFactory bufferFactory; private DataBufferMapper(DataBufferFactory bufferFactory) { this.bufferFactory = bufferFactory; } @Override public DataBuffer map(int b) { DataBuffer buffer = this.bufferFactory.allocateBuffer(1); buffer.write((byte) b); return buffer; } @Override public DataBuffer map(byte[] b, int off, int len) { DataBuffer buffer = this.bufferFactory.allocateBuffer(len); buffer.write(b, off, len); return buffer; } } }
DataBufferMapper
java
apache__camel
components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorConsumer.java
{ "start": 1637, "end": 7626 }
class ____ extends ServiceSupport implements Consumer, Suspendable, ShutdownAware { private static final Logger LOGGER = LoggerFactory.getLogger(DisruptorConsumer.class); private static final AsyncCallback NOOP_ASYNC_CALLBACK = new AsyncCallback() { @Override public void done(boolean doneSync) { //Noop } }; private final DisruptorEndpoint endpoint; private final AsyncProcessor processor; private ExceptionHandler exceptionHandler; public DisruptorConsumer(final DisruptorEndpoint endpoint, final Processor processor) { this.endpoint = endpoint; this.processor = AsyncProcessorConverterHelper.convert(processor); } @Override public AsyncProcessor getProcessor() { return processor; } public ExceptionHandler getExceptionHandler() { if (exceptionHandler == null) { exceptionHandler = new LoggingExceptionHandler(endpoint.getCamelContext(), getClass()); } return exceptionHandler; } public void setExceptionHandler(final ExceptionHandler exceptionHandler) { this.exceptionHandler = exceptionHandler; } @Override public DisruptorEndpoint getEndpoint() { return endpoint; } @Override protected void doStart() throws Exception { getEndpoint().onStarted(this); } @Override protected void doStop() throws Exception { getEndpoint().onStopped(this); } @Override protected void doSuspend() throws Exception { getEndpoint().onStopped(this); } @Override protected void doResume() throws Exception { getEndpoint().onStarted(this); } Set<LifecycleAwareExchangeEventHandler> createEventHandlers(final int concurrentConsumers) { final Set<LifecycleAwareExchangeEventHandler> eventHandlers = new HashSet<>(); for (int i = 0; i < concurrentConsumers; ++i) { eventHandlers.add(new ConsumerEventHandler(i, concurrentConsumers)); } return eventHandlers; } @Override public boolean deferShutdown(final ShutdownRunningTask shutdownRunningTask) { // deny stopping on shutdown as we want disruptor consumers to run in case some other queues // depend on this consumer to run, so it can complete its exchanges return true; } @Override public void prepareShutdown(boolean suspendOnly, boolean forced) { // nothing } @Override public int getPendingExchangesSize() { return getEndpoint().getDisruptor().getPendingExchangeCount(); } @Override public String toString() { return "DisruptorConsumer[" + endpoint + "]"; } private Exchange prepareExchange(final Exchange exchange) { // send a new copied exchange with new camel context // don't copy handovers as they are handled by the Disruptor Event Handlers final Exchange newExchange = ExchangeHelper.copyExchangeWithProperties(exchange, endpoint.getCamelContext()); // set the from endpoint newExchange.getExchangeExtension().setFromEndpoint(endpoint); return newExchange; } private void process(final SynchronizedExchange synchronizedExchange) { try { Exchange exchange = synchronizedExchange.getExchange(); final boolean ignore = exchange.hasProperties() && exchange .getProperties().containsKey(DisruptorEndpoint.DISRUPTOR_IGNORE_EXCHANGE); if (ignore) { // Property was set and it was set to true, so don't process Exchange. LOGGER.trace("Ignoring exchange {}", exchange); return; } // send a new copied exchange with new camel context final Exchange result = prepareExchange(exchange); // We need to be notified when the exchange processing is complete to synchronize the original exchange // This is however, the last part of the processing of this exchange and as such can't be done // in the AsyncCallback as that is called *AFTER* processing is considered to be done // (see org.apache.camel.processor.CamelInternalProcessor.InternalCallback#done). // To solve this problem, a new synchronization is set on the exchange that is to be // processed result.getExchangeExtension().addOnCompletion(newSynchronization(synchronizedExchange, result)); // As the necessary post-processing of the exchange is done by the registered Synchronization, // we can suffice with a no-op AsyncCallback processor.process(result, NOOP_ASYNC_CALLBACK); } catch (Exception e) { handleException(synchronizedExchange, e); } } private static Synchronization newSynchronization(SynchronizedExchange synchronizedExchange, Exchange result) { return new Synchronization() { @Override public void onComplete(Exchange exchange) { synchronizedExchange.consumed(result); } @Override public void onFailure(Exchange exchange) { synchronizedExchange.consumed(result); } }; } private void handleException(SynchronizedExchange synchronizedExchange, Exception e) { Exchange exchange = synchronizedExchange.getExchange(); if (exchange != null) { getExceptionHandler().handleException("Error processing exchange", exchange, e); } else { getExceptionHandler().handleException(e); } } @Override public Exchange createExchange(boolean autoRelease) { // noop return null; } @Override public void releaseExchange(Exchange exchange, boolean autoRelease) { // noop } /** * Implementation of the {@link LifecycleAwareExchangeEventHandler}
DisruptorConsumer
java
spring-projects__spring-security
rsocket/src/main/java/org/springframework/security/rsocket/api/PayloadInterceptorChain.java
{ "start": 857, "end": 1112 }
interface ____ { /** * Process the payload exchange. * @param exchange the current server exchange * @return {@code Mono<Void>} to indicate when request processing is complete */ Mono<Void> next(PayloadExchange exchange); }
PayloadInterceptorChain
java
spring-projects__spring-framework
spring-websocket/src/test/java/org/springframework/web/socket/config/HandlersBeanDefinitionParserTests.java
{ "start": 13901, "end": 14644 }
class ____ implements TaskScheduler { @Override public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) { return null; } @Override public ScheduledFuture<?> schedule(Runnable task, Instant startTime) { return null; } @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period) { return null; } @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period) { return null; } @Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime, Duration delay) { return null; } @Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay) { return null; } }
TestTaskScheduler
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/inference/XContentRowEncoder.java
{ "start": 5926, "end": 6961 }
class ____ implements ExpressionEvaluator.Factory { private final XContentType xContentType; private final Map<ColumnInfoImpl, ExpressionEvaluator.Factory> fieldsEvaluatorFactories; Factory(XContentType xContentType, Map<ColumnInfoImpl, ExpressionEvaluator.Factory> fieldsEvaluatorFactories) { this.xContentType = xContentType; this.fieldsEvaluatorFactories = fieldsEvaluatorFactories; } public XContentRowEncoder get(DriverContext context) { return new XContentRowEncoder(xContentType, context.blockFactory(), columnsInfo(), fieldsValueEvaluators(context)); } private ColumnInfoImpl[] columnsInfo() { return fieldsEvaluatorFactories.keySet().toArray(ColumnInfoImpl[]::new); } private ExpressionEvaluator[] fieldsValueEvaluators(DriverContext context) { return fieldsEvaluatorFactories.values().stream().map(factory -> factory.get(context)).toArray(ExpressionEvaluator[]::new); } } }
Factory
java
apache__rocketmq
broker/src/main/java/org/apache/rocketmq/broker/metrics/InvocationStatus.java
{ "start": 855, "end": 1087 }
enum ____ { SUCCESS("success"), FAILURE("failure"); private final String name; InvocationStatus(String name) { this.name = name; } public String getName() { return name; } }
InvocationStatus
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/TahuHostEndpointBuilderFactory.java
{ "start": 1597, "end": 8343 }
interface ____ extends EndpointConsumerBuilder { default AdvancedTahuHostEndpointBuilder advanced() { return (AdvancedTahuHostEndpointBuilder) this; } /** * MQTT client ID length check enabled. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param checkClientIdLength the value to set * @return the dsl builder */ default TahuHostEndpointBuilder checkClientIdLength(boolean checkClientIdLength) { doSetProperty("checkClientIdLength", checkClientIdLength); return this; } /** * MQTT client ID length check enabled. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param checkClientIdLength the value to set * @return the dsl builder */ default TahuHostEndpointBuilder checkClientIdLength(String checkClientIdLength) { doSetProperty("checkClientIdLength", checkClientIdLength); return this; } /** * MQTT client ID to use for all server definitions, rather than * specifying the same one for each. Note that if neither the 'clientId' * parameter nor an 'MqttClientId' are defined for an MQTT Server, a * random MQTT Client ID will be generated automatically, prefaced with * 'Camel'. * * The option is a: <code>java.lang.String</code> type. * * Required: true * Group: common * * @param clientId the value to set * @return the dsl builder */ default TahuHostEndpointBuilder clientId(String clientId) { doSetProperty("clientId", clientId); return this; } /** * MQTT connection keep alive timeout, in seconds. * * The option is a: <code>int</code> type. * * Default: 30 * Group: common * * @param keepAliveTimeout the value to set * @return the dsl builder */ default TahuHostEndpointBuilder keepAliveTimeout(int keepAliveTimeout) { doSetProperty("keepAliveTimeout", keepAliveTimeout); return this; } /** * MQTT connection keep alive timeout, in seconds. * * The option will be converted to a <code>int</code> type. * * Default: 30 * Group: common * * @param keepAliveTimeout the value to set * @return the dsl builder */ default TahuHostEndpointBuilder keepAliveTimeout(String keepAliveTimeout) { doSetProperty("keepAliveTimeout", keepAliveTimeout); return this; } /** * Delay before recurring node rebirth messages will be sent. * * The option is a: <code>long</code> type. * * Default: 5000 * Group: common * * @param rebirthDebounceDelay the value to set * @return the dsl builder */ default TahuHostEndpointBuilder rebirthDebounceDelay(long rebirthDebounceDelay) { doSetProperty("rebirthDebounceDelay", rebirthDebounceDelay); return this; } /** * Delay before recurring node rebirth messages will be sent. * * The option will be converted to a <code>long</code> type. * * Default: 5000 * Group: common * * @param rebirthDebounceDelay the value to set * @return the dsl builder */ default TahuHostEndpointBuilder rebirthDebounceDelay(String rebirthDebounceDelay) { doSetProperty("rebirthDebounceDelay", rebirthDebounceDelay); return this; } /** * MQTT server definitions, given with the following syntax in a * comma-separated list: * MqttServerName:(MqttClientId:)(tcp/ssl)://hostname(:port),... * * The option is a: <code>java.lang.String</code> type. * * Required: true * Group: common * * @param servers the value to set * @return the dsl builder */ default TahuHostEndpointBuilder servers(String servers) { doSetProperty("servers", servers); return this; } /** * Password for MQTT server authentication. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param password the value to set * @return the dsl builder */ default TahuHostEndpointBuilder password(String password) { doSetProperty("password", password); return this; } /** * SSL configuration for MQTT server connections. * * The option is a: * <code>org.apache.camel.support.jsse.SSLContextParameters</code> type. * * Group: security * * @param sslContextParameters the value to set * @return the dsl builder */ default TahuHostEndpointBuilder sslContextParameters(org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) { doSetProperty("sslContextParameters", sslContextParameters); return this; } /** * SSL configuration for MQTT server connections. * * The option will be converted to a * <code>org.apache.camel.support.jsse.SSLContextParameters</code> type. * * Group: security * * @param sslContextParameters the value to set * @return the dsl builder */ default TahuHostEndpointBuilder sslContextParameters(String sslContextParameters) { doSetProperty("sslContextParameters", sslContextParameters); return this; } /** * Username for MQTT server authentication. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param username the value to set * @return the dsl builder */ default TahuHostEndpointBuilder username(String username) { doSetProperty("username", username); return this; } } /** * Advanced builder for endpoint for the Tahu Host Application component. */ public
TahuHostEndpointBuilder
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/core/annotation/ExpressionTemplateSecurityAnnotationScannerTests.java
{ "start": 2876, "end": 3130 }
interface ____ { Permission[] permissions(); } @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) @HasAnyCustomPermissions(permissions = { Permission.READ, Permission.WRITE }) @
HasAnyCustomPermissions
java
google__dagger
javatests/dagger/android/processor/AndroidMapKeyValidatorTest.java
{ "start": 957, "end": 1266 }
class ____ { private static final Source FOO_ACTIVITY = CompilerTests.javaSource( "test.FooActivity", "package test;", "", "import android.app.Activity;", "import dagger.android.AndroidInjector;", "", "public
AndroidMapKeyValidatorTest
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/devservices/crossclassloader/runtime/RunningDevServicesRegistry.java
{ "start": 797, "end": 1127 }
class ____ { private static final Logger log = Logger.getLogger(RunningDevServicesRegistry.class); public static final RunningDevServicesRegistry INSTANCE = new RunningDevServicesRegistry(); // A useful uniqueness marker which will persist across profiles and application restarts, since this
RunningDevServicesRegistry
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_849/Target.java
{ "start": 314, "end": 548 }
class ____ { private List<Serializable> targetList; public List<Serializable> getTargetList() { if ( targetList == null ) { targetList = new ArrayList<>(); } return targetList; } }
Target
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/AbstractEntity.java
{ "start": 334, "end": 534 }
class ____ { @Id private long id; @Embedded private EmbeddableEntity embedded; public long getId() { return id; } public EmbeddableEntity getEmbedded() { return embedded; } }
AbstractEntity
java
google__dagger
javatests/dagger/functional/builder/BuilderBindsInstanceParameterTest.java
{ "start": 1134, "end": 1667 }
interface ____ { // https://github.com/google/dagger/issues/1464 Builder s(@BindsInstance String notTheSameNameAsMethod); Builder i(@BindsInstance int i); TestComponent build(); } } @Test public void builder_bindsInstanceOnParameter_allowed() { TestComponent component = DaggerBuilderBindsInstanceParameterTest_TestComponent.builder() .s("hello") .i(42) .build(); assertThat(component.s()).isEqualTo("hello"); assertThat(component.i()).isEqualTo(42); } }
Builder
java
jhy__jsoup
src/main/java/org/jsoup/parser/HtmlTreeBuilder.java
{ "start": 857, "end": 42331 }
class ____ extends TreeBuilder { // tag searches. must be sorted, used in inSorted. HtmlTreeBuilderTest validates they're sorted. static final String[] TagsSearchInScope = new String[]{ // a particular element in scope "applet", "caption", "html", "marquee", "object", "table", "td", "template", "th" }; // math and svg namespaces for particular element in scope static final String[]TagSearchInScopeMath = new String[] { "annotation-xml", "mi", "mn", "mo", "ms", "mtext" }; static final String[]TagSearchInScopeSvg = new String[] { "desc", "foreignObject", "title" }; static final String[] TagSearchList = new String[]{"ol", "ul"}; static final String[] TagSearchButton = new String[]{"button"}; static final String[] TagSearchTableScope = new String[]{"html", "table"}; static final String[] TagSearchSelectScope = new String[]{"optgroup", "option"}; static final String[] TagSearchEndTags = new String[]{"dd", "dt", "li", "optgroup", "option", "p", "rb", "rp", "rt", "rtc"}; static final String[] TagThoroughSearchEndTags = new String[]{"caption", "colgroup", "dd", "dt", "li", "optgroup", "option", "p", "rb", "rp", "rt", "rtc", "tbody", "td", "tfoot", "th", "thead", "tr"}; static final String[] TagSearchSpecial = new String[]{ "address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "iframe", "img", "input", "keygen", "li", "link", "listing", "main", "marquee", "menu", "meta", "nav", "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", "search", "section", "select", "source", "style", "summary", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "title", "tr", "track", "ul", "wbr", "xmp"}; static String[] TagSearchSpecialMath = {"annotation-xml", "mi", "mn", "mo", "ms", "mtext"}; // differs to MathML text integration point; adds annotation-xml static final String[] TagMathMlTextIntegration = new String[]{"mi", "mn", "mo", "ms", "mtext"}; static final String[] TagSvgHtmlIntegration = new String[]{"desc", "foreignObject", "title"}; static final String[] TagFormListed = { "button", "fieldset", "input", "keygen", "object", "output", "select", "textarea" }; /** @deprecated This is not used anymore. Will be removed in a future release. */ @Deprecated public static final int MaxScopeSearchDepth = 100; private HtmlTreeBuilderState state; // the current state private HtmlTreeBuilderState originalState; // original / marked state private boolean baseUriSetFromDoc; private @Nullable Element headElement; // the current head element private @Nullable FormElement formElement; // the current form element private @Nullable Element contextElement; // fragment parse root; name only copy of context. could be null even if fragment parsing ArrayList<Element> formattingElements; // active (open) formatting elements private ArrayList<HtmlTreeBuilderState> tmplInsertMode; // stack of Template Insertion modes private List<Token.Character> pendingTableCharacters; // chars in table to be shifted out private Token.EndTag emptyEnd; // reused empty end tag private boolean framesetOk; // if ok to go into frameset private boolean fosterInserts; // if next inserts should be fostered private boolean fragmentParsing; // if parsing a fragment of html @Override ParseSettings defaultSettings() { return ParseSettings.htmlDefault; } @Override HtmlTreeBuilder newInstance() { return new HtmlTreeBuilder(); } @Override protected void initialiseParse(Reader input, String baseUri, Parser parser) { super.initialiseParse(input, baseUri, parser); // this is a bit mucky. todo - probably just create new parser objects to ensure all reset. state = HtmlTreeBuilderState.Initial; originalState = null; baseUriSetFromDoc = false; headElement = null; formElement = null; contextElement = null; formattingElements = new ArrayList<>(); tmplInsertMode = new ArrayList<>(); pendingTableCharacters = new ArrayList<>(); emptyEnd = new Token.EndTag(this); framesetOk = true; fosterInserts = false; fragmentParsing = false; } @Override void initialiseParseFragment(@Nullable Element context) { // context may be null state = HtmlTreeBuilderState.Initial; fragmentParsing = true; if (context != null) { final String contextName = context.normalName(); contextElement = new Element(tagFor(contextName, contextName, defaultNamespace(), settings), baseUri); if (context.ownerDocument() != null) // quirks setup: doc.quirksMode(context.ownerDocument().quirksMode()); // initialise the tokeniser state: switch (contextName) { case "script": tokeniser.transition(TokeniserState.ScriptData); break; case "plaintext": tokeniser.transition(TokeniserState.PLAINTEXT); break; case "template": tokeniser.transition(TokeniserState.Data); pushTemplateMode(HtmlTreeBuilderState.InTemplate); break; default: Tag tag = contextElement.tag(); TokeniserState textState = tag.textState(); if (textState != null) tokeniser.transition(textState); // style, xmp, title, textarea, etc; or custom else tokeniser.transition(TokeniserState.Data); } doc.appendChild(contextElement); push(contextElement); resetInsertionMode(); // setup form element to nearest form on context (up ancestor chain). ensures form controls are associated // with form correctly Element formSearch = context; while (formSearch != null) { if (formSearch instanceof FormElement) { formElement = (FormElement) formSearch; break; } formSearch = formSearch.parent(); } } } @Override List<Node> completeParseFragment() { if (contextElement != null) { // depending on context and the input html, content may have been added outside of the root el // e.g. context=p, input=div, the div will have been pushed out. List<Node> nodes = contextElement.siblingNodes(); if (!nodes.isEmpty()) contextElement.insertChildren(-1, nodes); return contextElement.childNodes(); } else return doc.childNodes(); } @Override protected boolean process(Token token) { HtmlTreeBuilderState dispatch = useCurrentOrForeignInsert(token) ? this.state : ForeignContent; return dispatch.process(token, this); } boolean useCurrentOrForeignInsert(Token token) { // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction // If the stack of open elements is empty if (stack.isEmpty()) return true; final Element el = currentElement(); final String ns = el.tag().namespace(); // If the adjusted current node is an element in the HTML namespace if (NamespaceHtml.equals(ns)) return true; // If the adjusted current node is a MathML text integration point and the token is a start tag whose tag name is neither "mglyph" nor "malignmark" // If the adjusted current node is a MathML text integration point and the token is a character token if (isMathmlTextIntegration(el)) { if (token.isStartTag() && !"mglyph".equals(token.asStartTag().normalName) && !"malignmark".equals(token.asStartTag().normalName)) return true; if (token.isCharacter()) return true; } // If the adjusted current node is a MathML annotation-xml element and the token is a start tag whose tag name is "svg" if (Parser.NamespaceMathml.equals(ns) && el.nameIs("annotation-xml") && token.isStartTag() && "svg".equals(token.asStartTag().normalName)) return true; // If the adjusted current node is an HTML integration point and the token is a start tag // If the adjusted current node is an HTML integration point and the token is a character token if (isHtmlIntegration(el) && (token.isStartTag() || token.isCharacter())) return true; // If the token is an end-of-file token return token.isEOF(); } static boolean isMathmlTextIntegration(Element el) { /* A node is a MathML text integration point if it is one of the following elements: A MathML mi element A MathML mo element A MathML mn element A MathML ms element A MathML mtext element */ return (Parser.NamespaceMathml.equals(el.tag().namespace()) && StringUtil.inSorted(el.normalName(), TagMathMlTextIntegration)); } static boolean isHtmlIntegration(Element el) { /* A node is an HTML integration point if it is one of the following elements: A MathML annotation-xml element whose start tag token had an attribute with the name "encoding" whose value was an ASCII case-insensitive match for the string "text/html" A MathML annotation-xml element whose start tag token had an attribute with the name "encoding" whose value was an ASCII case-insensitive match for the string "application/xhtml+xml" An SVG foreignObject element An SVG desc element An SVG title element */ if (Parser.NamespaceMathml.equals(el.tag().namespace()) && el.nameIs("annotation-xml")) { String encoding = Normalizer.normalize(el.attr("encoding")); if (encoding.equals("text/html") || encoding.equals("application/xhtml+xml")) return true; } // note using .tagName for case-sensitive hit here of foreignObject return Parser.NamespaceSvg.equals(el.tag().namespace()) && StringUtil.in(el.tagName(), TagSvgHtmlIntegration); } boolean process(Token token, HtmlTreeBuilderState state) { return state.process(token, this); } void transition(HtmlTreeBuilderState state) { this.state = state; } HtmlTreeBuilderState state() { return state; } void markInsertionMode() { originalState = state; } HtmlTreeBuilderState originalState() { return originalState; } void framesetOk(boolean framesetOk) { this.framesetOk = framesetOk; } boolean framesetOk() { return framesetOk; } Document getDocument() { return doc; } String getBaseUri() { return baseUri; } void maybeSetBaseUri(Element base) { if (baseUriSetFromDoc) // only listen to the first <base href> in parse return; String href = base.absUrl("href"); if (href.length() != 0) { // ignore <base target> etc baseUri = href; baseUriSetFromDoc = true; doc.setBaseUri(href); // set on the doc so doc.createElement(Tag) will get updated base, and to update all descendants } } boolean isFragmentParsing() { return fragmentParsing; } void error(HtmlTreeBuilderState state) { if (parser.getErrors().canAddError()) parser.getErrors().add(new ParseError(reader, "Unexpected %s token [%s] when in state [%s]", currentToken.tokenType(), currentToken, state)); } Element createElementFor(Token.StartTag startTag, String namespace, boolean forcePreserveCase) { // dedupe and normalize the attributes: Attributes attributes = startTag.attributes; if (attributes != null && !attributes.isEmpty()) { if (!forcePreserveCase) settings.normalizeAttributes(attributes); int dupes = attributes.deduplicate(settings); if (dupes > 0) { error("Dropped duplicate attribute(s) in tag [%s]", startTag.normalName); } } Tag tag = tagFor(startTag.name(), startTag.normalName, namespace, forcePreserveCase ? ParseSettings.preserveCase : settings); return (tag.normalName().equals("form")) ? new FormElement(tag, null, attributes) : new Element(tag, null, attributes); } /** Inserts an HTML element for the given tag */ Element insertElementFor(final Token.StartTag startTag) { Element el = createElementFor(startTag, NamespaceHtml, false); doInsertElement(el); // handle self-closing tags. when the spec expects an empty (void) tag, will directly hit insertEmpty, so won't generate this fake end tag. if (startTag.isSelfClosing()) { Tag tag = el.tag(); tag.setSeenSelfClose(); // can infer output if in xml syntax if (tag.isEmpty()) { // treated as empty below; nothing further } else if (tag.isKnownTag() && tag.isSelfClosing()) { // ok, allow it. effectively a pop, but fiddles with the state. handles empty style, title etc which would otherwise leave us in data state tokeniser.transition(TokeniserState.Data); // handles <script />, otherwise needs breakout steps from script data tokeniser.emit(emptyEnd.reset().name(el.tagName())); // ensure we get out of whatever state we are in. emitted for yielded processing } else { // error it, and leave the inserted element on tokeniser.error("Tag [%s] cannot be self-closing; not a void tag", tag.normalName()); } } if (el.tag().isEmpty()) { pop(); // custom void tags behave like built-in voids (no children, not left on the stack); known empty go via insertEmpty } return el; } /** Inserts a foreign element. Preserves the case of the tag name and of the attributes. */ Element insertForeignElementFor(final Token.StartTag startTag, String namespace) { Element el = createElementFor(startTag, namespace, true); doInsertElement(el); if (startTag.isSelfClosing()) { // foreign els are OK to self-close el.tag().setSeenSelfClose(); // remember this is self-closing for output pop(); } return el; } Element insertEmptyElementFor(Token.StartTag startTag) { Element el = createElementFor(startTag, NamespaceHtml, false); doInsertElement(el); pop(); return el; } FormElement insertFormElement(Token.StartTag startTag, boolean onStack, boolean checkTemplateStack) { FormElement el = (FormElement) createElementFor(startTag, NamespaceHtml, false); if (checkTemplateStack) { if(!onStack("template")) setFormElement(el); } else setFormElement(el); doInsertElement(el); if (!onStack) pop(); return el; } /** Inserts the Element onto the stack. All element inserts must run through this method. Performs any general tests on the Element before insertion. * @param el the Element to insert and make the current element */ private void doInsertElement(Element el) { enforceStackDepthLimit(); if (formElement != null && el.tag().namespace.equals(NamespaceHtml) && StringUtil.inSorted(el.normalName(), TagFormListed)) formElement.addElement(el); // connect form controls to their form element // in HTML, the xmlns attribute if set must match what the parser set the tag's namespace to if (parser.getErrors().canAddError() && el.hasAttr("xmlns") && !el.attr("xmlns").equals(el.tag().namespace())) error("Invalid xmlns attribute [%s] on tag [%s]", el.attr("xmlns"), el.tagName()); if (isFosterInserts() && StringUtil.inSorted(currentElement().normalName(), InTableFoster)) insertInFosterParent(el); else currentElement().appendChild(el); push(el); } void insertCommentNode(Token.Comment token) { Comment node = new Comment(token.getData()); currentElement().appendChild(node); onNodeInserted(node); } /** Inserts the provided character token into the current element. Any nulls in the data will be removed. */ void insertCharacterNode(Token.Character characterToken) { insertCharacterNode(characterToken, false); } /** Inserts the provided character token into the current element. The tokenizer will have already raised precise character errors. @param characterToken the character token to insert @param replace if true, replaces any null chars in the data with the replacement char (U+FFFD). If false, removes null chars. */ void insertCharacterNode(Token.Character characterToken, boolean replace) { characterToken.normalizeNulls(replace); Element el = currentElement(); // will be doc if no current element; allows for whitespace to be inserted into the doc root object (not on the stack) insertCharacterToElement(characterToken, el); } /** Inserts the provided character token into the provided element. */ void insertCharacterToElement(Token.Character characterToken, Element el) { final Node node; final String data = characterToken.getData(); if (characterToken.isCData()) node = new CDataNode(data); else if (el.tag().is(Tag.Data)) node = new DataNode(data); else node = new TextNode(data); el.appendChild(node); // doesn't use insertNode, because we don't foster these; and will always have a stack. onNodeInserted(node); } ArrayList<Element> getStack() { return stack; } boolean onStack(Element el) { return onStack(stack, el); } /** Checks if there is an HTML element with the given name on the stack. */ boolean onStack(String elName) { return getFromStack(elName) != null; } private static final int maxQueueDepth = 256; // an arbitrary tension point between real HTML and crafted pain private static boolean onStack(ArrayList<Element> queue, Element element) { final int bottom = queue.size() - 1; final int upper = bottom >= maxQueueDepth ? bottom - maxQueueDepth : 0; for (int pos = bottom; pos >= upper; pos--) { Element next = queue.get(pos); if (next == element) { return true; } } return false; } /** Gets the nearest (lowest) HTML element with the given name from the stack. */ @Nullable Element getFromStack(String elName) { final int bottom = stack.size() - 1; final int upper = bottom >= maxQueueDepth ? bottom - maxQueueDepth : 0; for (int pos = bottom; pos >= upper; pos--) { Element next = stack.get(pos); if (next.elementIs(elName, NamespaceHtml)) { return next; } } return null; } boolean removeFromStack(Element el) { for (int pos = stack.size() -1; pos >= 0; pos--) { Element next = stack.get(pos); if (next == el) { stack.remove(pos); onNodeClosed(el); return true; } } return false; } @Override void onStackPrunedForDepth(Element element) { // handle other effects of popping to keep state correct if (element == headElement) headElement = null; if (element == formElement) setFormElement(null); removeFromActiveFormattingElements(element); if (element.nameIs("template")) { clearFormattingElementsToLastMarker(); if (templateModeSize() > 0) popTemplateMode(); resetInsertionMode(); } } /** Pops the stack until the given HTML element is removed. */ @Nullable Element popStackToClose(String elName) { for (int pos = stack.size() -1; pos >= 0; pos--) { Element el = pop(); if (el.elementIs(elName, NamespaceHtml)) { return el; } } return null; } /** Pops the stack until an element with the supplied name is removed, irrespective of namespace. */ @Nullable Element popStackToCloseAnyNamespace(String elName) { for (int pos = stack.size() -1; pos >= 0; pos--) { Element el = pop(); if (el.nameIs(elName)) { return el; } } return null; } /** Pops the stack until one of the given HTML elements is removed. */ void popStackToClose(String... elNames) { // elnames is sorted, comes from Constants for (int pos = stack.size() -1; pos >= 0; pos--) { Element el = pop(); if (inSorted(el.normalName(), elNames) && NamespaceHtml.equals(el.tag().namespace())) { break; } } } void clearStackToTableContext() { clearStackToContext("table", "template"); } void clearStackToTableBodyContext() { clearStackToContext("tbody", "tfoot", "thead", "template"); } void clearStackToTableRowContext() { clearStackToContext("tr", "template"); } /** Removes elements from the stack until one of the supplied HTML elements is removed. */ private void clearStackToContext(String... nodeNames) { for (int pos = stack.size() -1; pos >= 0; pos--) { Element next = stack.get(pos); if (NamespaceHtml.equals(next.tag().namespace()) && (StringUtil.in(next.normalName(), nodeNames) || next.nameIs("html"))) break; else pop(); } } /** Gets the Element immediately above the supplied element on the stack. Which due to adoption, may not necessarily be its parent. @param el @return the Element immediately above the supplied element, or null if there is no such element. */ @Nullable Element aboveOnStack(Element el) { if (!onStack(el)) return null; for (int pos = stack.size() -1; pos > 0; pos--) { Element next = stack.get(pos); if (next == el) { return stack.get(pos-1); } } return null; } void insertOnStackAfter(Element after, Element in) { int i = stack.lastIndexOf(after); if (i == -1) { error("Did not find element on stack to insert after"); stack.add(in); // may happen on particularly malformed inputs during adoption } else { stack.add(i+1, in); } } void replaceOnStack(Element out, Element in) { replaceInQueue(stack, out, in); } private static void replaceInQueue(ArrayList<Element> queue, Element out, Element in) { int i = queue.lastIndexOf(out); Validate.isTrue(i != -1); queue.set(i, in); } /** * Reset the insertion mode, by searching up the stack for an appropriate insertion mode. The stack search depth * is limited to {@link #maxQueueDepth}. * @return true if the insertion mode was actually changed. */ boolean resetInsertionMode() { // https://html.spec.whatwg.org/multipage/parsing.html#the-insertion-mode boolean last = false; final int bottom = stack.size() - 1; final int upper = bottom >= maxQueueDepth ? bottom - maxQueueDepth : 0; final HtmlTreeBuilderState origState = this.state; if (stack.size() == 0) { // nothing left of stack, just get to body transition(HtmlTreeBuilderState.InBody); } LOOP: for (int pos = bottom; pos >= upper; pos--) { Element node = stack.get(pos); if (pos == upper) { last = true; if (fragmentParsing) node = contextElement; } String name = node != null ? node.normalName() : ""; if (!NamespaceHtml.equals(node.tag().namespace())) continue; // only looking for HTML elements here switch (name) { case "select": transition(HtmlTreeBuilderState.InSelect); // todo - should loop up (with some limit) and check for table or template hits break LOOP; case "td": case "th": if (!last) { transition(HtmlTreeBuilderState.InCell); break LOOP; } break; case "tr": transition(HtmlTreeBuilderState.InRow); break LOOP; case "tbody": case "thead": case "tfoot": transition(HtmlTreeBuilderState.InTableBody); break LOOP; case "caption": transition(HtmlTreeBuilderState.InCaption); break LOOP; case "colgroup": transition(HtmlTreeBuilderState.InColumnGroup); break LOOP; case "table": transition(HtmlTreeBuilderState.InTable); break LOOP; case "template": HtmlTreeBuilderState tmplState = currentTemplateMode(); Validate.notNull(tmplState, "Bug: no template insertion mode on stack!"); transition(tmplState); break LOOP; case "head": if (!last) { transition(HtmlTreeBuilderState.InHead); break LOOP; } break; case "body": transition(HtmlTreeBuilderState.InBody); break LOOP; case "frameset": transition(HtmlTreeBuilderState.InFrameset); break LOOP; case "html": transition(headElement == null ? HtmlTreeBuilderState.BeforeHead : HtmlTreeBuilderState.AfterHead); break LOOP; } if (last) { transition(HtmlTreeBuilderState.InBody); break; } } return state != origState; } /** Places the body back onto the stack and moves to InBody, for cases in AfterBody / AfterAfterBody when more content comes */ void resetBody() { if (!onStack("body")) { stack.add(doc.body()); // not onNodeInserted, as already seen } transition(HtmlTreeBuilderState.InBody); } // todo: tidy up in specific scope methods private final String[] specificScopeTarget = {null}; private boolean inSpecificScope(String targetName, String[] baseTypes, String[] extraTypes) { specificScopeTarget[0] = targetName; return inSpecificScope(specificScopeTarget, baseTypes, extraTypes); } private boolean inSpecificScope(String[] targetNames, String[] baseTypes, @Nullable String[] extraTypes) { // https://html.spec.whatwg.org/multipage/parsing.html#has-an-element-in-the-specific-scope final int bottom = stack.size() -1; // don't walk too far up the tree for (int pos = bottom; pos >= 0; pos--) { Element el = stack.get(pos); String elName = el.normalName(); // namespace checks - arguments provided are always in html ns, with this bolt-on for math and svg: String ns = el.tag().namespace(); if (ns.equals(NamespaceHtml)) { if (inSorted(elName, targetNames)) return true; if (inSorted(elName, baseTypes)) return false; if (extraTypes != null && inSorted(elName, extraTypes)) return false; } else if (baseTypes == TagsSearchInScope) { if (ns.equals(NamespaceMathml) && inSorted(elName, TagSearchInScopeMath)) return false; if (ns.equals(NamespaceSvg) && inSorted(elName, TagSearchInScopeSvg)) return false; } } //Validate.fail("Should not be reachable"); // would end up false because hitting 'html' at root (basetypes) return false; } boolean inScope(String[] targetNames) { return inSpecificScope(targetNames, TagsSearchInScope, null); } boolean inScope(String targetName) { return inScope(targetName, null); } boolean inScope(String targetName, String[] extras) { return inSpecificScope(targetName, TagsSearchInScope, extras); } boolean inListItemScope(String targetName) { return inScope(targetName, TagSearchList); } boolean inButtonScope(String targetName) { return inScope(targetName, TagSearchButton); } boolean inTableScope(String targetName) { return inSpecificScope(targetName, TagSearchTableScope, null); } boolean inSelectScope(String targetName) { for (int pos = stack.size() -1; pos >= 0; pos--) { Element el = stack.get(pos); String elName = el.normalName(); if (elName.equals(targetName)) return true; if (!inSorted(elName, TagSearchSelectScope)) // all elements except return false; } return false; // nothing left on stack } /** Tests if there is some element on the stack that is not in the provided set. */ boolean onStackNot(String[] allowedTags) { for (int pos = stack.size() - 1; pos >= 0; pos--) { final String elName = stack.get(pos).normalName(); if (!inSorted(elName, allowedTags)) return true; } return false; } void setHeadElement(Element headElement) { this.headElement = headElement; } Element getHeadElement() { return headElement; } boolean isFosterInserts() { return fosterInserts; } void setFosterInserts(boolean fosterInserts) { this.fosterInserts = fosterInserts; } @Nullable FormElement getFormElement() { return formElement; } void setFormElement(FormElement formElement) { this.formElement = formElement; } void resetPendingTableCharacters() { pendingTableCharacters.clear(); } List<Token.Character> getPendingTableCharacters() { return pendingTableCharacters; } void addPendingTableCharacters(Token.Character c) { // make a copy of the token to maintain its state (as Tokens are otherwise reset) Token.Character copy = new Token.Character(c); pendingTableCharacters.add(copy); } /** 13.2.6.3 Closing elements that have implied end tags When the steps below require the UA to generate implied end tags, then, while the current node is a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, or an rtc element, the UA must pop the current node off the stack of open elements. If a step requires the UA to generate implied end tags but lists an element to exclude from the process, then the UA must perform the above steps as if that element was not in the above list. When the steps below require the UA to generate all implied end tags thoroughly, then, while the current node is a caption element, a colgroup element, a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, or a tr element, the UA must pop the current node off the stack of open elements. @param excludeTag If a step requires the UA to generate implied end tags but lists an element to exclude from the process, then the UA must perform the above steps as if that element was not in the above list. */ void generateImpliedEndTags(String excludeTag) { while (inSorted(currentElement().normalName(), TagSearchEndTags)) { if (excludeTag != null && currentElementIs(excludeTag)) break; pop(); } } void generateImpliedEndTags() { generateImpliedEndTags(false); } /** Pops HTML elements off the stack according to the implied end tag rules @param thorough if we are thorough (includes table elements etc) or not */ void generateImpliedEndTags(boolean thorough) { final String[] search = thorough ? TagThoroughSearchEndTags : TagSearchEndTags; while (NamespaceHtml.equals(currentElement().tag().namespace()) && inSorted(currentElement().normalName(), search)) { pop(); } } void closeElement(String name) { generateImpliedEndTags(name); if (!name.equals(currentElement().normalName())) error(state()); popStackToClose(name); } static boolean isSpecial(Element el) { String namespace = el.tag().namespace(); String name = el.normalName(); switch (namespace) { case NamespaceHtml: return inSorted(name, TagSearchSpecial); case Parser.NamespaceMathml: return inSorted(name, TagSearchSpecialMath); case Parser.NamespaceSvg: return inSorted(name, TagSvgHtmlIntegration); default: return false; } } Element lastFormattingElement() { return formattingElements.size() > 0 ? formattingElements.get(formattingElements.size()-1) : null; } int positionOfElement(Element el){ for (int i = 0; i < formattingElements.size(); i++){ if (el == formattingElements.get(i)) return i; } return -1; } Element removeLastFormattingElement() { int size = formattingElements.size(); if (size > 0) return formattingElements.remove(size-1); else return null; } // active formatting elements void pushActiveFormattingElements(Element in) { checkActiveFormattingElements(in); formattingElements.add(in); } void pushWithBookmark(Element in, int bookmark){ checkActiveFormattingElements(in); // catch any range errors and assume bookmark is incorrect - saves a redundant range check. try { formattingElements.add(bookmark, in); } catch (IndexOutOfBoundsException e) { formattingElements.add(in); } } void checkActiveFormattingElements(Element in){ int numSeen = 0; final int size = formattingElements.size() -1; int ceil = size - maxUsedFormattingElements; if (ceil <0) ceil = 0; for (int pos = size; pos >= ceil; pos--) { Element el = formattingElements.get(pos); if (el == null) // marker break; if (isSameFormattingElement(in, el)) numSeen++; if (numSeen == 3) { formattingElements.remove(pos); break; } } } private static boolean isSameFormattingElement(Element a, Element b) { // same if: same namespace, tag, and attributes. Element.equals only checks tag, might in future check children return a.normalName().equals(b.normalName()) && // a.namespace().equals(b.namespace()) && a.attributes().equals(b.attributes()); // todo: namespaces } void reconstructFormattingElements() { if (stack.size() > maxQueueDepth) return; Element last = lastFormattingElement(); if (last == null || onStack(last)) return; Element entry = last; int size = formattingElements.size(); int ceil = size - maxUsedFormattingElements; if (ceil <0) ceil = 0; int pos = size - 1; boolean skip = false; while (true) { if (pos == ceil) { // step 4. if none before, skip to 8 skip = true; break; } entry = formattingElements.get(--pos); // step 5. one earlier than entry if (entry == null || onStack(entry)) // step 6 - neither marker nor on stack break; // jump to 8, else continue back to 4 } while(true) { if (!skip) // step 7: on later than entry entry = formattingElements.get(++pos); Validate.notNull(entry); // should not occur, as we break at last element // 8. create new element from element, 9 insert into current node, onto stack skip = false; // can only skip increment from 4. Element newEl = new Element(tagFor(entry.nodeName(), entry.normalName(), defaultNamespace(), settings), null, entry.attributes().clone()); doInsertElement(newEl); // 10. replace entry with new entry formattingElements.set(pos, newEl); // 11 if (pos == size-1) // if not last entry in list, jump to 7 break; } } private static final int maxUsedFormattingElements = 12; // limit how many elements get recreated void clearFormattingElementsToLastMarker() { while (!formattingElements.isEmpty()) { Element el = removeLastFormattingElement(); if (el == null) break; } } void removeFromActiveFormattingElements(Element el) { for (int pos = formattingElements.size() -1; pos >= 0; pos--) { Element next = formattingElements.get(pos); if (next == el) { formattingElements.remove(pos); break; } } } boolean isInActiveFormattingElements(Element el) { return onStack(formattingElements, el); } @Nullable Element getActiveFormattingElement(String nodeName) { for (int pos = formattingElements.size() -1; pos >= 0; pos--) { Element next = formattingElements.get(pos); if (next == null) // scope marker break; else if (next.nameIs(nodeName)) return next; } return null; } void replaceActiveFormattingElement(Element out, Element in) { replaceInQueue(formattingElements, out, in); } void insertMarkerToFormattingElements() { formattingElements.add(null); } void insertInFosterParent(Node in) { Element fosterParent; Element lastTable = getFromStack("table"); boolean isLastTableParent = false; if (lastTable != null) { if (lastTable.parent() != null) { fosterParent = lastTable.parent(); isLastTableParent = true; } else fosterParent = aboveOnStack(lastTable); } else { // no table == frag fosterParent = stack.get(0); } if (isLastTableParent) { Validate.notNull(lastTable); // last table cannot be null by this point. lastTable.before(in); } else fosterParent.appendChild(in); } // Template Insertion Mode stack void pushTemplateMode(HtmlTreeBuilderState state) { tmplInsertMode.add(state); } @Nullable HtmlTreeBuilderState popTemplateMode() { if (tmplInsertMode.size() > 0) { return tmplInsertMode.remove(tmplInsertMode.size() -1); } else { return null; } } int templateModeSize() { return tmplInsertMode.size(); } @Nullable HtmlTreeBuilderState currentTemplateMode() { return (tmplInsertMode.size() > 0) ? tmplInsertMode.get(tmplInsertMode.size() -1) : null; } @Override public String toString() { return "TreeBuilder{" + "currentToken=" + currentToken + ", state=" + state + ", currentElement=" + currentElement() + '}'; } }
HtmlTreeBuilder
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/MvMedian.java
{ "start": 1888, "end": 4305 }
class ____ extends AbstractMultivalueFunction { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(Expression.class, "MvMedian", MvMedian::new); @FunctionInfo( returnType = { "double", "integer", "long", "unsigned_long" }, description = "Converts a multivalued field into a single valued field containing the median value.", examples = { @Example(file = "math", tag = "mv_median"), @Example( description = "If the row has an even number of values for a column, " + "the result will be the average of the middle two entries. If the column is not floating point, " + "the average rounds **down**:", file = "math", tag = "mv_median_round_down" ) } ) public MvMedian( Source source, @Param( name = "number", type = { "double", "integer", "long", "unsigned_long" }, description = "Multivalue expression." ) Expression field ) { super(source, field); } private MvMedian(StreamInput in) throws IOException { super(in); } @Override public String getWriteableName() { return ENTRY.name; } @Override protected TypeResolution resolveFieldType() { return isType(field(), t -> t.isNumeric() && isRepresentable(t), sourceText(), null, "numeric"); } @Override protected ExpressionEvaluator.Factory evaluator(ExpressionEvaluator.Factory fieldEval) { return switch (PlannerUtils.toElementType(field().dataType())) { case DOUBLE -> new MvMedianDoubleEvaluator.Factory(fieldEval); case INT -> new MvMedianIntEvaluator.Factory(fieldEval); case LONG -> field().dataType() == DataType.UNSIGNED_LONG ? new MvMedianUnsignedLongEvaluator.Factory(fieldEval) : new MvMedianLongEvaluator.Factory(fieldEval); default -> throw EsqlIllegalArgumentException.illegalDataType(field.dataType()); }; } @Override public Expression replaceChildren(List<Expression> newChildren) { return new MvMedian(source(), newChildren.get(0)); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, MvMedian::new, field()); } static
MvMedian
java
alibaba__nacos
ai/src/test/java/com/alibaba/nacos/ai/remote/handler/QueryMcpServerRequestHandlerTest.java
{ "start": 1559, "end": 3785 }
class ____ { @Mock private McpServerOperationService mcpServerOperationService; @Mock private McpServerIndex mcpServerIndex; QueryMcpServerRequestHandler requestHandler; @BeforeEach void setUp() { requestHandler = new QueryMcpServerRequestHandler(mcpServerOperationService, mcpServerIndex); } @AfterEach void tearDown() { } @Test void handleWithInvalidParam() throws NacosException { QueryMcpServerRequest request = new QueryMcpServerRequest(); QueryMcpServerResponse response = requestHandler.handle(request, null); assertEquals(ResponseCode.FAIL.getCode(), response.getResultCode()); assertEquals(NacosException.INVALID_PARAM, response.getErrorCode()); assertEquals("parameters `mcpName` can't be empty or null", response.getMessage()); } @Test void handleMcpServerNotFound() throws NacosException { QueryMcpServerRequest request = new QueryMcpServerRequest(); request.setMcpName("test"); QueryMcpServerResponse response = requestHandler.handle(request, null); assertEquals(ResponseCode.FAIL.getCode(), response.getResultCode()); assertEquals(NacosException.NOT_FOUND, response.getErrorCode()); assertEquals("MCP server `test` not found in namespaceId: `public`", response.getMessage()); } @Test void handle() throws NacosException { QueryMcpServerRequest request = new QueryMcpServerRequest(); request.setMcpName("test"); McpServerIndexData indexData = new McpServerIndexData(); indexData.setId(UUID.randomUUID().toString()); indexData.setNamespaceId("public"); when(mcpServerIndex.getMcpServerByName("public", "test")).thenReturn(indexData); McpServerDetailInfo mcpServerDetailInfo = new McpServerDetailInfo(); when(mcpServerOperationService.getMcpServerDetail("public", indexData.getId(), null, null)).thenReturn( mcpServerDetailInfo); QueryMcpServerResponse response = requestHandler.handle(request, null); assertEquals(mcpServerDetailInfo, response.getMcpServerDetailInfo()); } }
QueryMcpServerRequestHandlerTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/PgEventEndpointBuilderFactory.java
{ "start": 15653, "end": 19313 }
interface ____ extends EndpointProducerBuilder { default PgEventEndpointProducerBuilder basic() { return (PgEventEndpointProducerBuilder) this; } /** * 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: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedPgEventEndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * 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 will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedPgEventEndpointProducerBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * To connect using the given javax.sql.DataSource instead of using * hostname and port. * * The option is a: <code>javax.sql.DataSource</code> type. * * Group: advanced * * @param datasource the value to set * @return the dsl builder */ default AdvancedPgEventEndpointProducerBuilder datasource(javax.sql.DataSource datasource) { doSetProperty("datasource", datasource); return this; } /** * To connect using the given javax.sql.DataSource instead of using * hostname and port. * * The option will be converted to a <code>javax.sql.DataSource</code> * type. * * Group: advanced * * @param datasource the value to set * @return the dsl builder */ default AdvancedPgEventEndpointProducerBuilder datasource(String datasource) { doSetProperty("datasource", datasource); return this; } } /** * Builder for endpoint for the PostgresSQL Event component. */ public
AdvancedPgEventEndpointProducerBuilder
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/various/ExportIdentifierTest.java
{ "start": 1180, "end": 2979 }
class ____ { @Test @JiraKey(value = "HHH-12935") public void testUniqueExportableIdentifier() { final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry(); final MetadataBuilderImpl.MetadataBuildingOptionsImpl options = new MetadataBuilderImpl.MetadataBuildingOptionsImpl( ssr ); options.setBootstrapContext( new BootstrapContextImpl( ssr, options ) ); final Database database = new Database( options ); database.locateNamespace( null, null ); database.locateNamespace( Identifier.toIdentifier( "catalog1" ), null ); database.locateNamespace( Identifier.toIdentifier( "catalog2" ), null ); database.locateNamespace( null, Identifier.toIdentifier( "schema1" ) ); database.locateNamespace( null, Identifier.toIdentifier( "schema2" ) ); database.locateNamespace( Identifier.toIdentifier( "catalog_both_1" ), Identifier.toIdentifier( "schema_both_1" ) ); database.locateNamespace( Identifier.toIdentifier( "catalog_both_2" ), Identifier.toIdentifier( "schema_both_2" ) ); try { final Set<String> exportIdentifierSet = new HashSet<>(); int namespaceSize = 0; for ( Namespace namespace : database.getNamespaces() ) { final SequenceStructure sequenceStructure = new SequenceStructure( "envers", new QualifiedNameImpl( namespace.getName(), Identifier.toIdentifier( "aSequence" ) ), 1, 1, Integer.class ); sequenceStructure.registerExportables( database ); exportIdentifierSet.add( namespace.getSequences().iterator().next().getExportIdentifier() ); namespaceSize++; } assertThat( namespaceSize ).isEqualTo( 7 ); assertThat( exportIdentifierSet.size() ).isEqualTo( 7 ); } finally { StandardServiceRegistryBuilder.destroy( ssr ); } } }
ExportIdentifierTest
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/spi-deployment/src/main/java/io/quarkus/resteasy/reactive/server/spi/PreExceptionMapperHandlerBuildItem.java
{ "start": 462, "end": 1269 }
class ____ extends MultiBuildItem implements Comparable<PreExceptionMapperHandlerBuildItem> { private final ServerRestHandler handler; private final int priority; public PreExceptionMapperHandlerBuildItem(ServerRestHandler handler, int priority) { this.handler = handler; this.priority = priority; } public PreExceptionMapperHandlerBuildItem(ServerRestHandler handler) { this.handler = handler; this.priority = Priorities.USER; } @Override public int compareTo(PreExceptionMapperHandlerBuildItem o) { return Integer.compare(priority, o.priority); } public ServerRestHandler getHandler() { return handler; } public int getPriority() { return priority; } }
PreExceptionMapperHandlerBuildItem
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/SwigMemoryLeak.java
{ "start": 1439, "end": 2293 }
class ____ extends BugChecker implements LiteralTreeMatcher { private static final Matcher<MethodTree> ENCLOSING_CLASS_HAS_FINALIZER = Matchers.enclosingClass(Matchers.hasMethod(Matchers.methodIsNamed("finalize"))); @Override public Description matchLiteral(LiteralTree tree, VisitorState state) { // Is there a literal matching the message SWIG uses to indicate a // destructor problem? if (tree.getValue() == null || !tree.getValue().equals("C++ destructor does not have public access")) { return NO_MATCH; } // Is it within a delete method? MethodTree enclosingMethodTree = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class); Name name = enclosingMethodTree.getName(); if (!name.contentEquals("delete")) { return NO_MATCH; } // Does the enclosing
SwigMemoryLeak
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/hhh16711/Inheriting.java
{ "start": 330, "end": 450 }
class ____ extends Inherited { Inheriting(String id, String name) { super(id, name); } Inheriting() { } }
Inheriting
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/floatarray/FloatArrayAssert_endsWith_with_Float_array_Test.java
{ "start": 1316, "end": 2251 }
class ____ extends FloatArrayAssertBaseTest { @Test void should_fail_if_values_is_null() { // GIVEN Float[] sequence = null; // WHEN Throwable thrown = catchThrowable(() -> assertions.endsWith(sequence)); // THEN then(thrown).isInstanceOf(NullPointerException.class) .hasMessage(shouldNotBeNull("sequence").create()); } @Test void should_pass_if_values_are_in_range_of_precision() { // GIVEN Float[] values = new Float[] { 2.1f, 2.9f }; // WHEN/THEN assertThat(arrayOf(1.0f, 2.0f, 3.0f)).endsWith(values, withPrecision(0.2f)); } @Override protected FloatArrayAssert invoke_api_method() { return assertions.endsWith(new Float[] { 1.0f, 2.0f }); } @Override protected void verify_internal_effects() { verify(arrays).assertEndsWith(getInfo(assertions), getActual(assertions), arrayOf(1.0f, 2.0f)); } }
FloatArrayAssert_endsWith_with_Float_array_Test
java
alibaba__nacos
client/src/main/java/com/alibaba/nacos/client/config/impl/ClientWorker.java
{ "start": 26360, "end": 64594 }
class ____ extends ConfigTransportClient { Map<String, ExecutorService> multiTaskExecutor = new HashMap<>(); private ExecutorService listenExecutor; private final BlockingQueue<Object> listenExecutebell = new ArrayBlockingQueue<>(1); private final Object bellItem = new Object(); private long lastAllSyncTime = System.currentTimeMillis(); Subscriber subscriber = null; /** * 3 minutes to check all listen cache keys. */ private static final long ALL_SYNC_INTERNAL = 3 * 60 * 1000L; public ConfigRpcTransportClient(NacosClientProperties properties, ConfigServerListManager serverListManager) { super(properties, serverListManager); } private ConnectionType getConnectionType() { return ConnectionType.GRPC; } @Override public void shutdown() throws NacosException { super.shutdown(); synchronized (RpcClientFactory.getAllClientEntries()) { LOGGER.info("Trying to shutdown transport client {}", this); Set<Map.Entry<String, RpcClient>> allClientEntries = RpcClientFactory.getAllClientEntries(); Iterator<Map.Entry<String, RpcClient>> iterator = allClientEntries.iterator(); while (iterator.hasNext()) { Map.Entry<String, RpcClient> entry = iterator.next(); if (entry.getKey().startsWith(uuid)) { LOGGER.info("Trying to shutdown rpc client {}", entry.getKey()); try { entry.getValue().shutdown(); } catch (NacosException nacosException) { nacosException.printStackTrace(); } LOGGER.info("Remove rpc client {}", entry.getKey()); iterator.remove(); } } LOGGER.info("Shutdown executor {}", agent.getExecutor()); agent.getExecutor().shutdown(); Map<String, CacheData> stringCacheDataMap = cacheMap.get(); for (Map.Entry<String, CacheData> entry : stringCacheDataMap.entrySet()) { entry.getValue().setConsistentWithServer(false); } if (subscriber != null) { NotifyCenter.deregisterSubscriber(subscriber); } multiTaskExecutor.values().forEach((executor) -> { if (executor != null && !executor.isShutdown()) { LOGGER.info("Shutdown multi task executor {}", executor); executor.shutdown(); } }); if (listenExecutor != null && !listenExecutor.isShutdown()) { LOGGER.info("Shutdown listen config executor {}", listenExecutor); listenExecutor.shutdown(); } } } private Map<String, String> getLabels() { Map<String, String> labels = new HashMap<>(2, 1); labels.put(RemoteConstants.LABEL_SOURCE, RemoteConstants.LABEL_SOURCE_SDK); labels.put(RemoteConstants.LABEL_MODULE, RemoteConstants.LABEL_MODULE_CONFIG); labels.put(Constants.APPNAME, AppNameUtils.getAppName()); if (EnvUtil.getSelfVipserverTag() != null) { labels.put(Constants.VIPSERVER_TAG, EnvUtil.getSelfVipserverTag()); } if (EnvUtil.getSelfAmoryTag() != null) { labels.put(Constants.AMORY_TAG, EnvUtil.getSelfAmoryTag()); } if (EnvUtil.getSelfLocationTag() != null) { labels.put(Constants.LOCATION_TAG, EnvUtil.getSelfLocationTag()); } labels.putAll(appLabels); return labels; } ConfigChangeNotifyResponse handleConfigChangeNotifyRequest(ConfigChangeNotifyRequest configChangeNotifyRequest, String clientName) { LOGGER.info("[{}] [server-push] config changed. dataId={}, group={},tenant={}", clientName, configChangeNotifyRequest.getDataId(), configChangeNotifyRequest.getGroup(), configChangeNotifyRequest.getTenant()); String groupKey = GroupKey.getKeyTenant(configChangeNotifyRequest.getDataId(), configChangeNotifyRequest.getGroup(), configChangeNotifyRequest.getTenant()); CacheData cacheData = cacheMap.get().get(groupKey); if (cacheData != null) { synchronized (cacheData) { cacheData.getReceiveNotifyChanged().set(true); cacheData.setConsistentWithServer(false); notifyListenConfig(); } } return new ConfigChangeNotifyResponse(); } ClientConfigMetricResponse handleClientMetricsRequest(ClientConfigMetricRequest configMetricRequest) { ClientConfigMetricResponse response = new ClientConfigMetricResponse(); response.setMetrics(getMetrics(configMetricRequest.getMetricsKeys())); return response; } @SuppressWarnings("PMD.MethodTooLongRule") private void initRpcClientHandler(final RpcClient rpcClientInner) { /* * Register Config Change /Config ReSync Handler */ rpcClientInner.registerServerRequestHandler((request, connection) -> { //config change notify if (request instanceof ConfigChangeNotifyRequest) { return handleConfigChangeNotifyRequest((ConfigChangeNotifyRequest) request, rpcClientInner.getName()); } return null; }); rpcClientInner.registerServerRequestHandler((request, connection) -> { if (request instanceof ClientConfigMetricRequest) { return handleClientMetricsRequest((ClientConfigMetricRequest) request); } return null; }); rpcClientInner.registerServerRequestHandler( new ClientFuzzyWatchNotifyRequestHandler(configFuzzyWatchGroupKeyHolder)); rpcClientInner.registerConnectionListener(new ConnectionEventListener() { @Override public void onConnected(Connection connection) { LOGGER.info("[{}] Connected,notify listen context...", rpcClientInner.getName()); notifyListenConfig(); LOGGER.info("[{}] Connected,notify fuzzy listen context...", rpcClientInner.getName()); configFuzzyWatchGroupKeyHolder.notifyFuzzyWatchSync(); } @Override public void onDisConnect(Connection connection) { String taskId = rpcClientInner.getLabels().get("taskId"); LOGGER.info("[{}] DisConnected,reset listen context", rpcClientInner.getName()); Collection<CacheData> values = cacheMap.get().values(); for (CacheData cacheData : values) { if (StringUtils.isNotBlank(taskId)) { if (Integer.valueOf(taskId).equals(cacheData.getTaskId())) { cacheData.setConsistentWithServer(false); } } else { cacheData.setConsistentWithServer(false); } } LOGGER.info("[{}] DisConnected,reset fuzzy watch consistence status", rpcClientInner.getName()); configFuzzyWatchGroupKeyHolder.resetConsistenceStatus(); } }); rpcClientInner.serverListFactory(new ServerListFactory() { @Override public String genNextServer() { return ConfigRpcTransportClient.super.serverListManager.genNextServer(); } @Override public String getCurrentServer() { return ConfigRpcTransportClient.super.serverListManager.getCurrentServer(); } @Override public List<String> getServerList() { return ConfigRpcTransportClient.super.serverListManager.getServerList(); } }); subscriber = new Subscriber() { @Override public void onEvent(Event event) { rpcClientInner.onServerListChange(); } @Override public Class<? extends Event> subscribeType() { return ServerListChangeEvent.class; } }; NotifyCenter.registerSubscriber(subscriber); } @Override public void startInternal() { listenExecutor = Executors.newSingleThreadExecutor(new NameThreadFactory("com.alibaba.nacos.client.listen-executor")); listenExecutor.submit(() -> { while (!listenExecutor.isShutdown() && !listenExecutor.isTerminated()) { try { listenExecutebell.poll(5L, TimeUnit.SECONDS); if (listenExecutor.isShutdown() || listenExecutor.isTerminated()) { continue; } executeConfigListen(); } catch (Throwable e) { LOGGER.error("[rpc listen execute] [rpc listen] exception", e); try { Thread.sleep(50L); } catch (InterruptedException interruptedException) { //ignore } notifyListenConfig(); } } }); } @Override public String getName() { return serverListManager.getName(); } @Override public void notifyListenConfig() { listenExecutebell.offer(bellItem); } @Override public void executeConfigListen() throws NacosException { Map<String, List<CacheData>> listenCachesMap = new HashMap<>(16); Map<String, List<CacheData>> removeListenCachesMap = new HashMap<>(16); long now = System.currentTimeMillis(); boolean needAllSync = now - lastAllSyncTime >= ALL_SYNC_INTERNAL; for (CacheData cache : cacheMap.get().values()) { synchronized (cache) { checkLocalConfig(cache); // check local listeners consistent. if (cache.isConsistentWithServer()) { cache.checkListenerMd5(); if (!needAllSync) { continue; } } // If local configuration information is used, then skip the processing directly. if (cache.isUseLocalConfigInfo()) { continue; } if (!cache.isDiscard()) { List<CacheData> cacheDatas = listenCachesMap.computeIfAbsent(String.valueOf(cache.getTaskId()), k -> new LinkedList<>()); cacheDatas.add(cache); } else { List<CacheData> cacheDatas = removeListenCachesMap.computeIfAbsent( String.valueOf(cache.getTaskId()), k -> new LinkedList<>()); cacheDatas.add(cache); } } } //execute check listen ,return true if has change keys. boolean hasChangedKeys = checkListenCache(listenCachesMap); //execute check remove listen. checkRemoveListenCache(removeListenCachesMap); if (needAllSync) { lastAllSyncTime = now; } //If has changed keys,notify re sync md5. if (hasChangedKeys) { notifyListenConfig(); } } /** * Checks and handles local configuration for a given CacheData object. This method evaluates the use of * failover files for local configuration storage and updates the CacheData accordingly. * * @param cacheData The CacheData object to be processed. */ public void checkLocalConfig(CacheData cacheData) { final String dataId = cacheData.dataId; final String group = cacheData.group; final String tenant = cacheData.tenant; final String envName = cacheData.envName; // Check if a failover file exists for the specified dataId, group, and tenant. File file = LocalConfigInfoProcessor.getFailoverFile(envName, dataId, group, tenant); // If not using local config info and a failover file exists, load and use it. if (!cacheData.isUseLocalConfigInfo() && file.exists()) { String content = LocalConfigInfoProcessor.getFailover(envName, dataId, group, tenant); final String md5 = MD5Utils.md5Hex(content, Constants.ENCODE); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(file.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file created. dataId={}, group={}, tenant={}, md5={}", envName, dataId, group, tenant, md5); return; } // If use local config info, but the failover file is deleted, switch back to server config. if (cacheData.isUseLocalConfigInfo() && !file.exists()) { cacheData.setUseLocalConfigInfo(false); LOGGER.warn("[{}] [failover-change] failover file deleted. dataId={}, group={}, tenant={}", envName, dataId, group, tenant); return; } // When the failover file content changes, indicating a change in local configuration. if (cacheData.isUseLocalConfigInfo() && file.exists() && cacheData.getLocalConfigInfoVersion() != file.lastModified()) { String content = LocalConfigInfoProcessor.getFailover(envName, dataId, group, tenant); final String md5 = MD5Utils.md5Hex(content, Constants.ENCODE); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(file.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file changed. dataId={}, group={}, tenant={}, md5={}", envName, dataId, group, tenant, md5); } } private ExecutorService ensureSyncExecutor(String taskId) { if (!multiTaskExecutor.containsKey(taskId)) { multiTaskExecutor.put(taskId, new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), r -> { Thread thread = new Thread(r, "nacos.client.config.listener.task-" + taskId); thread.setDaemon(true); return thread; })); } return multiTaskExecutor.get(taskId); } private void refreshContentAndCheck(RpcClient rpcClient, String groupKey, boolean notify) { if (cacheMap.get() != null && cacheMap.get().containsKey(groupKey)) { CacheData cache = cacheMap.get().get(groupKey); refreshContentAndCheck(rpcClient, cache, notify); } } private void refreshContentAndCheck(RpcClient rpcClient, CacheData cacheData, boolean notify) { try { ConfigResponse response = this.queryConfigInner(rpcClient, cacheData.dataId, cacheData.group, cacheData.tenant, requestTimeout, notify); cacheData.setEncryptedDataKey(response.getEncryptedDataKey()); cacheData.setContent(response.getContent()); if (null != response.getConfigType()) { cacheData.setType(response.getConfigType()); } if (notify) { LOGGER.info("[{}] [data-received] dataId={}, group={}, tenant={}, md5={}, type={}", agent.getName(), cacheData.dataId, cacheData.group, cacheData.tenant, cacheData.getMd5(), response.getConfigType()); } cacheData.checkListenerMd5(); } catch (Exception e) { LOGGER.error("refresh content and check md5 fail ,dataId={},group={},tenant={} ", cacheData.dataId, cacheData.group, cacheData.tenant, e); } } private void checkRemoveListenCache(Map<String, List<CacheData>> removeListenCachesMap) throws NacosException { if (!removeListenCachesMap.isEmpty()) { List<Future> listenFutures = new ArrayList<>(); for (Map.Entry<String, List<CacheData>> entry : removeListenCachesMap.entrySet()) { String taskId = entry.getKey(); RpcClient rpcClient = ensureRpcClient(taskId); ExecutorService executorService = ensureSyncExecutor(taskId); Future future = executorService.submit(() -> { List<CacheData> removeListenCaches = entry.getValue(); ConfigBatchListenRequest configChangeListenRequest = buildConfigRequest(removeListenCaches); configChangeListenRequest.setListen(false); try { boolean removeSuccess = unListenConfigChange(rpcClient, configChangeListenRequest); if (removeSuccess) { for (CacheData cacheData : removeListenCaches) { synchronized (cacheData) { if (cacheData.isDiscard() && cacheData.getListeners().isEmpty()) { ClientWorker.this.removeCache(cacheData.dataId, cacheData.group, cacheData.tenant); } } } } } catch (Throwable e) { LOGGER.error("Async remove listen config change error ", e); try { Thread.sleep(50L); } catch (InterruptedException interruptedException) { //ignore } notifyListenConfig(); } }); listenFutures.add(future); } for (Future future : listenFutures) { try { future.get(); } catch (Throwable throwable) { LOGGER.error("Async remove listen config change error ", throwable); } } } } @SuppressWarnings("PMD.MethodTooLongRule") private boolean checkListenCache(Map<String, List<CacheData>> listenCachesMap) throws NacosException { final AtomicBoolean hasChangedKeys = new AtomicBoolean(false); if (!listenCachesMap.isEmpty()) { List<Future> listenFutures = new ArrayList<>(); for (Map.Entry<String, List<CacheData>> entry : listenCachesMap.entrySet()) { String taskId = entry.getKey(); RpcClient rpcClient = ensureRpcClient(taskId); ExecutorService executorService = ensureSyncExecutor(taskId); Future future = executorService.submit(() -> { List<CacheData> listenCaches = entry.getValue(); //reset notify change flag. for (CacheData cacheData : listenCaches) { cacheData.getReceiveNotifyChanged().set(false); } ConfigBatchListenRequest configChangeListenRequest = buildConfigRequest(listenCaches); configChangeListenRequest.setListen(true); try { ConfigChangeBatchListenResponse listenResponse = (ConfigChangeBatchListenResponse) requestProxy( rpcClient, configChangeListenRequest); if (listenResponse != null && listenResponse.isSuccess()) { Set<String> changeKeys = new HashSet<String>(); List<ConfigChangeBatchListenResponse.ConfigContext> changedConfigs = listenResponse.getChangedConfigs(); //handle changed keys,notify listener if (!CollectionUtils.isEmpty(changedConfigs)) { hasChangedKeys.set(true); for (ConfigChangeBatchListenResponse.ConfigContext changeConfig : changedConfigs) { String changeKey = GroupKey.getKeyTenant(changeConfig.getDataId(), changeConfig.getGroup(), changeConfig.getTenant()); changeKeys.add(changeKey); boolean isInitializing = cacheMap.get().get(changeKey).isInitializing(); refreshContentAndCheck(rpcClient, changeKey, !isInitializing); } } for (CacheData cacheData : listenCaches) { if (cacheData.getReceiveNotifyChanged().get()) { String changeKey = GroupKey.getKeyTenant(cacheData.dataId, cacheData.group, cacheData.getTenant()); if (!changeKeys.contains(changeKey)) { boolean isInitializing = cacheMap.get().get(changeKey).isInitializing(); refreshContentAndCheck(rpcClient, changeKey, !isInitializing); } } } //handler content configs for (CacheData cacheData : listenCaches) { cacheData.setInitializing(false); String groupKey = GroupKey.getKeyTenant(cacheData.dataId, cacheData.group, cacheData.getTenant()); if (!changeKeys.contains(groupKey)) { synchronized (cacheData) { if (!cacheData.getReceiveNotifyChanged().get()) { cacheData.setConsistentWithServer(true); } } } } } } catch (Throwable e) { LOGGER.error("Execute listen config change error ", e); try { Thread.sleep(50L); } catch (InterruptedException interruptedException) { //ignore } notifyListenConfig(); } }); listenFutures.add(future); } for (Future future : listenFutures) { try { future.get(); } catch (Throwable throwable) { LOGGER.error("Async listen config change error ", throwable); } } } return hasChangedKeys.get(); } RpcClient ensureRpcClient(String taskId) throws NacosException { synchronized (ClientWorker.this) { Map<String, String> labels = getLabels(); Map<String, String> newLabels = new HashMap<>(labels); newLabels.put("taskId", taskId); GrpcClientConfig grpcClientConfig = RpcClientConfigFactory.getInstance() .createGrpcClientConfig(properties, newLabels); RpcClient rpcClient = RpcClientFactory.createClient(uuid + "_config-" + taskId, getConnectionType(), grpcClientConfig); if (rpcClient.isWaitInitiated()) { initRpcClientHandler(rpcClient); rpcClient.setTenant(getTenant()); rpcClient.start(); } return rpcClient; } } /** * build config string. * * @param caches caches to build config string. * @return request. */ private ConfigBatchListenRequest buildConfigRequest(List<CacheData> caches) { ConfigBatchListenRequest configChangeListenRequest = new ConfigBatchListenRequest(); for (CacheData cacheData : caches) { configChangeListenRequest.addConfigListenContext(cacheData.group, cacheData.dataId, cacheData.tenant, cacheData.getMd5()); } return configChangeListenRequest; } @Override public void removeCache(String dataId, String group) { // Notify to rpc un listen ,and remove cache if success. notifyListenConfig(); } /** * send cancel listen config change request . * * @param configChangeListenRequest request of remove listen config string. */ private boolean unListenConfigChange(RpcClient rpcClient, ConfigBatchListenRequest configChangeListenRequest) throws NacosException { ConfigChangeBatchListenResponse response = (ConfigChangeBatchListenResponse) requestProxy(rpcClient, configChangeListenRequest); return response.isSuccess(); } @Override public ConfigResponse queryConfig(String dataId, String group, String tenant, long readTimeouts, boolean notify) throws NacosException { RpcClient rpcClient = getOneRunningClient(); if (notify) { CacheData cacheData = cacheMap.get().get(GroupKey.getKeyTenant(dataId, group, tenant)); if (cacheData != null) { rpcClient = ensureRpcClient(String.valueOf(cacheData.getTaskId())); } } return queryConfigInner(rpcClient, dataId, group, tenant, readTimeouts, notify); } ConfigResponse queryConfigInner(RpcClient rpcClient, String dataId, String group, String tenant, long readTimeouts, boolean notify) throws NacosException { ConfigQueryRequest request = ConfigQueryRequest.build(dataId, group, tenant); request.putHeader(NOTIFY_HEADER, String.valueOf(notify)); ConfigQueryResponse response = (ConfigQueryResponse) requestProxy(rpcClient, request, readTimeouts); ConfigResponse configResponse = new ConfigResponse(); if (response.isSuccess()) { LocalConfigInfoProcessor.saveSnapshot(this.getName(), dataId, group, tenant, response.getContent()); configResponse.setContent(response.getContent()); String configType; if (StringUtils.isNotBlank(response.getContentType())) { configType = response.getContentType(); } else { configType = ConfigType.TEXT.getType(); } configResponse.setConfigType(configType); String encryptedDataKey = response.getEncryptedDataKey(); LocalEncryptedDataKeyProcessor.saveEncryptDataKeySnapshot(agent.getName(), dataId, group, tenant, encryptedDataKey); configResponse.setEncryptedDataKey(encryptedDataKey); return configResponse; } else if (response.getErrorCode() == ConfigQueryResponse.CONFIG_NOT_FOUND) { LocalConfigInfoProcessor.saveSnapshot(this.getName(), dataId, group, tenant, null); LocalEncryptedDataKeyProcessor.saveEncryptDataKeySnapshot(agent.getName(), dataId, group, tenant, null); return configResponse; } else if (response.getErrorCode() == ConfigQueryResponse.CONFIG_QUERY_CONFLICT) { LOGGER.error( "[{}] [sub-server-error] get server config being modified concurrently, dataId={}, group={}, " + "tenant={}", this.getName(), dataId, group, tenant); throw new NacosException(NacosException.CONFLICT, "data being modified, dataId=" + dataId + ",group=" + group + ",tenant=" + tenant); } else { LOGGER.error("[{}] [sub-server-error] dataId={}, group={}, tenant={}, code={}", this.getName(), dataId, group, tenant, response); throw new NacosException(response.getErrorCode(), "http error, code=" + response.getErrorCode() + ",msg=" + response.getMessage() + ",dataId=" + dataId + ",group=" + group + ",tenant=" + tenant); } } Response requestProxy(RpcClient rpcClientInner, Request request) throws NacosException { return requestProxy(rpcClientInner, request, requestTimeout); } private Response requestProxy(RpcClient rpcClientInner, Request request, long timeoutMills) throws NacosException { try { request.putAllHeader(super.getSecurityHeaders(resourceBuild(request))); request.putAllHeader(super.getCommonHeader()); } catch (Exception e) { throw new NacosException(NacosException.CLIENT_INVALID_PARAM, e); } JsonObject asJsonObjectTemp = new Gson().toJsonTree(request).getAsJsonObject(); asJsonObjectTemp.remove("headers"); asJsonObjectTemp.remove("requestId"); boolean limit = Limiter.isLimit(request.getClass() + asJsonObjectTemp.toString()); if (limit) { throw new NacosException(NacosException.CLIENT_OVER_THRESHOLD, "More than client-side current limit threshold"); } Response response; if (timeoutMills < 0) { response = rpcClientInner.request(request); } else { response = rpcClientInner.request(request, timeoutMills); } // If the 403 login operation is triggered, refresh the accessToken of the client if (response.getErrorCode() == ConfigQueryResponse.NO_RIGHT) { reLogin(); } return response; } private RequestResource resourceBuild(Request request) { if (request instanceof ConfigQueryRequest) { String tenant = ((ConfigQueryRequest) request).getTenant(); String group = ((ConfigQueryRequest) request).getGroup(); String dataId = ((ConfigQueryRequest) request).getDataId(); return buildResource(tenant, group, dataId); } if (request instanceof ConfigPublishRequest) { String tenant = ((ConfigPublishRequest) request).getTenant(); String group = ((ConfigPublishRequest) request).getGroup(); String dataId = ((ConfigPublishRequest) request).getDataId(); return buildResource(tenant, group, dataId); } if (request instanceof ConfigRemoveRequest) { String tenant = ((ConfigRemoveRequest) request).getTenant(); String group = ((ConfigRemoveRequest) request).getGroup(); String dataId = ((ConfigRemoveRequest) request).getDataId(); return buildResource(tenant, group, dataId); } return RequestResource.configBuilder().build(); } RpcClient getOneRunningClient() throws NacosException { return ensureRpcClient("0"); } @Override public boolean publishConfig(String dataId, String group, String tenant, String appName, String tag, String betaIps, String content, String encryptedDataKey, String casMd5, String type) throws NacosException { try { ConfigPublishRequest request = new ConfigPublishRequest(dataId, group, tenant, content); request.setCasMd5(casMd5); request.putAdditionalParam(TAG_PARAM, tag); request.putAdditionalParam(APP_NAME_PARAM, appName); request.putAdditionalParam(BETAIPS_PARAM, betaIps); request.putAdditionalParam(TYPE_PARAM, type); request.putAdditionalParam(ENCRYPTED_DATA_KEY_PARAM, encryptedDataKey == null ? "" : encryptedDataKey); ConfigPublishResponse response = (ConfigPublishResponse) requestProxy(getOneRunningClient(), request); if (!response.isSuccess()) { LOGGER.warn("[{}] [publish-single] fail, dataId={}, group={}, tenant={}, code={}, msg={}", this.getName(), dataId, group, tenant, response.getErrorCode(), response.getMessage()); return false; } else { LOGGER.info("[{}] [publish-single] ok, dataId={}, group={}, tenant={}", getName(), dataId, group, tenant); return true; } } catch (Exception e) { LOGGER.warn("[{}] [publish-single] error, dataId={}, group={}, tenant={}, code={}, msg={}", this.getName(), dataId, group, tenant, "unknown", e.getMessage()); return false; } } @Override public boolean removeConfig(String dataId, String group, String tenant, String tag) throws NacosException { ConfigRemoveRequest request = new ConfigRemoveRequest(dataId, group, tenant, tag); ConfigRemoveResponse response = (ConfigRemoveResponse) requestProxy(getOneRunningClient(), request); return response.isSuccess(); } /** * check server is health. * * @return */ public boolean isHealthServer() { try { return getOneRunningClient().isRunning(); } catch (NacosException e) { LOGGER.warn("check server status failed.", e); return false; } } /** * Determine whether nacos-server supports the capability. * * @param abilityKey ability key * @return true if supported, otherwise false */ public boolean isAbilitySupportedByServer(AbilityKey abilityKey) { try { return getOneRunningClient().getConnectionAbility(abilityKey) == AbilityStatus.SUPPORTED; } catch (NacosException e) { throw new NacosRuntimeException(e.getErrCode(), "Get Running Client failed: ", e); } } } public String getAgentName() { return agent.getName(); } public ConfigTransportClient getAgent() { return agent; } }
ConfigRpcTransportClient
java
quarkusio__quarkus
test-framework/common/src/test/java/io/quarkus/test/common/PathTestHelperTest.java
{ "start": 768, "end": 1044 }
class ____ we don't have many of them in jars, but that should still work Path path = PathTestHelper.getTestClassesLocation(org.jboss.logging.Logger.class); assertNotNull(path); assertTrue(path.toString().contains(".jar"), path.toString()); } }
because
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/builder/abstractGenericTarget/ImmutableParent.java
{ "start": 906, "end": 1518 }
class ____ { private int count; private ImmutableChild child; private Child nonGenericChild; public Builder count(int count) { this.count = count; return this; } public Builder nonGenericChild(Child nonGenericChild) { this.nonGenericChild = nonGenericChild; return this; } public Builder child(ImmutableChild child) { this.child = child; return this; } public ImmutableParent build() { return new ImmutableParent( this ); } } }
Builder
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/socket/server/upgrade/DefaultServerEndpointConfig.java
{ "start": 1254, "end": 2938 }
class ____ extends ServerEndpointConfig.Configurator implements ServerEndpointConfig { private final String path; private final Endpoint endpoint; private List<String> protocols = new ArrayList<>(); /** * Constructor with a path and an {@code jakarta.websocket.Endpoint}. * @param path the endpoint path * @param endpoint the endpoint instance */ public DefaultServerEndpointConfig(String path, Endpoint endpoint) { Assert.hasText(path, "path must not be empty"); Assert.notNull(endpoint, "endpoint must not be null"); this.path = path; this.endpoint = endpoint; } @Override public List<Class<? extends Encoder>> getEncoders() { return new ArrayList<>(); } @Override public List<Class<? extends Decoder>> getDecoders() { return new ArrayList<>(); } @Override public Map<String, Object> getUserProperties() { return new HashMap<>(); } @Override public Class<?> getEndpointClass() { return this.endpoint.getClass(); } @Override public String getPath() { return this.path; } public void setSubprotocols(List<String> protocols) { this.protocols = protocols; } @Override public List<String> getSubprotocols() { return this.protocols; } @Override public List<Extension> getExtensions() { return new ArrayList<>(); } @Override public Configurator getConfigurator() { return this; } @SuppressWarnings("unchecked") @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { return (T) this.endpoint; } @Override public String toString() { return "DefaultServerEndpointConfig for path '" + getPath() + "': " + getEndpointClass(); } }
DefaultServerEndpointConfig
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/OptionTag.java
{ "start": 5838, "end": 11333 }
class ____ extends AbstractHtmlElementBodyTag implements BodyTag { /** * The name of the JSP variable used to expose the value for this tag. */ public static final String VALUE_VARIABLE_NAME = "value"; /** * The name of the JSP variable used to expose the display value for this tag. */ public static final String DISPLAY_VALUE_VARIABLE_NAME = "displayValue"; /** * The name of the '{@code selected}' attribute. */ private static final String SELECTED_ATTRIBUTE = "selected"; /** * The name of the '{@code value}' attribute. */ private static final String VALUE_ATTRIBUTE = VALUE_VARIABLE_NAME; /** * The name of the '{@code disabled}' attribute. */ private static final String DISABLED_ATTRIBUTE = "disabled"; /** * The 'value' attribute of the rendered HTML {@code <option>} tag. */ private @Nullable Object value; /** * The text body of the rendered HTML {@code <option>} tag. */ private @Nullable String label; private @Nullable Object oldValue; private @Nullable Object oldDisplayValue; private boolean disabled; /** * Set the 'value' attribute of the rendered HTML {@code <option>} tag. */ public void setValue(Object value) { this.value = value; } /** * Get the 'value' attribute of the rendered HTML {@code <option>} tag. */ protected @Nullable Object getValue() { return this.value; } /** * Set the value of the '{@code disabled}' attribute. */ public void setDisabled(boolean disabled) { this.disabled = disabled; } /** * Get the value of the '{@code disabled}' attribute. */ protected boolean isDisabled() { return this.disabled; } /** * Set the text body of the rendered HTML {@code <option>} tag. * <p>May be a runtime expression. */ public void setLabel(String label) { this.label = label; } /** * Get the text body of the rendered HTML {@code <option>} tag. */ protected @Nullable String getLabel() { return this.label; } @Override protected void renderDefaultContent(TagWriter tagWriter) throws JspException { Object value = this.pageContext.getAttribute(VALUE_VARIABLE_NAME); String label = getLabelValue(value); renderOption(value, label, tagWriter); } @Override protected void renderFromBodyContent(BodyContent bodyContent, TagWriter tagWriter) throws JspException { Object value = this.pageContext.getAttribute(VALUE_VARIABLE_NAME); String label = bodyContent.getString(); renderOption(value, label, tagWriter); } /** * Make sure we are under a '{@code select}' tag before proceeding. */ @Override protected void onWriteTagContent() { assertUnderSelectTag(); } @Override protected void exposeAttributes() throws JspException { Object value = resolveValue(); this.oldValue = this.pageContext.getAttribute(VALUE_VARIABLE_NAME); this.pageContext.setAttribute(VALUE_VARIABLE_NAME, value); this.oldDisplayValue = this.pageContext.getAttribute(DISPLAY_VALUE_VARIABLE_NAME); this.pageContext.setAttribute(DISPLAY_VALUE_VARIABLE_NAME, getDisplayString(value, getBindStatus().getEditor())); } @Override protected BindStatus getBindStatus() { return (BindStatus) this.pageContext.getAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE); } @Override protected void removeAttributes() { if (this.oldValue != null) { this.pageContext.setAttribute(VALUE_ATTRIBUTE, this.oldValue); this.oldValue = null; } else { this.pageContext.removeAttribute(VALUE_VARIABLE_NAME); } if (this.oldDisplayValue != null) { this.pageContext.setAttribute(DISPLAY_VALUE_VARIABLE_NAME, this.oldDisplayValue); this.oldDisplayValue = null; } else { this.pageContext.removeAttribute(DISPLAY_VALUE_VARIABLE_NAME); } } private void renderOption(Object value, String label, TagWriter tagWriter) throws JspException { tagWriter.startTag("option"); writeOptionalAttribute(tagWriter, "id", resolveId()); writeOptionalAttributes(tagWriter); String renderedValue = getDisplayString(value, getBindStatus().getEditor()); renderedValue = processFieldValue(getSelectTag().getName(), renderedValue, "option"); tagWriter.writeAttribute(VALUE_ATTRIBUTE, renderedValue); if (isSelected(value)) { tagWriter.writeAttribute(SELECTED_ATTRIBUTE, SELECTED_ATTRIBUTE); } if (isDisabled()) { tagWriter.writeAttribute(DISABLED_ATTRIBUTE, "disabled"); } tagWriter.appendValue(label); tagWriter.endTag(); } @Override protected @Nullable String autogenerateId() throws JspException { return null; } /** * Return the value of the label for this '{@code option}' element. * <p>If the {@link #setLabel label} property is set then the resolved value * of that property is used, otherwise the value of the {@code resolvedValue} * argument is used. */ private String getLabelValue(Object resolvedValue) throws JspException { String label = getLabel(); Object labelObj = (label == null ? resolvedValue : evaluate("label", label)); return getDisplayString(labelObj, getBindStatus().getEditor()); } private void assertUnderSelectTag() { TagUtils.assertHasAncestorOfType(this, SelectTag.class, "option", "select"); } private SelectTag getSelectTag() { return (SelectTag) findAncestorWithClass(this, SelectTag.class); } private boolean isSelected(Object resolvedValue) { return SelectedValueComparator.isSelected(getBindStatus(), resolvedValue); } private @Nullable Object resolveValue() throws JspException { return evaluate(VALUE_VARIABLE_NAME, getValue()); } }
OptionTag
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/calc/async/AsyncFunctionRunner.java
{ "start": 1395, "end": 1961 }
class ____ extends AbstractAsyncFunctionRunner<RowData> { private static final long serialVersionUID = -7198305381139008806L; public AsyncFunctionRunner( GeneratedFunction<AsyncFunction<RowData, RowData>> generatedFetcher) { super(generatedFetcher); } @Override public void asyncInvoke(RowData input, ResultFuture<RowData> resultFuture) { try { fetcher.asyncInvoke(input, resultFuture); } catch (Throwable t) { resultFuture.completeExceptionally(t); } } }
AsyncFunctionRunner
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/TenantIdToOneBidirectionalTest.java
{ "start": 4129, "end": 4445 }
class ____ { @Id private Long id; @TenantId @Column(name="tenant_col") private String tenant; @OneToOne( mappedBy = "child" ) private RootEntity root; public ChildEntity() { } public ChildEntity(Long id) { this.id = id; } public RootEntity getRoot() { return root; } } }
ChildEntity
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/boot/jaxb/mapping/SimpleEntity.java
{ "start": 368, "end": 737 }
class ____ { @Id private Integer id; @Basic private String name; private SimpleEntity() { // for Hibernate use } public SimpleEntity(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
SimpleEntity
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderedBySQLTest.java
{ "start": 1182, "end": 2229 }
class ____ { @Test public void testLifecycle(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { Person person = new Person(); person.setId(1L); person.setName("Vlad Mihalcea"); person.addArticle( new Article( "High-Performance JDBC", "Connection Management, Statement Caching, Batch Updates" ) ); person.addArticle( new Article( "High-Performance Hibernate", "Associations, Lazy fetching, Concurrency Control, Second-level Caching" ) ); entityManager.persist(person); }); scope.inTransaction( entityManager -> { //tag::collections-customizing-ordered-by-sql-clause-fetching-example[] Person person = entityManager.find(Person.class, 1L); assertEquals( "High-Performance Hibernate", person.getArticles().get(0).getName() ); //end::collections-customizing-ordered-by-sql-clause-fetching-example[] }); } //tag::collections-customizing-ordered-by-sql-clause-mapping-example[] @Entity(name = "Person") public static
OrderedBySQLTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/feature/FeaturesTest7.java
{ "start": 1175, "end": 1224 }
enum ____ { SECONDS, MINUTES } }
TimeUnit
java
google__guava
android/guava/src/com/google/common/collect/Tables.java
{ "start": 1921, "end": 5640 }
class ____ { private Tables() {} /** * Returns a {@link Collector} that accumulates elements into a {@code Table} created using the * specified supplier, whose cells are generated by applying the provided mapping functions to the * input elements. Cells are inserted into the generated {@code Table} in encounter order. * * <p>If multiple input elements map to the same row and column, an {@code IllegalStateException} * is thrown when the collection operation is performed. * * <p>To collect to an {@link ImmutableTable}, use {@link ImmutableTable#toImmutableTable}. * * @since 33.2.0 (available since 21.0 in guava-jre) */ @IgnoreJRERequirement // Users will use this only if they're already using streams. public static < T extends @Nullable Object, R extends @Nullable Object, C extends @Nullable Object, V, I extends Table<R, C, V>> Collector<T, ?, I> toTable( java.util.function.Function<? super T, ? extends R> rowFunction, java.util.function.Function<? super T, ? extends C> columnFunction, java.util.function.Function<? super T, ? extends V> valueFunction, java.util.function.Supplier<I> tableSupplier) { return TableCollectors.<T, R, C, V, I>toTable( rowFunction, columnFunction, valueFunction, tableSupplier); } /** * Returns a {@link Collector} that accumulates elements into a {@code Table} created using the * specified supplier, whose cells are generated by applying the provided mapping functions to the * input elements. Cells are inserted into the generated {@code Table} in encounter order. * * <p>If multiple input elements map to the same row and column, the specified merging function is * used to combine the values. Like {@link * java.util.stream.Collectors#toMap(java.util.function.Function, java.util.function.Function, * BinaryOperator, java.util.function.Supplier)}, this Collector throws a {@code * NullPointerException} on null values returned from {@code valueFunction}, and treats nulls * returned from {@code mergeFunction} as removals of that row/column pair. * * @since 33.2.0 (available since 21.0 in guava-jre) */ @IgnoreJRERequirement // Users will use this only if they're already using streams. public static < T extends @Nullable Object, R extends @Nullable Object, C extends @Nullable Object, V, I extends Table<R, C, V>> Collector<T, ?, I> toTable( java.util.function.Function<? super T, ? extends R> rowFunction, java.util.function.Function<? super T, ? extends C> columnFunction, java.util.function.Function<? super T, ? extends V> valueFunction, BinaryOperator<V> mergeFunction, java.util.function.Supplier<I> tableSupplier) { return TableCollectors.<T, R, C, V, I>toTable( rowFunction, columnFunction, valueFunction, mergeFunction, tableSupplier); } /** * Returns an immutable cell with the specified row key, column key, and value. * * <p>The returned cell is serializable. * * @param rowKey the row key to be associated with the returned cell * @param columnKey the column key to be associated with the returned cell * @param value the value to be associated with the returned cell */ public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Cell<R, C, V> immutableCell( @ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value) { return new ImmutableCell<>(rowKey, columnKey, value); } static final
Tables
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/connector/source/DynamicParallelismInference.java
{ "start": 1463, "end": 2396 }
interface ____ { /** * Get the dynamic filtering info of the source vertex. * * @return the dynamic filter instance. */ Optional<DynamicFilteringInfo> getDynamicFilteringInfo(); /** * Get the upper bound for the inferred parallelism. * * @return the upper bound for the inferred parallelism. */ int getParallelismInferenceUpperBound(); /** * Get the average size of data volume (in bytes) to expect each task instance to process. * * @return the data volume per task in bytes. */ long getDataVolumePerTask(); } /** * The method is invoked on the master (JobManager) before the initialization of the source * vertex. * * @param context The context to get dynamic parallelism decision infos. */ int inferParallelism(Context context); }
Context
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/concurrent/InboundMessageQueueTest.java
{ "start": 978, "end": 1250 }
class ____ extends VertxTestBase { private volatile Thread producerThread; private volatile Thread consumerThread; Context context; TestChannel queue; final AtomicInteger sequence = new AtomicInteger(); InboundMessageQueueTest() { }
InboundMessageQueueTest
java
mapstruct__mapstruct
integrationtest/src/test/resources/freeBuilderBuilderTest/src/test/java/org/mapstruct/itest/freebuilder/FreeBuilderMapperTest.java
{ "start": 381, "end": 1458 }
class ____ { @Test public void testSimpleImmutableBuilderHappyPath() { PersonDto personDto = PersonMapper.INSTANCE.toDto( Person.builder() .setAge( 33 ) .setName( "Bob" ) .setAddress( Address.builder() .setAddressLine( "Wild Drive" ) .build() ) .build() ); assertThat( personDto.getAge() ).isEqualTo( 33 ); assertThat( personDto.getName() ).isEqualTo( "Bob" ); assertThat( personDto.getAddress() ).isNotNull(); assertThat( personDto.getAddress().getAddressLine() ).isEqualTo( "Wild Drive" ); } @Test public void testLombokToImmutable() { Person person = PersonMapper.INSTANCE.fromDto( new PersonDto( "Bob", 33, new AddressDto( "Wild Drive" ) ) ); assertThat( person.getAge() ).isEqualTo( 33 ); assertThat( person.getName() ).isEqualTo( "Bob" ); assertThat( person.getAddress() ).isNotNull(); assertThat( person.getAddress().getAddressLine() ).isEqualTo( "Wild Drive" ); } }
FreeBuilderMapperTest
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java
{ "start": 97500, "end": 97820 }
class ____ { private Resource @Nullable [] resources; Resource @Nullable [] getResources() { return this.resources; } void setResources(Resource @Nullable [] resources) { this.resources = resources; } } @EnableConfigurationProperties(ResourceCollectionProperties.class) static
ResourceArrayProperties
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/http/HttpSecurityBeanDefinitionParser.java
{ "start": 21308, "end": 22297 }
class ____ extends MethodInvokingFactoryBean { @Override public void afterPropertiesSet() throws Exception { boolean isTargetProviderManager = getTargetObject() instanceof ProviderManager; if (!isTargetProviderManager) { setTargetObject(this); } super.afterPropertiesSet(); } /** * The default value if the target object is not a ProviderManager is false. We * use false because this feature is associated with {@link ProviderManager} not * {@link AuthenticationManager}. If the user wants to leverage * {@link ProviderManager#setEraseCredentialsAfterAuthentication(boolean)} their * original {@link AuthenticationManager} must be a {@link ProviderManager} (we * should not magically add this functionality to their implementation since we * cannot determine if it should be on or off). * @return */ boolean isEraseCredentialsAfterAuthentication() { return false; } } public static final
ClearCredentialsMethodInvokingFactoryBean
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/externalresource/ExternalResourceDriver.java
{ "start": 1278, "end": 1707 }
interface ____ { /** * Retrieve the information of the external resources according to the amount. * * @param amount of the required external resources * @return information set of the required external resources * @throws Exception if there is something wrong during retrieving */ Set<? extends ExternalResourceInfo> retrieveResourceInfo(long amount) throws Exception; }
ExternalResourceDriver
java
google__auto
common/src/test/java/com/google/auto/common/OverridesTest.java
{ "start": 12645, "end": 12741 }
interface ____<E> { @SuppressWarnings("unused") boolean add(E e); } private
XCollection
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/internal/transformation/impl/TransformedArtifact.java
{ "start": 1820, "end": 4926 }
class ____ extends DefaultArtifact { private static final int SHA1_BUFFER_SIZE = 8192; private final PomArtifactTransformer pomArtifactTransformer; private final MavenProject project; private final Supplier<ModelSource> sourcePathProvider; private final Path target; private final RepositorySystemSession session; private final AtomicReference<String> sourceState; @SuppressWarnings("checkstyle:ParameterNumber") TransformedArtifact( PomArtifactTransformer pomArtifactTransformer, MavenProject project, Path target, RepositorySystemSession session, org.apache.maven.artifact.Artifact source, Supplier<ModelSource> sourcePathProvider, String classifier, String extension) { super( source.getGroupId(), source.getArtifactId(), source.getVersionRange(), source.getScope(), extension, classifier, new TransformedArtifactHandler( classifier, extension, source.getArtifactHandler().getPackaging())); this.pomArtifactTransformer = pomArtifactTransformer; this.project = project; this.target = target; this.session = session; this.sourcePathProvider = sourcePathProvider; this.sourceState = new AtomicReference<>(null); } @Override public boolean isResolved() { return getFile() != null; } @Override public void setFile(File file) { throw new UnsupportedOperationException("transformed artifact file cannot be set"); } @Override public synchronized File getFile() { try { String state = mayUpdate(); if (state == null) { return null; } return target.toFile(); } catch (IOException | XMLStreamException | ModelBuilderException e) { throw new TransformationFailedException(e); } } private String mayUpdate() throws IOException, XMLStreamException, ModelBuilderException { String result; ModelSource src = sourcePathProvider.get(); if (src == null) { Files.deleteIfExists(target); result = null; } else if (!Files.exists(src.getPath())) { Files.deleteIfExists(target); result = ""; } else { String current = ChecksumAlgorithmHelper.calculate( src.getPath(), List.of(new Sha1ChecksumAlgorithmFactory())) .get(Sha1ChecksumAlgorithmFactory.NAME); String existing = sourceState.get(); if (!Files.exists(target) || !Objects.equals(current, existing)) { pomArtifactTransformer.transform(project, session, src, target); Files.setLastModifiedTime(target, Files.getLastModifiedTime(src.getPath())); } result = current; } sourceState.set(result); return result; } }
TransformedArtifact
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SmbEndpointBuilderFactory.java
{ "start": 152731, "end": 160313 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final SmbHeaderNameBuilder INSTANCE = new SmbHeaderNameBuilder(); /** * A long value containing the file size. * * The option is a: {@code long} type. * * Group: consumer * * @return the name of the header {@code FileLength}. */ public String fileLength() { return "CamelFileLength"; } /** * A Long value containing the last modified timestamp of the file. * * The option is a: {@code long} type. * * Group: consumer * * @return the name of the header {@code FileLastModified}. */ public String fileLastModified() { return "CamelFileLastModified"; } /** * Only the file name (the name with no leading paths). * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code FileNameOnly}. */ public String fileNameOnly() { return "CamelFileNameOnly"; } /** * (producer) Specifies the name of the file to write (relative to the * endpoint directory). This name can be a String; a String with a file * or simple Language expression; or an Expression object. If it's null * then Camel will auto-generate a filename based on the message unique * ID. (consumer) Name of the consumed file as a relative file path with * offset from the starting directory configured on the endpoint. * * The option is a: {@code String} type. * * Group: common * * @return the name of the header {@code FileName}. */ public String fileName() { return "CamelFileName"; } /** * The name of the file that has been consumed. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code FileNameConsumed}. */ public String fileNameConsumed() { return "CamelFileNameConsumed"; } /** * A boolean option specifying whether the consumed file denotes an * absolute path or not. Should normally be false for relative paths. * Absolute paths should normally not be used but we added to the move * option to allow moving files to absolute paths. But can be used * elsewhere as well. * * The option is a: {@code Boolean} type. * * Group: consumer * * @return the name of the header {@code FileAbsolute}. */ public String fileAbsolute() { return "CamelFileAbsolute"; } /** * The absolute path to the file. For relative files this path holds the * relative path instead. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code FileAbsolutePath}. */ public String fileAbsolutePath() { return "CamelFileAbsolutePath"; } /** * The file path. For relative files this is the starting directory. For * absolute files this is the absolute path. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code FilePath}. */ public String filePath() { return "CamelFilePath"; } /** * The relative path. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code FileRelativePath}. */ public String fileRelativePath() { return "CamelFileRelativePath"; } /** * The parent path. * * The option is a: {@code String} type. * * Group: common * * @return the name of the header {@code FileParent}. */ public String fileParent() { return "CamelFileParent"; } /** * The actual absolute filepath (path name) for the output file that was * written. This header is set by Camel and its purpose is providing * end-users with the name of the file that was written. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code FileNameProduced}. */ public String fileNameProduced() { return "CamelFileNameProduced"; } /** * Is used for overruling CamelFileName header and use the value instead * (but only once, as the producer will remove this header after writing * the file). The value can be only be a String. Notice that if the * option fileName has been configured, then this is still being * evaluated. * * The option is a: {@code Object} type. * * Group: producer * * @return the name of the header {@code OverruleFileName}. */ public String overruleFileName() { return "CamelOverruleFileName"; } /** * The remote hostname. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code FileHost}. */ public String fileHost() { return "CamelFileHost"; } /** * The remote file input stream. * * The option is a: {@code java.io.InputStream} type. * * Group: consumer * * @return the name of the header {@code SmbFileInputStream}. */ public String smbFileInputStream() { return "CamelSmbFileInputStream"; } /** * Path to the local work file, if local work directory is used. * * The option is a: {@code String} type. * * Group: common * * @return the name of the header {@code FileLocalWorkPath}. */ public String fileLocalWorkPath() { return "CamelFileLocalWorkPath"; } /** * The expected behavior if the file already exists. * * The option is a: {@code * org.apache.camel.component.file.GenericFileExist} type. * * Group: producer * * @return the name of the header {@code SmbFileExists}. */ @Deprecated public String smbFileExists() { return "CamelSmbFileExists"; } /** * UNC path to the retrieved file. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code SmbUncPath}. */ public String smbUncPath() { return "CamelSmbUncPath"; } } static SmbEndpointBuilder endpointBuilder(String componentName, String path) {
SmbHeaderNameBuilder
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/injection/guice/spi/ProviderLookup.java
{ "start": 1200, "end": 3083 }
class ____<T> implements Provider<T> { private final ProviderLookup<T> lookup; private ProviderImpl(ProviderLookup<T> lookup) { this.lookup = lookup; } @Override public T get() { if (lookup.delegate == null) { throw new IllegalStateException("This Provider cannot be used until the Injector has been created."); } return lookup.delegate.get(); } @Override public String toString() { return "Provider<" + lookup.key.getTypeLiteral() + ">"; } } private final Object source; private final Key<T> key; private Provider<T> delegate; public ProviderLookup(Object source, Key<T> key) { this.source = Objects.requireNonNull(source, "source"); this.key = Objects.requireNonNull(key, "key"); } @Override public Object getSource() { return source; } public Key<T> getKey() { return key; } @Override public <T> T acceptVisitor(ElementVisitor<T> visitor) { return visitor.visit(this); } /** * Sets the actual provider. * * @throws IllegalStateException if the delegate is already set */ public void initializeDelegate(Provider<T> delegate) { if (this.delegate != null) { throw new IllegalStateException("delegate already initialized"); } this.delegate = Objects.requireNonNull(delegate, "delegate"); } /** * Returns the looked up provider. The result is not valid until this lookup has been initialized, * which usually happens when the injector is created. The provider will throw an {@code * IllegalStateException} if you try to use it beforehand. */ public Provider<T> getProvider() { return new ProviderImpl<>(this); } }
ProviderImpl
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/requests/RequestContext.java
{ "start": 1656, "end": 8378 }
class ____ implements AuthorizableRequestContext { public final RequestHeader header; public final String connectionId; public final InetAddress clientAddress; public final Optional<Integer> clientPort; public final KafkaPrincipal principal; public final ListenerName listenerName; public final SecurityProtocol securityProtocol; public final ClientInformation clientInformation; public final boolean fromPrivilegedListener; public final Optional<KafkaPrincipalSerde> principalSerde; public RequestContext(RequestHeader header, String connectionId, InetAddress clientAddress, KafkaPrincipal principal, ListenerName listenerName, SecurityProtocol securityProtocol, ClientInformation clientInformation, boolean fromPrivilegedListener) { this(header, connectionId, clientAddress, Optional.empty(), principal, listenerName, securityProtocol, clientInformation, fromPrivilegedListener, Optional.empty()); } public RequestContext(RequestHeader header, String connectionId, InetAddress clientAddress, Optional<Integer> clientPort, KafkaPrincipal principal, ListenerName listenerName, SecurityProtocol securityProtocol, ClientInformation clientInformation, boolean fromPrivilegedListener) { this(header, connectionId, clientAddress, clientPort, principal, listenerName, securityProtocol, clientInformation, fromPrivilegedListener, Optional.empty()); } public RequestContext(RequestHeader header, String connectionId, InetAddress clientAddress, Optional<Integer> clientPort, KafkaPrincipal principal, ListenerName listenerName, SecurityProtocol securityProtocol, ClientInformation clientInformation, boolean fromPrivilegedListener, Optional<KafkaPrincipalSerde> principalSerde) { this.header = header; this.connectionId = connectionId; this.clientAddress = clientAddress; this.clientPort = clientPort; this.principal = principal; this.listenerName = listenerName; this.securityProtocol = securityProtocol; this.clientInformation = clientInformation; this.fromPrivilegedListener = fromPrivilegedListener; this.principalSerde = principalSerde; } public RequestAndSize parseRequest(ByteBuffer buffer) { if (isUnsupportedApiVersionsRequest()) { // Unsupported ApiVersion requests are treated as v0 requests and are not parsed ApiVersionsRequest apiVersionsRequest = new ApiVersionsRequest(new ApiVersionsRequestData(), (short) 0, header.apiVersion()); return new RequestAndSize(apiVersionsRequest, 0); } else { ApiKeys apiKey = header.apiKey(); try { short apiVersion = header.apiVersion(); return AbstractRequest.parseRequest(apiKey, apiVersion, new ByteBufferAccessor(buffer)); } catch (Throwable ex) { throw new InvalidRequestException("Error getting request for apiKey: " + apiKey + ", apiVersion: " + header.apiVersion() + ", connectionId: " + connectionId + ", listenerName: " + listenerName + ", principal: " + principal, ex); } } } /** * Build a {@link Send} for direct transmission of the provided response * over the network. */ public Send buildResponseSend(AbstractResponse body) { return body.toSend(header.toResponseHeader(), apiVersion()); } /** * Serialize a response into a {@link ByteBuffer}. This is used when the response * will be encapsulated in an {@link EnvelopeResponse}. The buffer will contain * both the serialized {@link ResponseHeader} as well as the bytes from the response. * There is no `size` prefix unlike the output from {@link #buildResponseSend(AbstractResponse)}. * * Note that envelope requests are reserved only for APIs which have set the * {@link ApiKeys#forwardable} flag. Notably the `Fetch` API cannot be forwarded, * so we do not lose the benefit of "zero copy" transfers from disk. */ public ByteBuffer buildResponseEnvelopePayload(AbstractResponse body) { return body.serializeWithHeader(header.toResponseHeader(), apiVersion()); } private boolean isUnsupportedApiVersionsRequest() { return header.apiKey() == API_VERSIONS && !header.isApiVersionSupported(); } public short apiVersion() { // Use v0 when serializing an unhandled ApiVersion response if (isUnsupportedApiVersionsRequest()) return 0; return header.apiVersion(); } public String connectionId() { return connectionId; } @Override public String listenerName() { return listenerName.value(); } @Override public SecurityProtocol securityProtocol() { return securityProtocol; } @Override public KafkaPrincipal principal() { return principal; } @Override public InetAddress clientAddress() { return clientAddress; } @Override public int requestType() { return header.apiKey().id; } @Override public int requestVersion() { return header.apiVersion(); } @Override public String clientId() { return header.clientId(); } @Override public int correlationId() { return header.correlationId(); } @Override public String toString() { return "RequestContext(" + "header=" + header + ", connectionId='" + connectionId + '\'' + ", clientAddress=" + clientAddress + ", principal=" + principal + ", listenerName=" + listenerName + ", securityProtocol=" + securityProtocol + ", clientInformation=" + clientInformation + ", fromPrivilegedListener=" + fromPrivilegedListener + ", principalSerde=" + principalSerde + ')'; } }
RequestContext
java
quarkusio__quarkus
extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/CollectionListOptions.java
{ "start": 290, "end": 1422 }
class ____ { private long maxTime; private TimeUnit maxTimeUnit; private Bson filter; /** * Sets the query filter to apply to the query. * * @param filter the filter, which may be null. * @return this */ public CollectionListOptions filter(Bson filter) { this.filter = filter; return this; } /** * Sets the maximum execution time on the server for this operation. * * @param maxTime the max time * @param timeUnit the time unit, which may not be null * @return this */ public CollectionListOptions maxTime(long maxTime, TimeUnit timeUnit) { this.maxTime = maxTime; this.maxTimeUnit = timeUnit; return this; } public <T> ListCollectionsPublisher<T> apply(ListCollectionsPublisher<T> stream) { ListCollectionsPublisher<T> publisher = stream; if (maxTime > 0) { publisher = publisher.maxTime(maxTime, maxTimeUnit); } if (filter != null) { publisher = publisher.filter(filter); } return publisher; } }
CollectionListOptions
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/dataformat/ThriftDataFormat.java
{ "start": 1495, "end": 3420 }
class ____ extends DataFormatDefinition implements ContentTypeHeaderAware { @XmlTransient private Object defaultInstance; @XmlAttribute private String instanceClass; @XmlAttribute @Metadata(enums = "binary,json,sjson", defaultValue = "binary") private String contentTypeFormat; @XmlAttribute @Metadata(javaType = "java.lang.Boolean", defaultValue = "true", description = "Whether the data format should set the Content-Type header with the type from the data format." + " For example application/xml for data formats marshalling to XML, or application/json for data formats marshalling to JSON") private String contentTypeHeader; public ThriftDataFormat() { super("thrift"); } protected ThriftDataFormat(ThriftDataFormat builder) { super(builder); this.defaultInstance = builder.defaultInstance; this.instanceClass = builder.instanceClass; this.contentTypeFormat = builder.contentTypeFormat; this.contentTypeHeader = builder.contentTypeHeader; } public ThriftDataFormat(String instanceClass) { this(); setInstanceClass(instanceClass); } public ThriftDataFormat(String instanceClass, String contentTypeFormat) { this(); setInstanceClass(instanceClass); setContentTypeFormat(contentTypeFormat); } private ThriftDataFormat(Builder builder) { this(); this.defaultInstance = builder.defaultInstance; this.instanceClass = builder.instanceClass; this.contentTypeFormat = builder.contentTypeFormat; this.contentTypeHeader = builder.contentTypeHeader; } @Override public ThriftDataFormat copyDefinition() { return new ThriftDataFormat(this); } public String getInstanceClass() { return instanceClass; } /** * Name of
ThriftDataFormat
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/EntityGraphEmbeddedAttributesTest.java
{ "start": 1303, "end": 3452 }
class ____ { private static final int TRACKED_PRODUCT_ID = 1; @Test void testFetchGraphFind(SessionFactoryScope scope) { executeTest( scope, HINT_SPEC_FETCH_GRAPH, true ); } @Test void testFetchGraphQuery(SessionFactoryScope scope) { executeTest( scope, HINT_SPEC_FETCH_GRAPH, false ); } @Test void testLoadGraphFind(SessionFactoryScope scope) { executeTest( scope, HINT_SPEC_LOAD_GRAPH, true ); } @Test void testLoadGraphQuery(SessionFactoryScope scope) { executeTest( scope, HINT_SPEC_LOAD_GRAPH, false ); } static void executeTest(SessionFactoryScope scope, String hint, boolean find) { scope.inTransaction( session -> { final EntityGraph<TrackedProduct> graph = createGraph( session ); final TrackedProduct product = find ? session.find( TrackedProduct.class, TRACKED_PRODUCT_ID, Map.of( hint, graph ) ) : session.createQuery( "from TrackedProduct where id = :id", TrackedProduct.class ).setParameter( "id", TRACKED_PRODUCT_ID ).setHint( hint, graph ).getSingleResult(); assertThat( Hibernate.isInitialized( product.tracking.creator ) ).isTrue(); assertThat( Hibernate.isInitialized( product.tracking.modifier ) ).isFalse(); } ); } static EntityGraph<TrackedProduct> createGraph(Session session) { final EntityGraph<TrackedProduct> graph = session.createEntityGraph( TrackedProduct.class ); graph.addSubgraph( "tracking" ).addAttributeNodes( "creator" ); return graph; } @BeforeAll void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { final UserForTracking creator = new UserForTracking( 1, "foo" ); session.persist( creator ); final UserForTracking modifier = new UserForTracking( 2, "bar" ); session.persist( modifier ); final TrackedProduct product = new TrackedProduct( TRACKED_PRODUCT_ID, new Tracking( creator, modifier ) ); session.persist( product ); } ); } @AfterAll public void tearDown(SessionFactoryScope scope) { scope.inTransaction( session -> session.getSessionFactory().getSchemaManager().truncateMappedObjects() ); } @Entity( name = "TrackedProduct" ) static
EntityGraphEmbeddedAttributesTest
java
apache__flink
flink-connectors/flink-hadoop-compatibility/src/main/java/org/apache/flink/api/java/hadoop/mapred/HadoopInputFormat.java
{ "start": 1470, "end": 2665 }
class ____<K, V> extends HadoopInputFormatBase<K, V, Tuple2<K, V>> implements ResultTypeQueryable<Tuple2<K, V>> { private static final long serialVersionUID = 1L; public HadoopInputFormat( org.apache.hadoop.mapred.InputFormat<K, V> mapredInputFormat, Class<K> key, Class<V> value, JobConf job) { super(mapredInputFormat, key, value, job); } public HadoopInputFormat( org.apache.hadoop.mapred.InputFormat<K, V> mapredInputFormat, Class<K> key, Class<V> value) { super(mapredInputFormat, key, value, new JobConf()); } @Override public Tuple2<K, V> nextRecord(Tuple2<K, V> record) throws IOException { if (!fetched) { fetchNext(); } if (!hasNext) { return null; } record.f0 = key; record.f1 = value; fetched = false; return record; } @Override public TypeInformation<Tuple2<K, V>> getProducedType() { return new TupleTypeInfo<>( TypeExtractor.createTypeInfo(keyClass), TypeExtractor.createTypeInfo(valueClass)); } }
HadoopInputFormat
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/math/CoshSerializationTests.java
{ "start": 537, "end": 743 }
class ____ extends AbstractUnaryScalarSerializationTests<Cosh> { @Override protected Cosh create(Source source, Expression child) { return new Cosh(source, child); } }
CoshSerializationTests
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/streaming/api/datastream/DataStreamWithSharedPartitionNodeITCase.java
{ "start": 2979, "end": 3316 }
class ____ implements Partitioner<Integer> { private int nextChannelToSendTo = -1; @Override public int partition(Integer key, int numPartitions) { nextChannelToSendTo = (nextChannelToSendTo + 1) % numPartitions; return nextChannelToSendTo; } } private static
TestPartitioner
java
google__error-prone
core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
{ "start": 34255, "end": 34626 }
class ____ { void test() { checkNotNull(1); } void verifyNotNull(int a) {} } """) .addOutputLines( "Test.java", """ import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Verify;
Test
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/transport/TransportActionProxy.java
{ "start": 1683, "end": 6250 }
class ____<T extends ProxyRequest<TransportRequest>> implements TransportRequestHandler<T> { private final TransportService service; private final String action; private final Function<TransportRequest, Writeable.Reader<? extends TransportResponse>> responseFunction; private final NamedWriteableRegistry namedWriteableRegistry; ProxyRequestHandler( TransportService service, String action, Function<TransportRequest, Writeable.Reader<? extends TransportResponse>> responseFunction, NamedWriteableRegistry namedWriteableRegistry ) { this.service = service; this.action = action; this.responseFunction = responseFunction; this.namedWriteableRegistry = namedWriteableRegistry; } @Override public void messageReceived(T request, TransportChannel channel, Task task) throws Exception { DiscoveryNode targetNode = request.targetNode; TransportRequest wrappedRequest = request.wrapped; assert assertConsistentTaskType(task, wrappedRequest); TaskId taskId = task.taskInfo(service.localNode.getId(), false).taskId(); wrappedRequest.setParentTask(taskId); service.sendRequest(targetNode, action, wrappedRequest, new TransportResponseHandler<>() { @Override public Executor executor() { return TransportResponseHandler.TRANSPORT_WORKER; } @Override public void handleResponse(TransportResponse response) { // This is a short term solution to ensure data node responses for batched search go back to the coordinating // node in the expected format when a proxy data node proxies the request to itself. The response would otherwise // be sent directly via DirectResponseChannel, skipping the read and write step that this handler normally performs. if (response instanceof BytesTransportResponse btr && btr.mustConvertResponseForVersion(channel.getVersion())) { try ( NamedWriteableAwareStreamInput in = new NamedWriteableAwareStreamInput( btr.streamInput(), namedWriteableRegistry ) ) { TransportResponse convertedResponse = responseFunction.apply(wrappedRequest).read(in); try { channel.sendResponse(convertedResponse); } finally { convertedResponse.decRef(); } } catch (IOException e) { throw new UncheckedIOException(e); } } else { channel.sendResponse(response); } } @Override public void handleException(TransportException exp) { channel.sendResponse(exp); } @Override public TransportResponse read(StreamInput in) throws IOException { if (in.getTransportVersion().equals(channel.getVersion()) && in.supportReadAllToReleasableBytesReference()) { return new BytesTransportResponse(in.readAllToReleasableBytesReference(), in.getTransportVersion()); } else { return responseFunction.apply(wrappedRequest).read(in); } } }); } private static boolean assertConsistentTaskType(Task proxyTask, TransportRequest wrapped) { final Task targetTask = wrapped.createTask(0, proxyTask.getType(), proxyTask.getAction(), TaskId.EMPTY_TASK_ID, Map.of()); assert targetTask instanceof CancellableTask == proxyTask instanceof CancellableTask : "Cancellable property of proxy action [" + proxyTask.getAction() + "] is configured inconsistently: " + "expected [" + (targetTask instanceof CancellableTask) + "] actual [" + (proxyTask instanceof CancellableTask) + "]"; return true; } } static
ProxyRequestHandler
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RCollectionReactive.java
{ "start": 899, "end": 3974 }
interface ____<V> extends RExpirableReactive { /** * Returns iterator over collection elements * * @return iterator */ Flux<V> iterator(); /** * Retains only the elements in this collection that are contained in the * specified collection (optional operation). * * @param c collection containing elements to be retained in this collection * @return <code>true</code> if this collection changed as a result of the call */ Mono<Boolean> retainAll(Collection<?> c); /** * Removes all of this collection's elements that are also contained in the * specified collection (optional operation). * * @param c collection containing elements to be removed from this collection * @return <code>true</code> if this collection changed as a result of the * call */ Mono<Boolean> removeAll(Collection<?> c); /** * Returns <code>true</code> if this collection contains encoded state of the specified element. * * @param o element whose presence in this collection is to be tested * @return <code>true</code> if this collection contains the specified * element and <code>false</code> otherwise */ Mono<Boolean> contains(V o); /** * Returns <code>true</code> if this collection contains all of the elements * in the specified collection. * * @param c collection to be checked for containment in this collection * @return <code>true</code> if this collection contains all of the elements * in the specified collection */ Mono<Boolean> containsAll(Collection<?> c); /** * Removes a single instance of the specified element from this * collection, if it is present (optional operation). * * @param o element to be removed from this collection, if present * @return <code>true</code> if an element was removed as a result of this call */ Mono<Boolean> remove(V o); /** * Returns number of elements in this collection. * * @return size of collection */ Mono<Integer> size(); /** * Adds element into this collection. * * @param e - element to add * @return <code>true</code> if an element was added * and <code>false</code> if it is already present */ Mono<Boolean> add(V e); /** * Adds all elements contained in the specified collection * * @param c - collection of elements to add * @return <code>true</code> if at least one element was added * and <code>false</code> if all elements are already present */ Mono<Boolean> addAll(Publisher<? extends V> c); /** * Adds all elements contained in the specified collection * * @param c - collection of elements to add * @return <code>true</code> if at least one element was added * and <code>false</code> if all elements are already present */ Mono<Boolean> addAll(Collection<? extends V> c); }
RCollectionReactive
java
google__guice
extensions/assistedinject/test/com/google/inject/assistedinject/FactoryProviderTest.java
{ "start": 11203, "end": 12404 }
class ____ implements Car { private final Set<String> features; private final Set<Integer> featureActivationSpeeds; private final Color color; @AssistedInject public DeLorean( Set<String> extraFeatures, Set<Integer> featureActivationSpeeds, @Assisted Color color) { this.features = extraFeatures; this.featureActivationSpeeds = featureActivationSpeeds; this.color = color; } } public void testTypeTokenProviderInjection() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Set<String>>() {}).toInstance(Collections.singleton("Datsun")); bind(ColoredCarFactory.class) .toProvider(FactoryProvider.newFactory(ColoredCarFactory.class, Z.class)); } }); ColoredCarFactory carFactory = injector.getInstance(ColoredCarFactory.class); Z orangeZ = (Z) carFactory.create(Color.ORANGE); assertEquals(Color.ORANGE, orangeZ.color); assertEquals("Datsun", orangeZ.manufacturersProvider.get().iterator().next()); } public static
DeLorean
java
playframework__playframework
core/play/src/main/java/play/libs/Files.java
{ "start": 8778, "end": 10422 }
class ____ implements TemporaryFile { private final play.api.libs.Files.TemporaryFile temporaryFile; private final TemporaryFileCreator temporaryFileCreator; public DelegateTemporaryFile(play.api.libs.Files.TemporaryFile temporaryFile) { this.temporaryFile = temporaryFile; this.temporaryFileCreator = new DelegateTemporaryFileCreator(temporaryFile.temporaryFileCreator()); } private DelegateTemporaryFile( play.api.libs.Files.TemporaryFile temporaryFile, TemporaryFileCreator temporaryFileCreator) { this.temporaryFile = temporaryFile; this.temporaryFileCreator = temporaryFileCreator; } @Override public Path path() { return temporaryFile.path(); } @Override public TemporaryFileCreator temporaryFileCreator() { return temporaryFileCreator; } @Override @Deprecated public Path moveFileTo(File to, boolean replace) { return moveTo(to, replace); } @Override public Path moveTo(File to, boolean replace) { return temporaryFile.moveTo(to, replace); } @Override public Path copyTo(Path destination, boolean replace) { return temporaryFile.copyTo(destination, replace); } @Override @Deprecated public Path atomicMoveFileWithFallback(File to) { return atomicMoveWithFallback(to); } @Override public Path atomicMoveWithFallback(File to) { return temporaryFile.atomicMoveWithFallback(to.toPath()); } } /** * A temporary file creator that uses the Scala play.api.libs.Files.SingletonTemporaryFileCreator *
DelegateTemporaryFile
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/util/MethodAssert.java
{ "start": 994, "end": 1824 }
class ____ extends AbstractObjectAssert<MethodAssert, Method> { public MethodAssert(@Nullable Method actual) { super(actual, MethodAssert.class); as("Method %s", actual); } /** * Verify that the actual method has the given {@linkplain Method#getName() * name}. * @param name the expected method name */ public MethodAssert hasName(String name) { isNotNull(); Assertions.assertThat(this.actual.getName()).as("Method name").isEqualTo(name); return this.myself; } /** * Verify that the actual method is declared in the given {@code type}. * @param type the expected declaring class */ public MethodAssert hasDeclaringClass(Class<?> type) { isNotNull(); Assertions.assertThat(this.actual.getDeclaringClass()) .as("Method declaring class").isEqualTo(type); return this.myself; } }
MethodAssert
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/observers/SafeObserverTest.java
{ "start": 5349, "end": 8419 }
class ____ extends RuntimeException { SafeObserverTestException(String message) { super(message); } } @Test public void actual() { Observer<Integer> actual = new DefaultObserver<Integer>() { @Override public void onNext(Integer t) { } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }; SafeObserver<Integer> observer = new SafeObserver<>(actual); assertSame(actual, observer.downstream); } @Test public void dispose() { TestObserver<Integer> to = new TestObserver<>(); SafeObserver<Integer> so = new SafeObserver<>(to); Disposable d = Disposable.empty(); so.onSubscribe(d); to.dispose(); assertTrue(d.isDisposed()); assertTrue(so.isDisposed()); } @Test @SuppressUndeliverable public void onNextAfterComplete() { TestObserver<Integer> to = new TestObserver<>(); SafeObserver<Integer> so = new SafeObserver<>(to); Disposable d = Disposable.empty(); so.onSubscribe(d); so.onComplete(); so.onNext(1); so.onError(new TestException()); so.onComplete(); to.assertResult(); } @Test public void onNextNull() { TestObserver<Integer> to = new TestObserver<>(); SafeObserver<Integer> so = new SafeObserver<>(to); Disposable d = Disposable.empty(); so.onSubscribe(d); so.onNext(null); to.assertFailure(NullPointerException.class); } @Test public void onNextWithoutOnSubscribe() { TestObserverEx<Integer> to = new TestObserverEx<>(); SafeObserver<Integer> so = new SafeObserver<>(to); so.onNext(1); to.assertFailureAndMessage(NullPointerException.class, "Subscription not set!"); } @Test public void onErrorWithoutOnSubscribe() { TestObserverEx<Integer> to = new TestObserverEx<>(); SafeObserver<Integer> so = new SafeObserver<>(to); so.onError(new TestException()); to.assertFailure(CompositeException.class); TestHelper.assertError(to, 0, TestException.class); TestHelper.assertError(to, 1, NullPointerException.class, "Subscription not set!"); } @Test public void onCompleteWithoutOnSubscribe() { TestObserverEx<Integer> to = new TestObserverEx<>(); SafeObserver<Integer> so = new SafeObserver<>(to); so.onComplete(); to.assertFailureAndMessage(NullPointerException.class, "Subscription not set!"); } @Test public void onNextNormal() { TestObserver<Integer> to = new TestObserver<>(); SafeObserver<Integer> so = new SafeObserver<>(to); Disposable d = Disposable.empty(); so.onSubscribe(d); so.onNext(1); so.onComplete(); to.assertResult(1); } static final
SafeObserverTestException
java
elastic__elasticsearch
plugins/discovery-ec2/src/main/java/org/elasticsearch/discovery/ec2/Ec2DiscoveryPlugin.java
{ "start": 1226, "end": 4920 }
class ____ extends Plugin implements DiscoveryPlugin, ReloadablePlugin { private static final Logger logger = LogManager.getLogger(Ec2DiscoveryPlugin.class); public static final String EC2_SEED_HOSTS_PROVIDER_NAME = "ec2"; static { SpecialPermission.check(); } private final Settings settings; // protected for testing protected final AwsEc2Service ec2Service; public Ec2DiscoveryPlugin(Settings settings) { this(settings, new AwsEc2ServiceImpl()); } @SuppressWarnings("this-escape") protected Ec2DiscoveryPlugin(Settings settings, AwsEc2ServiceImpl ec2Service) { this.settings = settings; this.ec2Service = ec2Service; // eagerly load client settings when secure settings are accessible reload(settings); } @Override public NetworkService.CustomNameResolver getCustomNameResolver(Settings _settings) { logger.debug("Register _ec2_, _ec2:xxx_ network names"); return new Ec2NameResolver(); } @Override public Map<String, Supplier<SeedHostsProvider>> getSeedHostProviders(TransportService transportService, NetworkService networkService) { return Map.of(EC2_SEED_HOSTS_PROVIDER_NAME, () -> new AwsEc2SeedHostsProvider(settings, transportService, ec2Service)); } @Override public List<Setting<?>> getSettings() { return Arrays.asList( // Register EC2 discovery settings: discovery.ec2 Ec2ClientSettings.ACCESS_KEY_SETTING, Ec2ClientSettings.SECRET_KEY_SETTING, Ec2ClientSettings.SESSION_TOKEN_SETTING, Ec2ClientSettings.ENDPOINT_SETTING, Ec2ClientSettings.PROTOCOL_SETTING, Ec2ClientSettings.PROXY_HOST_SETTING, Ec2ClientSettings.PROXY_PORT_SETTING, Ec2ClientSettings.PROXY_SCHEME_SETTING, Ec2ClientSettings.PROXY_USERNAME_SETTING, Ec2ClientSettings.PROXY_PASSWORD_SETTING, Ec2ClientSettings.READ_TIMEOUT_SETTING, AwsEc2Service.HOST_TYPE_SETTING, AwsEc2Service.ANY_GROUP_SETTING, AwsEc2Service.GROUPS_SETTING, AwsEc2Service.AVAILABILITY_ZONES_SETTING, AwsEc2Service.NODE_CACHE_TIME_SETTING, AwsEc2Service.TAG_SETTING, // Register cloud node settings: cloud.node AwsEc2Service.AUTO_ATTRIBUTE_SETTING ); } @Override public Settings additionalSettings() { return getAvailabilityZoneNodeAttributes(settings); } private static final String IMDS_AVAILABILITY_ZONE_PATH = "/latest/meta-data/placement/availability-zone"; // pkg private for testing static Settings getAvailabilityZoneNodeAttributes(Settings settings) { if (AwsEc2Service.AUTO_ATTRIBUTE_SETTING.get(settings)) { try { return Settings.builder() .put( Node.NODE_ATTRIBUTES.getKey() + "aws_availability_zone", AwsEc2Utils.getInstanceMetadata(IMDS_AVAILABILITY_ZONE_PATH) ) .build(); } catch (Exception e) { // this is lenient so the plugin does not fail when installed outside of ec2 logger.error("failed to get metadata for [placement/availability-zone]", e); } } return Settings.EMPTY; } @Override public void close() throws IOException { ec2Service.close(); } @Override public void reload(Settings settingsToLoad) { ec2Service.refreshAndClearCache(Ec2ClientSettings.getClientSettings(settingsToLoad)); } }
Ec2DiscoveryPlugin
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/dispatcher/cleanup/TestingCleanupRunnerFactory.java
{ "start": 1412, "end": 2010 }
class ____ extends TestingJobManagerRunnerFactory implements CleanupRunnerFactory { public TestingCleanupRunnerFactory() { super(0); } @Override public TestingJobManagerRunner create( JobResult jobResult, CheckpointRecoveryFactory checkpointRecoveryFactory, Configuration configuration, Executor cleanupExecutor) { try { return offerTestingJobManagerRunner(jobResult.getJobId()); } catch (Exception e) { throw new RuntimeException(e); } } }
TestingCleanupRunnerFactory
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java
{ "start": 6148, "end": 6311 }
class ____ extends BazTestCase { @Test void test() { } } /** * {@link DirtiesContext} is declared at the
ClassLevelDirtiesContextWithExhaustiveModeTestCase
java
apache__camel
components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpConsumer.java
{ "start": 1910, "end": 7249 }
class ____ extends RemoteFileConsumer<FTPFile> { private static final Logger LOG = LoggerFactory.getLogger(FtpConsumer.class); protected String endpointPath; private transient String ftpConsumerToString; public FtpConsumer(RemoteFileEndpoint<FTPFile> endpoint, Processor processor, RemoteFileOperations<FTPFile> fileOperations, GenericFileProcessStrategy processStrategy) { super(endpoint, processor, fileOperations, processStrategy); this.endpointPath = endpoint.getConfiguration().getDirectory(); } @Override protected FtpOperations getOperations() { return (FtpOperations) super.getOperations(); } @Override protected void doStart() throws Exception { // turn off scheduler first, so autoCreate is handled before scheduler // starts boolean startScheduler = isStartScheduler(); setStartScheduler(false); try { super.doStart(); if (endpoint.isAutoCreate() && hasStartingDirectory()) { String dir = endpoint.getConfiguration().getDirectory(); LOG.debug("Auto creating directory: {}", dir); try { connectIfNecessary(); operations.buildDirectory(dir, true); } catch (GenericFileOperationFailedException e) { // log a WARN as we want to start the consumer. LOG.warn( "Error auto creating directory: " + dir + " due " + e.getMessage() + ". This exception is ignored.", e); } } } finally { if (startScheduler) { setStartScheduler(true); startScheduler(); } } } @Override protected boolean pollDirectory(Exchange dynamic, String fileName, List<GenericFile<FTPFile>> fileList, int depth) { String currentDir = null; if (isStepwise()) { // must remember current dir so we stay in that directory after the // poll currentDir = operations.getCurrentDirectory(); } // strip trailing slash fileName = FileUtil.stripTrailingSeparator(fileName); boolean answer = doPollDirectory(dynamic, fileName, null, fileList, depth); if (currentDir != null) { operations.changeCurrentDirectory(currentDir); } return answer; } protected boolean pollSubDirectory( Exchange dynamic, String absolutePath, String dirName, List<GenericFile<FTPFile>> fileList, int depth) { boolean answer = doSafePollSubDirectory(dynamic, absolutePath, dirName, fileList, depth); // change back to parent directory when finished polling sub directory if (isStepwise()) { operations.changeToParentDirectory(); } return answer; } @Override protected boolean doPollDirectory( Exchange dynamic, String absolutePath, String dirName, List<GenericFile<FTPFile>> fileList, int depth) { LOG.trace("doPollDirectory from absolutePath: {}, dirName: {}", absolutePath, dirName); depth++; // remove trailing / dirName = FileUtil.stripTrailingSeparator(dirName); // compute dir depending on stepwise is enabled or not final String dir = computeDir(absolutePath, dirName); final FTPFile[] files = getFtpFiles(dir); if (files == null || files.length == 0) { // no files in this directory to poll LOG.trace("No files found in directory: {}", dir); return true; } // we found some files LOG.trace("Found {} files in directory: {}", files.length, dir); if (getEndpoint().isPreSort()) { Arrays.sort(files, Comparator.comparing(FTPFile::getName)); } for (FTPFile file : files) { if (handleFtpEntries(dynamic, absolutePath, fileList, depth, files, file)) { return false; } } return true; } private boolean handleFtpEntries( Exchange dynamic, String absolutePath, List<GenericFile<FTPFile>> fileList, int depth, FTPFile[] files, FTPFile file) { if (LOG.isTraceEnabled()) { LOG.trace("FtpFile[name={}, dir={}, file={}]", file.getName(), file.isDirectory(), file.isFile()); } // check if we can continue polling in files if (!canPollMoreFiles(fileList)) { return true; } if (file.isDirectory()) { if (handleDirectory(dynamic, absolutePath, fileList, depth, files, file)) { return true; } } else if (file.isFile()) { handleFile(dynamic, absolutePath, fileList, depth, files, file); } else { LOG.debug("Ignoring unsupported remote file type: {}", file); } return false; } private boolean handleDirectory( Exchange dynamic, String absolutePath, List<GenericFile<FTPFile>> fileList, int depth, FTPFile[] files, FTPFile file) { if (endpoint.isRecursive() && depth < endpoint.getMaxDepth()) { // calculate the absolute file path using util
FtpConsumer
java
elastic__elasticsearch
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/IpinfoIpDataLookups.java
{ "start": 17006, "end": 19261 }
class ____ extends AbstractBase<PrivacyDetectionResult> { PrivacyDetection(Set<Database.Property> properties) { super(properties, PrivacyDetectionResult.class); } @Override protected Map<String, Object> transform(final Result<PrivacyDetectionResult> result) { PrivacyDetectionResult response = result.result(); Map<String, Object> data = new HashMap<>(); for (Database.Property property : this.properties) { switch (property) { case IP -> data.put("ip", result.ip()); case HOSTING -> { if (response.hosting != null) { data.put("hosting", response.hosting); } } case TOR -> { if (response.tor != null) { data.put("tor", response.tor); } } case PROXY -> { if (response.proxy != null) { data.put("proxy", response.proxy); } } case RELAY -> { if (response.relay != null) { data.put("relay", response.relay); } } case VPN -> { if (response.vpn != null) { data.put("vpn", response.vpn); } } case SERVICE -> { if (Strings.hasText(response.service)) { data.put("service", response.service); } } } } return data; } } /** * The {@link IpinfoIpDataLookups.AbstractBase} is an abstract base implementation of {@link IpDataLookup} that * provides common functionality for getting a {@link IpDataLookup.Result} that wraps a record from a {@link IpDatabase}. * * @param <RESPONSE> the record type that will be wrapped and returned */ private abstract static
PrivacyDetection
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContextBootstrapper.java
{ "start": 1012, "end": 1307 }
class ____ extends AbstractTestContextBootstrapper { /** * Returns {@link DelegatingSmartContextLoader}. */ @Override protected Class<? extends ContextLoader> getDefaultContextLoaderClass(Class<?> testClass) { return DelegatingSmartContextLoader.class; } }
DefaultTestContextBootstrapper
java
apache__camel
core/camel-support/src/main/java/org/apache/camel/support/LifecycleStrategySupport.java
{ "start": 1846, "end": 9871 }
class ____ implements LifecycleStrategy { private static final Logger LOG = LoggerFactory.getLogger(LifecycleStrategySupport.class); // ******************************* // // Helpers (adapters) // // ******************************** public static LifecycleStrategy adapt(OnCamelContextEvent handler) { return new LifecycleStrategySupport() { @Override public void onContextInitializing(CamelContext context) throws VetoCamelContextStartException { if (handler instanceof OnCamelContextInitializing onCamelContextInitializing) { onCamelContextInitializing.onContextInitializing(context); } } @Override public void onContextInitialized(CamelContext context) throws VetoCamelContextStartException { if (handler instanceof OnCamelContextInitialized onCamelContextInitialized) { onCamelContextInitialized.onContextInitialized(context); } } @Override public void onContextStarting(CamelContext context) throws VetoCamelContextStartException { if (handler instanceof OnCamelContextStarting onCamelContextStarting) { onCamelContextStarting.onContextStarting(context); } } @Override public void onContextStarted(CamelContext context) { if (handler instanceof OnCamelContextStarted onCamelContextStarted) { onCamelContextStarted.onContextStarted(context); } } @Override public void onContextStopping(CamelContext context) { if (handler instanceof OnCamelContextStopping onCamelContextStopping) { onCamelContextStopping.onContextStopping(context); } } @Override public void onContextStopped(CamelContext context) { if (handler instanceof OnCamelContextStopped onCamelContextStopped) { onCamelContextStopped.onContextStopped(context); } } }; } public static LifecycleStrategy adapt(OnCamelContextInitializing handler) { return new LifecycleStrategySupport() { @Override public void onContextInitializing(CamelContext context) throws VetoCamelContextStartException { handler.onContextInitializing(context); } }; } public static LifecycleStrategy adapt(OnCamelContextInitialized handler) { return new LifecycleStrategySupport() { @Override public void onContextInitialized(CamelContext context) throws VetoCamelContextStartException { handler.onContextInitialized(context); } }; } public static LifecycleStrategy adapt(OnCamelContextStarting handler) { return new LifecycleStrategySupport() { @Override public void onContextStarting(CamelContext context) throws VetoCamelContextStartException { handler.onContextStarting(context); } }; } public static LifecycleStrategy adapt(OnCamelContextStarted handler) { return new LifecycleStrategySupport() { @Override public void onContextStarted(CamelContext context) { handler.onContextStarted(context); } }; } public static LifecycleStrategy adapt(OnCamelContextStopping handler) { return new LifecycleStrategySupport() { @Override public void onContextStopping(CamelContext context) { handler.onContextStopping(context); } }; } public static LifecycleStrategy adapt(OnCamelContextStopped handler) { return new LifecycleStrategySupport() { @Override public void onContextStopped(CamelContext context) { handler.onContextStopped(context); } }; } // ******************************* // // Helpers (functional) // // ******************************** public static OnCamelContextInitializing onCamelContextInitializing(Consumer<CamelContext> consumer) { return consumer::accept; } public static OnCamelContextInitialized onCamelContextInitialized(Consumer<CamelContext> consumer) { return consumer::accept; } public static OnCamelContextStarting onCamelContextStarting(Consumer<CamelContext> consumer) { return consumer::accept; } public static OnCamelContextStarted onCamelContextStarted(Consumer<CamelContext> consumer) { return consumer::accept; } public static OnCamelContextStopping onCamelContextStopping(Consumer<CamelContext> consumer) { return consumer::accept; } public static OnCamelContextStopped onCamelContextStopped(Consumer<CamelContext> consumer) { return consumer::accept; } // ******************************* // // Helpers // // ******************************** @Override public void onComponentAdd(String name, Component component) { // noop } @Override public void onComponentRemove(String name, Component component) { // noop } @Override public void onEndpointAdd(Endpoint endpoint) { // noop } @Override public void onEndpointRemove(Endpoint endpoint) { // noop } @Override public void onServiceAdd(CamelContext context, Service service, org.apache.camel.Route route) { // noop } @Override public void onServiceRemove(CamelContext context, Service service, org.apache.camel.Route route) { // noop } @Override public void onRoutesAdd(Collection<org.apache.camel.Route> routes) { // noop } @Override public void onRoutesRemove(Collection<org.apache.camel.Route> routes) { // noop } @Override public void onRouteContextCreate(Route route) { // noop } @Override public void onThreadPoolAdd( CamelContext camelContext, ThreadPoolExecutor threadPool, String id, String sourceId, String routeId, String threadPoolProfileId) { // noop } @Override public void onThreadPoolRemove(CamelContext camelContext, ThreadPoolExecutor threadPool) { // noop } protected static void doAutoWire(String name, String kind, Object target, CamelContext camelContext) { PropertyConfigurer pc = PluginHelper.getConfigurerResolver(camelContext) .resolvePropertyConfigurer(name + "-" + kind, camelContext); if (pc instanceof PropertyConfigurerGetter getter) { String[] names = getter.getAutowiredNames(); if (names != null) { for (String option : names) { // is there already a configured value? Object value = getter.getOptionValue(target, option, true); if (value == null) { Class<?> type = getter.getOptionType(option, true); if (type != null) { value = camelContext.getRegistry().findSingleByType(type); } if (value != null) { boolean hit = pc.configure(camelContext, target, option, value, true); if (hit) { LOG.info( "Autowired property: {} on {}: {} as exactly one instance of type: {} ({}) found in the registry", option, kind, name, type.getName(), value.getClass().getName()); } } } } } } } }
LifecycleStrategySupport
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/format/MapFormatShapeTest.java
{ "start": 884, "end": 1027 }
class ____ extends Map476Base { } @JsonPropertyOrder({ "a", "b", "c" }) @JsonInclude(JsonInclude.Include.NON_NULL) static
Map476AsPOJO
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/type/AbstractAnnotationMetadataTests.java
{ "start": 14208, "end": 14345 }
class ____ { } @Retention(RetentionPolicy.RUNTIME) @AnnotationAttributes(name = "m1", size = 1) public @
WithMetaAnnotationAttributes
java
quarkusio__quarkus
extensions/hibernate-validator/runtime/src/main/java/io/quarkus/hibernate/validator/runtime/jaxrs/JaxrsEndPointValidated.java
{ "start": 318, "end": 513 }
class ____ indicate a JAX-RS end point should be validated. */ @Inherited @InterceptorBinding @Retention(value = RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) public @
to
java
spring-projects__spring-boot
module/spring-boot-couchbase/src/main/java/org/springframework/boot/couchbase/autoconfigure/CouchbaseAutoConfiguration.java
{ "start": 3964, "end": 8719 }
class ____ { private final ResourceLoader resourceLoader; private final CouchbaseProperties properties; CouchbaseAutoConfiguration(ResourceLoader resourceLoader, CouchbaseProperties properties) { this.resourceLoader = ApplicationResourceLoader.get(resourceLoader); this.properties = properties; } @Bean @ConditionalOnMissingBean(CouchbaseConnectionDetails.class) PropertiesCouchbaseConnectionDetails couchbaseConnectionDetails(ObjectProvider<SslBundles> sslBundles) { return new PropertiesCouchbaseConnectionDetails(this.properties, sslBundles.getIfAvailable()); } @Bean @ConditionalOnMissingBean ClusterEnvironment couchbaseClusterEnvironment(ObjectProvider<ClusterEnvironmentBuilderCustomizer> customizers, CouchbaseConnectionDetails connectionDetails) { Builder builder = initializeEnvironmentBuilder(connectionDetails); customizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder.build(); } @Bean @ConditionalOnMissingBean Authenticator couchbaseAuthenticator(CouchbaseConnectionDetails connectionDetails) throws IOException { if (connectionDetails.getUsername() != null && connectionDetails.getPassword() != null) { return PasswordAuthenticator.create(connectionDetails.getUsername(), connectionDetails.getPassword()); } Pem pem = this.properties.getAuthentication().getPem(); if (pem.getCertificates() != null) { PemSslStoreDetails details = new PemSslStoreDetails(null, pem.getCertificates(), pem.getPrivateKey()); PemSslStore store = PemSslStore.load(details); Assert.state(store != null, "Unable to load key and certificates"); PrivateKey key = store.privateKey(); List<X509Certificate> certificates = store.certificates(); Assert.state(key != null, "No key found"); Assert.state(certificates != null, "No certificates found"); return CertificateAuthenticator.fromKey(key, pem.getPrivateKeyPassword(), certificates); } Jks jks = this.properties.getAuthentication().getJks(); if (jks.getLocation() != null) { Resource resource = this.resourceLoader.getResource(jks.getLocation()); String keystorePassword = jks.getPassword(); try (InputStream inputStream = resource.getInputStream()) { KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType()); store.load(inputStream, (keystorePassword != null) ? keystorePassword.toCharArray() : null); return CertificateAuthenticator.fromKeyStore(store, keystorePassword); } catch (GeneralSecurityException ex) { throw new IllegalStateException("Error reading Couchbase certificate store", ex); } } throw new IllegalStateException("Couchbase authentication requires username and password, or certificates"); } @Bean(destroyMethod = "disconnect") @ConditionalOnMissingBean Cluster couchbaseCluster(ClusterEnvironment couchbaseClusterEnvironment, Authenticator authenticator, CouchbaseConnectionDetails connectionDetails) { ClusterOptions options = ClusterOptions.clusterOptions(authenticator).environment(couchbaseClusterEnvironment); return Cluster.connect(connectionDetails.getConnectionString(), options); } private ClusterEnvironment.Builder initializeEnvironmentBuilder(CouchbaseConnectionDetails connectionDetails) { ClusterEnvironment.Builder builder = ClusterEnvironment.builder(); Timeouts timeouts = this.properties.getEnv().getTimeouts(); builder.timeoutConfig((config) -> config.kvTimeout(timeouts.getKeyValue()) .analyticsTimeout(timeouts.getAnalytics()) .kvDurableTimeout(timeouts.getKeyValueDurable()) .queryTimeout(timeouts.getQuery()) .viewTimeout(timeouts.getView()) .searchTimeout(timeouts.getSearch()) .managementTimeout(timeouts.getManagement()) .connectTimeout(timeouts.getConnect()) .disconnectTimeout(timeouts.getDisconnect())); CouchbaseProperties.Io io = this.properties.getEnv().getIo(); builder.ioConfig((config) -> config.maxHttpConnections(io.getMaxEndpoints()) .numKvConnections(io.getMinEndpoints()) .idleHttpConnectionTimeout(io.getIdleHttpConnectionTimeout())); SslBundle sslBundle = connectionDetails.getSslBundle(); if (sslBundle != null) { configureSsl(builder, sslBundle); } return builder; } private void configureSsl(Builder builder, SslBundle sslBundle) { Assert.state(!sslBundle.getOptions().isSpecified(), "SSL Options cannot be specified with Couchbase"); builder.securityConfig((config) -> { config.enableTls(true); TrustManagerFactory trustManagerFactory = sslBundle.getManagers().getTrustManagerFactory(); if (trustManagerFactory != null) { config.trustManagerFactory(trustManagerFactory); } }); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ObjectMapper.class) static
CouchbaseAutoConfiguration
java
apache__camel
components/camel-jmx/src/test/java/org/apache/camel/component/jmx/CamelJmxConsumerObserveAttributeMatchStringDifferTest.java
{ "start": 1203, "end": 3269 }
class ____ extends CamelTestSupport { @Override protected boolean useJmx() { return true; } @Test public void testJmxConsumer() throws Exception { getMockEndpoint("mock:result").expectedMinimumMessageCount(1); getMockEndpoint("mock:result").message(0).body().contains("<newValue>false</newValue>"); getMockEndpoint("mock:result").message(0).body().contains("<attributeName>Tracing</attributeName>"); // change the attribute so JMX triggers but should be filtered ManagedRouteMBean mr = context.getCamelContextExtension().getContextPlugin(ManagedCamelContext.class).getManagedRoute("foo"); mr.setStatisticsEnabled(true); // change the attribute so JMX triggers mr = context.getCamelContextExtension().getContextPlugin(ManagedCamelContext.class).getManagedRoute("foo"); mr.setTracing(true); // change the attribute so JMX triggers mr = context.getCamelContextExtension().getContextPlugin(ManagedCamelContext.class).getManagedRoute("foo"); mr.setTracing(false); // change the attribute so JMX triggers mr = context.getCamelContextExtension().getContextPlugin(ManagedCamelContext.class).getManagedRoute("foo"); mr.setTracing(true); MockEndpoint.assertIsSatisfied(context); } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { String id = getContext().getName(); fromF("jmx:platform?objectDomain=org.apache.camel&key.context=%s&key.type=routes&key.name=\"foo\"&observedAttribute=Tracing&stringToCompare=true&notifyDiffer=true", id) .routeId("jmxRoute") .to("log:jmx") .to("mock:result"); from("direct:foo").routeId("foo").to("log:foo", "mock:foo"); } }; } }
CamelJmxConsumerObserveAttributeMatchStringDifferTest