language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/expressions/EvaluatedExpressionConstants.java
{ "start": 761, "end": 1105 }
class ____ { /** * Evaluated expression prefix. */ public static final String EXPRESSION_PREFIX = "#{"; /** * RegEx pattern used to determine whether string value in * annotation includes evaluated expression. */ public static final String EXPRESSION_PATTERN = ".*#\\{.*}.*"; }
EvaluatedExpressionConstants
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceRegistryTest.java
{ "start": 5812, "end": 6157 }
class ____ implements StandardServiceInitiator<FakeService> { @Override public Class<FakeService> getServiceInitiated() { return FakeService.class; } @Override public FakeService initiateService(Map<String, Object> configurationValues, ServiceRegistryImplementor registry) { return null; } } public static
NullServiceInitiator
java
apache__kafka
streams/upgrade-system-tests-35/src/test/java/org/apache/kafka/streams/tests/SmokeTestUtil.java
{ "start": 1483, "end": 4000 }
class ____ { static final int END = Integer.MAX_VALUE; static ProcessorSupplier<Object, Object, Void, Void> printProcessorSupplier(final String topic) { return printProcessorSupplier(topic, ""); } static ProcessorSupplier<Object, Object, Void, Void> printProcessorSupplier(final String topic, final String name) { return () -> new ContextualProcessor<Object, Object, Void, Void>() { private int numRecordsProcessed = 0; private long smallestOffset = Long.MAX_VALUE; private long largestOffset = Long.MIN_VALUE; @Override public void init(final ProcessorContext<Void, Void> context) { super.init(context); System.out.println("[3.5] initializing processor: topic=" + topic + " taskId=" + context.taskId()); System.out.flush(); numRecordsProcessed = 0; smallestOffset = Long.MAX_VALUE; largestOffset = Long.MIN_VALUE; } @Override public void process(final Record<Object, Object> record) { numRecordsProcessed++; if (numRecordsProcessed % 100 == 0) { System.out.printf("%s: %s%n", name, Instant.now()); System.out.println("processed " + numRecordsProcessed + " records from topic=" + topic); } context().recordMetadata().ifPresent(recordMetadata -> { if (smallestOffset > recordMetadata.offset()) { smallestOffset = recordMetadata.offset(); } if (largestOffset < recordMetadata.offset()) { largestOffset = recordMetadata.offset(); } }); } @Override public void close() { System.out.printf("Close processor for task %s%n", context().taskId()); System.out.println("processed " + numRecordsProcessed + " records"); final long processed; if (largestOffset >= smallestOffset) { processed = 1L + largestOffset - smallestOffset; } else { processed = 0L; } System.out.println("offset " + smallestOffset + " to " + largestOffset + " -> processed " + processed); System.out.flush(); } }; } public static final
SmokeTestUtil
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/google/MultimapContainsKeyTester.java
{ "start": 1647, "end": 3150 }
class ____<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> { @CollectionSize.Require(absent = ZERO) public void testContainsKeyYes() { assertTrue(multimap().containsKey(k0())); } public void testContainsKeyNo() { assertFalse(multimap().containsKey(k3())); } public void testContainsKeysFromKeySet() { for (K k : multimap().keySet()) { assertTrue(multimap().containsKey(k)); } } public void testContainsKeyAgreesWithGet() { for (K k : sampleKeys()) { assertEquals(!multimap().get(k).isEmpty(), multimap().containsKey(k)); } } public void testContainsKeyAgreesWithAsMap() { for (K k : sampleKeys()) { assertEquals(multimap().containsKey(k), multimap().asMap().containsKey(k)); } } public void testContainsKeyAgreesWithKeySet() { for (K k : sampleKeys()) { assertEquals(multimap().containsKey(k), multimap().keySet().contains(k)); } } @MapFeature.Require(ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testContainsKeyNullPresent() { initMultimapWithNullKey(); assertTrue(multimap().containsKey(null)); } @MapFeature.Require(ALLOWS_NULL_KEY_QUERIES) public void testContainsKeyNullAbsent() { assertFalse(multimap().containsKey(null)); } @MapFeature.Require(absent = ALLOWS_NULL_KEY_QUERIES) public void testContainsKeyNullDisallowed() { assertThrows(NullPointerException.class, () -> multimap().containsKey(null)); } }
MultimapContainsKeyTester
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreFactory.java
{ "start": 2744, "end": 4965 }
class ____<T extends StateStore> implements StoreBuilder<T>, ConfigurableStore { private final StoreFactory storeFactory; public FactoryWrappingStoreBuilder(final StoreFactory storeFactory) { this.storeFactory = storeFactory; } public StoreFactory storeFactory() { return storeFactory; } public void configure(final StreamsConfig config) { storeFactory.configure(config); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final FactoryWrappingStoreBuilder<?> that = (FactoryWrappingStoreBuilder<?>) o; return storeFactory.isCompatibleWith(that.storeFactory); } @Override public int hashCode() { return storeFactory.hashCode(); } @Override public StoreBuilder<T> withCachingEnabled() { throw new IllegalStateException("Should not try to modify StoreBuilder wrapper"); } @Override public StoreBuilder<T> withCachingDisabled() { storeFactory.withCachingDisabled(); return this; } @Override public StoreBuilder<T> withLoggingEnabled(final Map<String, String> config) { throw new IllegalStateException("Should not try to modify StoreBuilder wrapper"); } @Override public StoreBuilder<T> withLoggingDisabled() { storeFactory.withLoggingDisabled(); return this; } @SuppressWarnings("unchecked") @Override public T build() { return (T) storeFactory.builder().build(); } @Override public Map<String, String> logConfig() { return storeFactory.logConfig(); } @Override public boolean loggingEnabled() { return storeFactory.loggingEnabled(); } @Override public String name() { return storeFactory.storeName(); } } }
FactoryWrappingStoreBuilder
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/WorkdayComponentBuilderFactory.java
{ "start": 1831, "end": 3937 }
interface ____ extends ComponentBuilder<WorkdayComponent> { /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default WorkdayComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default WorkdayComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } }
WorkdayComponentBuilder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/MappedSuperclassTest.java
{ "start": 751, "end": 1746 }
class ____ { @AfterEach void tearDown(SessionFactoryScope factoryScope) { factoryScope.dropData(); } @Test public void test(SessionFactoryScope factoryScope) { factoryScope.inTransaction( entityManager -> { DebitAccount debitAccount = new DebitAccount(); debitAccount.setId(1L); debitAccount.setOwner("John Doe"); debitAccount.setBalance(BigDecimal.valueOf(100)); debitAccount.setInterestRate(BigDecimal.valueOf(1.5d)); debitAccount.setOverdraftFee(BigDecimal.valueOf(25)); CreditAccount creditAccount = new CreditAccount(); creditAccount.setId(1L); creditAccount.setOwner("John Doe"); creditAccount.setBalance(BigDecimal.valueOf(1000)); creditAccount.setInterestRate(BigDecimal.valueOf(1.9d)); creditAccount.setCreditLimit(BigDecimal.valueOf(5000)); entityManager.persist(debitAccount); entityManager.persist(creditAccount); }); } //tag::entity-inheritance-mapped-superclass-example[] @MappedSuperclass public static
MappedSuperclassTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/JdbcTypeRegistrationsAnnotation.java
{ "start": 691, "end": 1943 }
class ____ implements JdbcTypeRegistrations, RepeatableContainer<org.hibernate.annotations.JdbcTypeRegistration> { private org.hibernate.annotations.JdbcTypeRegistration[] value; /** * Used in creating dynamic annotation instances (e.g. from XML) */ public JdbcTypeRegistrationsAnnotation(ModelsContext modelContext) { } /** * Used in creating annotation instances from JDK variant */ public JdbcTypeRegistrationsAnnotation(JdbcTypeRegistrations annotation, ModelsContext modelContext) { this.value = extractJdkValue( annotation, HibernateAnnotations.JDBC_TYPE_REGISTRATIONS, "value", modelContext ); } /** * Used in creating annotation instances from Jandex variant */ public JdbcTypeRegistrationsAnnotation( Map<String, Object> attributeValues, ModelsContext modelContext) { this.value = (org.hibernate.annotations.JdbcTypeRegistration[]) attributeValues.get( "value" ); } @Override public Class<? extends Annotation> annotationType() { return JdbcTypeRegistrations.class; } @Override public org.hibernate.annotations.JdbcTypeRegistration[] value() { return value; } public void value(org.hibernate.annotations.JdbcTypeRegistration[] value) { this.value = value; } }
JdbcTypeRegistrationsAnnotation
java
spring-projects__spring-security
acl/src/test/java/org/springframework/security/acls/domain/AuditLoggerTests.java
{ "start": 1237, "end": 2845 }
class ____ { private PrintStream console; private ByteArrayOutputStream bytes = new ByteArrayOutputStream(); private ConsoleAuditLogger logger; private AuditableAccessControlEntry ace; @BeforeEach public void setUp() { this.logger = new ConsoleAuditLogger(); this.ace = mock(AuditableAccessControlEntry.class); this.console = System.out; System.setOut(new PrintStream(this.bytes)); } @AfterEach public void tearDown() { System.setOut(this.console); this.bytes.reset(); } @Test public void nonAuditableAceIsIgnored() { AccessControlEntry ace = mock(AccessControlEntry.class); this.logger.logIfNeeded(true, ace); assertThat(this.bytes.size()).isZero(); } @Test public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() { given(this.ace.isAuditSuccess()).willReturn(false); this.logger.logIfNeeded(true, this.ace); assertThat(this.bytes.size()).isZero(); } @Test public void successIsLoggedIfAceRequiresSuccessAudit() { given(this.ace.isAuditSuccess()).willReturn(true); this.logger.logIfNeeded(true, this.ace); assertThat(this.bytes.toString()).startsWith("GRANTED due to ACE"); } @Test public void failureIsntLoggedIfAceDoesntRequireFailureAudit() { given(this.ace.isAuditFailure()).willReturn(false); this.logger.logIfNeeded(false, this.ace); assertThat(this.bytes.size()).isZero(); } @Test public void failureIsLoggedIfAceRequiresFailureAudit() { given(this.ace.isAuditFailure()).willReturn(true); this.logger.logIfNeeded(false, this.ace); assertThat(this.bytes.toString()).startsWith("DENIED due to ACE"); } }
AuditLoggerTests
java
google__dagger
javatests/dagger/internal/codegen/ComponentRequirementFieldTest.java
{ "start": 2173, "end": 3045 }
interface ____ {", " @BindsInstance Builder i(int i);", " @BindsInstance Builder list(List<String> list);", " TestComponent build();", " }", "}"); CompilerTests.daggerCompiler(component) .withProcessingOptions(compilerMode.processorOptions()) .compile( subject -> { subject.hasErrorCount(0); subject.generatedSource(goldenFileRule.goldenSource("test/DaggerTestComponent")); }); } @Test public void testBindsNullableInstance() throws Exception { Source component = CompilerTests.javaSource( "test.TestComponent", "package test;", "", "import dagger.BindsInstance;", "import dagger.Component;", "", "@Component", "
Builder
java
grpc__grpc-java
android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/XdsUpdateClientConfigureServiceGrpc.java
{ "start": 6344, "end": 6849 }
class ____ implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return XdsUpdateClientConfigureServiceGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service XdsUpdateClientConfigureService. * <pre> * A service to dynamically update the configuration of an xDS test client. * </pre> */ public static final
XdsUpdateClientConfigureServiceImplBase
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/Querier.java
{ "start": 19929, "end": 22806 }
class ____ extends BaseAggActionListener { private final boolean isPivot; CompositeActionListener( ActionListener<Page> listener, Client client, SqlConfiguration cfg, List<Attribute> output, QueryContainer query, SearchRequest request ) { super(listener, client, cfg, output, query, request); isPivot = query.fields().stream().anyMatch(t -> t.extraction() instanceof PivotColumnRef); } @Override protected void handleResponse(SearchResponse response, ActionListener<Page> listener) { CompositeAggregationBuilder aggregation = CompositeAggCursor.getCompositeBuilder(request.source()); boolean mightProducePartialPages = CompositeAggCursor.couldProducePartialPages(aggregation); Supplier<CompositeAggRowSet> makeRowSet = isPivot ? () -> new PivotRowSet( schema, initBucketExtractors(response), mask, response, aggregation.size(), query.sortingColumns().isEmpty() ? query.limit() : -1, null, mightProducePartialPages ) : () -> new SchemaCompositeAggRowSet( schema, initBucketExtractors(response), mask, response, aggregation.size(), query.sortingColumns().isEmpty() ? query.limit() : -1, mightProducePartialPages ); BiFunction<SearchSourceBuilder, CompositeAggRowSet, CompositeAggCursor> makeCursor = isPivot ? (q, r) -> { Map<String, Object> lastAfterKey = r instanceof PivotRowSet ? ((PivotRowSet) r).lastAfterKey() : null; return new PivotCursor( lastAfterKey, q, r.extractors(), r.mask(), r.remainingData(), query.shouldIncludeFrozen(), request.indices() ); } : (q, r) -> new CompositeAggCursor( q, r.extractors(), r.mask(), r.remainingData, query.shouldIncludeFrozen(), request.indices() ); CompositeAggCursor.handle( client, response, request.source(), makeRowSet, makeCursor, () -> client.search(request, this), listener, mightProducePartialPages ); } } abstract static
CompositeActionListener
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/record/MemoryRecordsTest.java
{ "start": 3845, "end": 4729 }
class ____ implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Arguments> arguments = new ArrayList<>(); for (long firstOffset : asList(0L, 57L)) for (CompressionType type: CompressionType.values()) { List<Byte> magics = type == CompressionType.ZSTD ? Collections.singletonList(RecordBatch.MAGIC_VALUE_V2) : asList(RecordBatch.MAGIC_VALUE_V0, RecordBatch.MAGIC_VALUE_V1, RecordBatch.MAGIC_VALUE_V2); for (byte magic : magics) arguments.add(Arguments.of(new Args(magic, firstOffset, Compression.of(type).build()))); } return arguments.stream(); } } private static
MemoryRecordsArgumentsProvider
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/Aws2EventbridgeComponentBuilderFactory.java
{ "start": 1928, "end": 16726 }
interface ____ extends ComponentBuilder<EventbridgeComponent> { /** * Component configuration. * * The option is a: * &lt;code&gt;org.apache.camel.component.aws2.eventbridge.EventbridgeConfiguration&lt;/code&gt; type. * * Group: producer * * @param configuration the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder configuration(org.apache.camel.component.aws2.eventbridge.EventbridgeConfiguration configuration) { doSetProperty("configuration", configuration); return this; } /** * EventPattern File. * * This option can also be loaded from an existing file, by prefixing * with file: or classpath: followed by the location of the file. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param eventPatternFile the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder eventPatternFile(java.lang.String eventPatternFile) { doSetProperty("eventPatternFile", eventPatternFile); 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 is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * The operation to perform. * * The option is a: * &lt;code&gt;org.apache.camel.component.aws2.eventbridge.EventbridgeOperations&lt;/code&gt; type. * * Default: putRule * Group: producer * * @param operation the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder operation(org.apache.camel.component.aws2.eventbridge.EventbridgeOperations operation) { doSetProperty("operation", operation); return this; } /** * Set the need for overriding the endpoint. This option needs to be * used in combination with the uriEndpointOverride option. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param overrideEndpoint the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder overrideEndpoint(boolean overrideEndpoint) { doSetProperty("overrideEndpoint", overrideEndpoint); return this; } /** * If we want to use a POJO request as body or not. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param pojoRequest the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder pojoRequest(boolean pojoRequest) { doSetProperty("pojoRequest", pojoRequest); return this; } /** * The region in which the Eventbridge client needs to work. When using * this parameter, the configuration will expect the lowercase name of * the region (for example, ap-east-1) You'll need to use the name * Region.EU_WEST_1.id(). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param region the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder region(java.lang.String region) { doSetProperty("region", region); return this; } /** * Set the overriding uri endpoint. This option needs to be used in * combination with overrideEndpoint option. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param uriEndpointOverride the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder uriEndpointOverride(java.lang.String uriEndpointOverride) { doSetProperty("uriEndpointOverride", uriEndpointOverride); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * To use an existing configured AWS Eventbridge client. * * The option is a: * &lt;code&gt;software.amazon.awssdk.services.eventbridge.EventBridgeClient&lt;/code&gt; type. * * Group: advanced * * @param eventbridgeClient the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder eventbridgeClient(software.amazon.awssdk.services.eventbridge.EventBridgeClient eventbridgeClient) { doSetProperty("eventbridgeClient", eventbridgeClient); return this; } /** * Used for enabling or disabling all consumer based health checks from * this component. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: health * * @param healthCheckConsumerEnabled the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder healthCheckConsumerEnabled(boolean healthCheckConsumerEnabled) { doSetProperty("healthCheckConsumerEnabled", healthCheckConsumerEnabled); return this; } /** * Used for enabling or disabling all producer based health checks from * this component. Notice: Camel has by default disabled all producer * based health-checks. You can turn on producer checks globally by * setting camel.health.producersEnabled=true. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: health * * @param healthCheckProducerEnabled the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder healthCheckProducerEnabled(boolean healthCheckProducerEnabled) { doSetProperty("healthCheckProducerEnabled", healthCheckProducerEnabled); return this; } /** * To define a proxy host when instantiating the Eventbridge client. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: proxy * * @param proxyHost the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder proxyHost(java.lang.String proxyHost) { doSetProperty("proxyHost", proxyHost); return this; } /** * To define a proxy port when instantiating the Eventbridge client. * * The option is a: &lt;code&gt;java.lang.Integer&lt;/code&gt; type. * * Group: proxy * * @param proxyPort the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder proxyPort(java.lang.Integer proxyPort) { doSetProperty("proxyPort", proxyPort); return this; } /** * To define a proxy protocol when instantiating the Eventbridge client. * * The option is a: * &lt;code&gt;software.amazon.awssdk.core.Protocol&lt;/code&gt; type. * * Default: HTTPS * Group: proxy * * @param proxyProtocol the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder proxyProtocol(software.amazon.awssdk.core.Protocol proxyProtocol) { doSetProperty("proxyProtocol", proxyProtocol); return this; } /** * Amazon AWS Access Key. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param accessKey the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder accessKey(java.lang.String accessKey) { doSetProperty("accessKey", accessKey); return this; } /** * If using a profile credentials provider this parameter will set the * profile name. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param profileCredentialsName the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder profileCredentialsName(java.lang.String profileCredentialsName) { doSetProperty("profileCredentialsName", profileCredentialsName); return this; } /** * Amazon AWS Secret Key. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param secretKey the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder secretKey(java.lang.String secretKey) { doSetProperty("secretKey", secretKey); return this; } /** * Amazon AWS Session Token used when the user needs to assume an IAM * role. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param sessionToken the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder sessionToken(java.lang.String sessionToken) { doSetProperty("sessionToken", sessionToken); return this; } /** * If we want to trust all certificates in case of overriding the * endpoint. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param trustAllCertificates the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder trustAllCertificates(boolean trustAllCertificates) { doSetProperty("trustAllCertificates", trustAllCertificates); return this; } /** * Set whether the Eventbridge client should expect to load credentials * through a default credentials provider or to expect static * credentials to be passed in. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param useDefaultCredentialsProvider the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder useDefaultCredentialsProvider(boolean useDefaultCredentialsProvider) { doSetProperty("useDefaultCredentialsProvider", useDefaultCredentialsProvider); return this; } /** * Set whether the Eventbridge client should expect to load credentials * through a profile credentials provider. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param useProfileCredentialsProvider the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder useProfileCredentialsProvider(boolean useProfileCredentialsProvider) { doSetProperty("useProfileCredentialsProvider", useProfileCredentialsProvider); return this; } /** * Set whether the Eventbridge client should expect to use Session * Credentials. This is useful in a situation in which the user needs to * assume an IAM role for doing operations in Eventbridge. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param useSessionCredentials the value to set * @return the dsl builder */ default Aws2EventbridgeComponentBuilder useSessionCredentials(boolean useSessionCredentials) { doSetProperty("useSessionCredentials", useSessionCredentials); return this; } }
Aws2EventbridgeComponentBuilder
java
netty__netty
common/src/main/java/io/netty/util/concurrent/GenericFutureListener.java
{ "start": 912, "end": 1234 }
interface ____<F extends Future<?>> extends EventListener { /** * Invoked when the operation associated with the {@link Future} has been completed. * * @param future the source {@link Future} which called this callback */ void operationComplete(F future) throws Exception; }
GenericFutureListener
java
apache__camel
components/camel-google/camel-google-drive/src/generated/java/org/apache/camel/component/google/drive/DriveTeamdrivesEndpointConfigurationConfigurer.java
{ "start": 750, "end": 8464 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("AccessToken", java.lang.String.class); map.put("ApiName", org.apache.camel.component.google.drive.internal.GoogleDriveApiName.class); map.put("ApplicationName", java.lang.String.class); map.put("ClientId", java.lang.String.class); map.put("ClientSecret", java.lang.String.class); map.put("Content", com.google.api.services.drive.model.TeamDrive.class); map.put("Delegate", java.lang.String.class); map.put("MethodName", java.lang.String.class); map.put("PageSize", java.lang.Integer.class); map.put("PageToken", java.lang.String.class); map.put("Q", java.lang.String.class); map.put("RefreshToken", java.lang.String.class); map.put("RequestId", java.lang.String.class); map.put("Scopes", java.lang.String.class); map.put("ServiceAccountKey", java.lang.String.class); map.put("TeamDriveId", java.lang.String.class); map.put("UseDomainAdminAccess", java.lang.Boolean.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.google.drive.DriveTeamdrivesEndpointConfiguration target = (org.apache.camel.component.google.drive.DriveTeamdrivesEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "accessToken": target.setAccessToken(property(camelContext, java.lang.String.class, value)); return true; case "apiname": case "apiName": target.setApiName(property(camelContext, org.apache.camel.component.google.drive.internal.GoogleDriveApiName.class, value)); return true; case "applicationname": case "applicationName": target.setApplicationName(property(camelContext, java.lang.String.class, value)); return true; case "clientid": case "clientId": target.setClientId(property(camelContext, java.lang.String.class, value)); return true; case "clientsecret": case "clientSecret": target.setClientSecret(property(camelContext, java.lang.String.class, value)); return true; case "content": target.setContent(property(camelContext, com.google.api.services.drive.model.TeamDrive.class, value)); return true; case "delegate": target.setDelegate(property(camelContext, java.lang.String.class, value)); return true; case "methodname": case "methodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true; case "pagesize": case "pageSize": target.setPageSize(property(camelContext, java.lang.Integer.class, value)); return true; case "pagetoken": case "pageToken": target.setPageToken(property(camelContext, java.lang.String.class, value)); return true; case "q": target.setQ(property(camelContext, java.lang.String.class, value)); return true; case "refreshtoken": case "refreshToken": target.setRefreshToken(property(camelContext, java.lang.String.class, value)); return true; case "requestid": case "requestId": target.setRequestId(property(camelContext, java.lang.String.class, value)); return true; case "scopes": target.setScopes(property(camelContext, java.lang.String.class, value)); return true; case "serviceaccountkey": case "serviceAccountKey": target.setServiceAccountKey(property(camelContext, java.lang.String.class, value)); return true; case "teamdriveid": case "teamDriveId": target.setTeamDriveId(property(camelContext, java.lang.String.class, value)); return true; case "usedomainadminaccess": case "useDomainAdminAccess": target.setUseDomainAdminAccess(property(camelContext, java.lang.Boolean.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "accessToken": return java.lang.String.class; case "apiname": case "apiName": return org.apache.camel.component.google.drive.internal.GoogleDriveApiName.class; case "applicationname": case "applicationName": return java.lang.String.class; case "clientid": case "clientId": return java.lang.String.class; case "clientsecret": case "clientSecret": return java.lang.String.class; case "content": return com.google.api.services.drive.model.TeamDrive.class; case "delegate": return java.lang.String.class; case "methodname": case "methodName": return java.lang.String.class; case "pagesize": case "pageSize": return java.lang.Integer.class; case "pagetoken": case "pageToken": return java.lang.String.class; case "q": return java.lang.String.class; case "refreshtoken": case "refreshToken": return java.lang.String.class; case "requestid": case "requestId": return java.lang.String.class; case "scopes": return java.lang.String.class; case "serviceaccountkey": case "serviceAccountKey": return java.lang.String.class; case "teamdriveid": case "teamDriveId": return java.lang.String.class; case "usedomainadminaccess": case "useDomainAdminAccess": return java.lang.Boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.google.drive.DriveTeamdrivesEndpointConfiguration target = (org.apache.camel.component.google.drive.DriveTeamdrivesEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "accessToken": return target.getAccessToken(); case "apiname": case "apiName": return target.getApiName(); case "applicationname": case "applicationName": return target.getApplicationName(); case "clientid": case "clientId": return target.getClientId(); case "clientsecret": case "clientSecret": return target.getClientSecret(); case "content": return target.getContent(); case "delegate": return target.getDelegate(); case "methodname": case "methodName": return target.getMethodName(); case "pagesize": case "pageSize": return target.getPageSize(); case "pagetoken": case "pageToken": return target.getPageToken(); case "q": return target.getQ(); case "refreshtoken": case "refreshToken": return target.getRefreshToken(); case "requestid": case "requestId": return target.getRequestId(); case "scopes": return target.getScopes(); case "serviceaccountkey": case "serviceAccountKey": return target.getServiceAccountKey(); case "teamdriveid": case "teamDriveId": return target.getTeamDriveId(); case "usedomainadminaccess": case "useDomainAdminAccess": return target.getUseDomainAdminAccess(); default: return null; } } }
DriveTeamdrivesEndpointConfigurationConfigurer
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng2305MultipleProxiesTest.java
{ "start": 6082, "end": 7545 }
class ____ extends AbstractHandler { public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter writer = response.getWriter(); String uri = request.getRequestURI(); if (!uri.startsWith("/repo/org/apache/maven/its/mng2305/" + request.getScheme() + "/")) { // HTTP connector serves only http-0.1.jar and HTTPS connector serves only https-0.1.jar response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else if (uri.endsWith(".pom")) { writer.println("<project xmlns=\"http://maven.apache.org/POM/4.0.0\">"); writer.println(" <modelVersion>4.0.0</modelVersion>"); writer.println(" <groupId>org.apache.maven.its.mng2305</groupId>"); writer.println(" <artifactId>" + request.getScheme() + "</artifactId>"); writer.println(" <version>0.1</version>"); writer.println("</project>"); response.setStatus(HttpServletResponse.SC_OK); } else if (uri.endsWith(".jar")) { writer.println("empty"); response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } ((Request) request).setHandled(true); } } }
RepoHandler
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/state/v2/RegisteredKeyValueStateBackendMetaInfoV2Test.java
{ "start": 1797, "end": 10855 }
class ____ { @Test void testRegisteredKeyValueStateBackendMetaInfoV2SerializationRoundtrip() throws Exception { TypeSerializer<?> keySerializer = IntSerializer.INSTANCE; TypeSerializer<?> namespaceSerializer = LongSerializer.INSTANCE; TypeSerializer<?> stateSerializer = DoubleSerializer.INSTANCE; TypeSerializer<?> userKeySerializer = StringSerializer.INSTANCE; List<StateMetaInfoSnapshot> stateMetaInfoList = new ArrayList<>(); stateMetaInfoList.add( new org.apache.flink.runtime.state.v2.RegisteredKeyValueStateBackendMetaInfo<>( "a", org.apache.flink.api.common.state.v2.StateDescriptor.Type.VALUE, namespaceSerializer, stateSerializer) .snapshot()); stateMetaInfoList.add( new org.apache.flink.runtime.state.v2 .RegisteredKeyAndUserKeyValueStateBackendMetaInfo<>( "b", org.apache.flink.api.common.state.v2.StateDescriptor.Type.MAP, namespaceSerializer, stateSerializer, userKeySerializer) .snapshot()); stateMetaInfoList.add( new org.apache.flink.runtime.state.v2.RegisteredKeyValueStateBackendMetaInfo<>( "c", org.apache.flink.api.common.state.v2.StateDescriptor.Type.VALUE, namespaceSerializer, stateSerializer) .snapshot()); KeyedBackendSerializationProxy<?> serializationProxy = new KeyedBackendSerializationProxy<>(keySerializer, stateMetaInfoList, true); byte[] serialized; try (ByteArrayOutputStreamWithPos out = new ByteArrayOutputStreamWithPos()) { serializationProxy.write(new DataOutputViewStreamWrapper(out)); serialized = out.toByteArray(); } serializationProxy = new KeyedBackendSerializationProxy<>( Thread.currentThread().getContextClassLoader()); try (ByteArrayInputStreamWithPos in = new ByteArrayInputStreamWithPos(serialized)) { serializationProxy.read(new DataInputViewStreamWrapper(in)); } assertThat(serializationProxy.isUsingKeyGroupCompression()).isTrue(); assertThat(serializationProxy.getKeySerializerSnapshot()) .isInstanceOf(IntSerializer.IntSerializerSnapshot.class); assertEqualStateMetaInfoSnapshotsLists( stateMetaInfoList, serializationProxy.getStateMetaInfoSnapshots()); } @Test void testMapKeyedStateMetaInfoSerialization() throws Exception { TypeSerializer<?> keySerializer = IntSerializer.INSTANCE; TypeSerializer<?> namespaceSerializer = LongSerializer.INSTANCE; TypeSerializer<?> stateSerializer = DoubleSerializer.INSTANCE; TypeSerializer<?> userKeySerializer = StringSerializer.INSTANCE; List<StateMetaInfoSnapshot> stateMetaInfoList = new ArrayList<>(); // create StateMetaInfoSnapshot without userKeySerializer StateMetaInfoSnapshot oldStateMeta = new org.apache.flink.runtime.state.v2.RegisteredKeyValueStateBackendMetaInfo<>( "test1", org.apache.flink.api.common.state.v2.StateDescriptor.Type.MAP, namespaceSerializer, stateSerializer) .snapshot(); StateMetaInfoSnapshot oldStateMetaWithUserKey = new org.apache.flink.runtime.state.v2 .RegisteredKeyAndUserKeyValueStateBackendMetaInfo<>( "test2", org.apache.flink.api.common.state.v2.StateDescriptor.Type.MAP, namespaceSerializer, stateSerializer, userKeySerializer) .snapshot(); stateMetaInfoList.add(oldStateMeta); stateMetaInfoList.add(oldStateMetaWithUserKey); assertThat(oldStateMeta.getBackendStateType()) .isEqualTo(StateMetaInfoSnapshot.BackendStateType.KEY_VALUE_V2); assertThat(oldStateMetaWithUserKey.getBackendStateType()) .isEqualTo(StateMetaInfoSnapshot.BackendStateType.KEY_VALUE_V2); assertThat( oldStateMeta.getTypeSerializerSnapshot( StateMetaInfoSnapshot.CommonSerializerKeys.USER_KEY_SERIALIZER)) .isNull(); assertThat( oldStateMetaWithUserKey .getTypeSerializerSnapshot( StateMetaInfoSnapshot.CommonSerializerKeys .USER_KEY_SERIALIZER) .restoreSerializer()) .isEqualTo(userKeySerializer); KeyedBackendSerializationProxy<?> serializationProxy = new KeyedBackendSerializationProxy<>(keySerializer, stateMetaInfoList, true); byte[] serialized; try (ByteArrayOutputStreamWithPos out = new ByteArrayOutputStreamWithPos()) { serializationProxy.write(new DataOutputViewStreamWrapper(out)); serialized = out.toByteArray(); } serializationProxy = new KeyedBackendSerializationProxy<>( Thread.currentThread().getContextClassLoader()); try (ByteArrayInputStreamWithPos in = new ByteArrayInputStreamWithPos(serialized)) { serializationProxy.read(new DataInputViewStreamWrapper(in)); } List<StateMetaInfoSnapshot> stateMetaInfoSnapshots = serializationProxy.getStateMetaInfoSnapshots(); org.apache.flink.runtime.state.v2.RegisteredKeyValueStateBackendMetaInfo restoredMetaInfo = (RegisteredKeyValueStateBackendMetaInfo) RegisteredStateMetaInfoBase.fromMetaInfoSnapshot( stateMetaInfoSnapshots.get(0)); assertThat(restoredMetaInfo.getClass()) .isEqualTo( org.apache.flink.runtime.state.v2 .RegisteredKeyAndUserKeyValueStateBackendMetaInfo.class); assertThat(restoredMetaInfo.getName()).isEqualTo("test1"); assertThat( ((RegisteredKeyAndUserKeyValueStateBackendMetaInfo) restoredMetaInfo) .getUserKeySerializer()) .isNull(); assertThat(restoredMetaInfo.getStateSerializer()).isEqualTo(DoubleSerializer.INSTANCE); assertThat(restoredMetaInfo.getNamespaceSerializer()).isEqualTo(LongSerializer.INSTANCE); org.apache.flink.runtime.state.v2.RegisteredKeyValueStateBackendMetaInfo restoredMetaInfo1 = (RegisteredKeyValueStateBackendMetaInfo) RegisteredStateMetaInfoBase.fromMetaInfoSnapshot( stateMetaInfoSnapshots.get(1)); assertThat(restoredMetaInfo1.getClass()) .isEqualTo( org.apache.flink.runtime.state.v2 .RegisteredKeyAndUserKeyValueStateBackendMetaInfo.class); assertThat(restoredMetaInfo1.getName()).isEqualTo("test2"); assertThat( ((RegisteredKeyAndUserKeyValueStateBackendMetaInfo) restoredMetaInfo1) .getUserKeySerializer()) .isEqualTo(StringSerializer.INSTANCE); assertThat(restoredMetaInfo1.getStateSerializer()).isEqualTo(DoubleSerializer.INSTANCE); assertThat(restoredMetaInfo1.getNamespaceSerializer()).isEqualTo(LongSerializer.INSTANCE); } private void assertEqualStateMetaInfoSnapshotsLists( List<StateMetaInfoSnapshot> expected, List<StateMetaInfoSnapshot> actual) { assertThat(actual).hasSameSizeAs(expected); for (int i = 0; i < expected.size(); ++i) { assertEqualStateMetaInfoSnapshots(expected.get(i), actual.get(i)); } } private void assertEqualStateMetaInfoSnapshots( StateMetaInfoSnapshot expected, StateMetaInfoSnapshot actual) { assertThat(actual.getName()).isEqualTo(expected.getName()); assertThat(actual.getBackendStateType()).isEqualTo(expected.getBackendStateType()); assertThat(actual.getOptionsImmutable()).isEqualTo(expected.getOptionsImmutable()); assertThat(actual.getSerializerSnapshotsImmutable()) .isEqualTo(expected.getSerializerSnapshotsImmutable()); } }
RegisteredKeyValueStateBackendMetaInfoV2Test
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest48.java
{ "start": 982, "end": 2887 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "select sequence_name from all_sequences " + "union select synonym_name" + " from all_synonyms us, all_sequences asq" + " where asq.sequence_name = us.table_name" + " and asq.sequence_owner = us.table_owner"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(2, visitor.getTables().size()); assertEquals(5, visitor.getColumns().size()); String text = TestUtils.outputOracle(stmt); assertEquals("SELECT sequence_name" + "\nFROM all_sequences" + "\nUNION" + "\nSELECT synonym_name" + "\nFROM all_synonyms us, all_sequences asq" + "\nWHERE asq.sequence_name = us.table_name" + "\n\tAND asq.sequence_owner = us.table_owner", text); // assertTrue(visitor.getColumns().contains(new TableStat.Column("acduser.vw_acd_info", "xzqh"))); // assertTrue(visitor.getOrderByColumns().contains(new TableStat.Column("employees", "last_name"))); } }
OracleSelectTest48
java
grpc__grpc-java
api/src/main/java/io/grpc/NameResolverProvider.java
{ "start": 1178, "end": 1400 }
class ____. Implementations that need arguments in * their constructor can be manually registered by {@link NameResolverRegistry#register}. * * <p>Implementations <em>should not</em> throw. If they do, it may interrupt
name
java
apache__camel
core/camel-main/src/test/java/org/apache/camel/main/MainScan2Test.java
{ "start": 1081, "end": 1627 }
class ____ { @Test public void testScan2() { Main main = new Main(); main.configure().withBasePackageScan("org.apache.camel.main.scan2"); main.start(); CamelContext camelContext = main.getCamelContext(); assertNotNull(camelContext); assertEquals(1, camelContext.getRoutes().size()); String out = camelContext.createProducerTemplate().requestBody("direct:start", "Camel", String.class); Assertions.assertEquals("Hello Camel", out); main.stop(); } }
MainScan2Test
java
apache__kafka
server-common/src/main/java/org/apache/kafka/timeline/SnapshottableHashTable.java
{ "start": 4546, "end": 4825 }
class ____<T extends SnapshottableHashTable.ElementWithStartEpoch> extends BaseHashTable<T> implements Revertable { /** * A special epoch value that represents the latest data. */ static final long LATEST_EPOCH = Long.MAX_VALUE;
SnapshottableHashTable
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/ServerResponseFilter.java
{ "start": 959, "end": 2366 }
class ____ { * * private final SomeBean someBean; * * // SomeBean will be automatically injected by CDI as long as SomeBean is a bean itself * public CustomContainerResponseFilter(SomeBean someBean) { * this.someBean = someBean; * } * * &#64;ServerResponseFilter * public void whatever(SimplifiedResourceInfo resourceInfo) { * // do something * } * } * </pre> * * Methods annotated with {@code ServerResponseFilter} can declare any of the following parameters (in any order) * <ul> * <li>{@link ContainerRequestContext} * <li>{@link ContainerResponseContext} * <li>{@link ResourceInfo} * <li>{@link UriInfo} * <li>{@link SimpleResourceInfo} * <li>{@link Throwable} - The thrown exception - or {@code null} if no exception was thrown * </ul> * * The return type of the method must be either be of type {@code void} or {@code Uni<Void>}. * <ul> * <li>{@code void} should be used when filtering does not need to perform any blocking operations. * <li>{@code Uni<Void>} should be used when filtering needs to perform a blocking operations. * </ul> * * Another important thing to note is that if {@link ContainerRequestContext} is used as a request parameter, calling * {@code abortWith} * is prohibited by the JAX-RS specification. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @
CustomContainerResponseFilter
java
redisson__redisson
redisson/src/main/java/org/redisson/PubSubStatusListener.java
{ "start": 959, "end": 2355 }
class ____ implements RedisPubSubListener<Object> { private final StatusListener listener; private final String[] names; private final Set<String> notified = Collections.newSetFromMap(new ConcurrentHashMap<>()); public PubSubStatusListener(StatusListener listener, String... names) { super(); this.listener = listener; this.names = names; notified.addAll(Arrays.asList(names)); } @Override public void onMessage(CharSequence channel, Object message) { } @Override public void onPatternMessage(CharSequence pattern, CharSequence channel, Object message) { } @Override public void onStatus(PubSubType type, CharSequence channel) { notified.remove(channel.toString()); if (notified.isEmpty()) { if (type == PubSubType.SUBSCRIBE || type == PubSubType.SSUBSCRIBE || type == PubSubType.PSUBSCRIBE) { listener.onSubscribe(channel.toString()); notified.addAll(Arrays.asList(names)); } else if (type == PubSubType.UNSUBSCRIBE || type == PubSubType.SUNSUBSCRIBE || type == PubSubType.PUNSUBSCRIBE) { listener.onUnsubscribe(channel.toString()); } } } public String[] getNames() { return names; } public StatusListener getListener() { return listener; } }
PubSubStatusListener
java
apache__flink
flink-table/flink-table-api-java-bridge/src/main/java/org/apache/flink/legacy/table/sources/StreamTableSource.java
{ "start": 1534, "end": 2093 }
interface ____<T> extends TableSource<T> { /** * Returns true if this is a bounded source, false if this is an unbounded source. Default is * unbounded for compatibility. */ default boolean isBounded() { return false; } /** * Returns the data of the table as a {@link DataStream}. * * <p>NOTE: This method is for internal use only for defining a {@link TableSource}. Do not use * it in Table API programs. */ DataStream<T> getDataStream(StreamExecutionEnvironment execEnv); }
StreamTableSource
java
netty__netty
handler/src/test/java/io/netty/handler/ssl/PemReaderTest.java
{ "start": 866, "end": 5514 }
class ____ { @Test public void mustBeAbleToReadMultipleCertificates() throws Exception { byte[] certs = ("-----BEGIN CERTIFICATE-----\n" + "MIICqjCCAZKgAwIBAgIIEaz8uuDHTcIwDQYJKoZIhvcNAQELBQAwFDESMBAGA1UEAwwJbG9jYWxo\n" + "b3N0MCAXDTIxMDYxNjE3MjYyOFoYDzk5OTkxMjMxMjM1OTU5WjAUMRIwEAYDVQQDDAlsb2NhbGhv\n" + "c3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCVjENomtpMqHkg1yJ/uYZgSWmf/0Gb\n" + "U4yMDf30muPvMYb3gO6peEnoXa2b0WDOjLbLrcltp1YdjTlLhRRTYgDo9TAvHoUdoMGlTnfQtQne\n" + "2o+/92bnlZTroRIjUT0lqSxQ6UNXcOi9tNqVD4tML3vk20fudwBur8Plx+3hOhM/v64GbV46k06+\n" + "AblrFwBt9u6V0uIVtvgraOd+NgL4yNf594uND30mbB7Q7xe/Y6DiPhI6cVI/CbLlXVwKLvC5OziS\n" + "JKZ7svP0K3DBRxk+dOD9pg4SdaAEQVtR734ZlDh1XJ+mZssuDDda3NGZAjpCU4rkeV/J3Tr5KKMD\n" + "g3NEOmifAgMBAAEwDQYJKoZIhvcNAQELBQADggEBABejZGeRNCyPdIqac6cyAf99JPp5OySEMWHU\n" + "QXVCHEbQ8Eh6hsmrXSEaZS2zy/5dixPb5Rin0xaX5fqZdfLIUc0Mw/zXV/RiOIjrtUKez15Ko/4K\n" + "ONyxELjUq+SaJx2C1UcKEMfQBeq7O6XO60CLQ2AtVozmvJU9pt4KYQv0Kr+br3iNFpRuR43IYHyx\n" + "HP7QsD3L3LEqIqW/QtYEnAAngZofUiq0XELh4GB0L8DbcSJIxfZmYagFl7c2go9OZPD14mlaTnMV\n" + "Pjd+OkwMif5T7v+r+KVSmDSMQwa+NfW+V6Xngg5/bN3kWHdw9qFQGANojl9wsRVN/B3pu3Cc2XFD\n" + "MmQ=\n" + "-----END CERTIFICATE-----\n" + "-----BEGIN CERTIFICATE-----\n" + "MIICqjCCAZKgAwIBAgIIIsUS6UkDau4wDQYJKoZIhvcNAQELBQAwFDESMBAGA1UEAwwJbG9jYWxo\n" + "b3N0MCAXDTIxMDYxNjE3MjYyOFoYDzk5OTkxMjMxMjM1OTU5WjAUMRIwEAYDVQQDDAlsb2NhbGhv\n" + "c3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCTZmahFZXB0Dv3N8t6gfXTeqhTxRng\n" + "mIBBPmrbZBODrZm06vrR5KNhxB2FhWIq1Yu8xXXv8sO+PaO2Sw/h6TeslRJ4EkrNd9zmYhT2cJvP\n" + "d1CtkX5EHyMZRUKj7Eg4eUO1k/+JnhMmaY+nUAG7fCtvs8pS9SEXbEqYW7S4AQ1oopbCAMqQekly\n" + "KCdnjGlVhXwL2Lj2rr/uw1Fc2+WvY/leQGo0rbIqoc7OSAktsP+MXI6iQ1RWJOec15V6iFRzcdE3\n" + "Q4ODSMZ/R8wm9DH+4hkeQNPMbcc1wlvVZpDZ/FZegr1XimcYcJr2AoAQf3Xe1yFKAtBMXCjCIGm8\n" + "veCQ+xeHAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAGyV+dib2MdpenbntKk7PdZEx+/vNl9cEpwL\n" + "BfWmQN/j2RmHUxrUM+PVkLTgyCq8okdCKqCvraKwBkF6vlzp4u5CL4L323z+/uxAi6pzbcWnG1EH\n" + "JpSkf1OhTUFu6UhLfpg3XqeiIujYdVZTpHr7KHVLRYUSQPprt4HjLZeCIg4P2pZ0yQ3SEBhVed89\n" + "GMj/+O4jjvuZv5NQc57NpMIrE9fNINczLG1CPTgnhvqMP42W6ahBuexQUe4gP+jmB/BZmBYKoauU\n" + "mPBKruq3mNuoXtbHufv5I7CFVXNgJ0/aT+lvEkQ4IlCIcJyvTgyUTOQVbqDp+SswymAIRowaRdxa\n" + "7Ss=\n" + "-----END CERTIFICATE-----\n").getBytes(CharsetUtil.US_ASCII); ByteArrayInputStream in = new ByteArrayInputStream(certs); ByteBuf[] bufs = PemReader.readCertificates(in); assertThat(bufs.length).isEqualTo(2); for (ByteBuf buf : bufs) { buf.release(); } } @Test public void mustBeAbleToReadPrivateKey() throws Exception { byte[] key = ("-----BEGIN PRIVATE KEY-----\n" + "MIICqjCCAZKgAwIBAgIIEaz8uuDHTcIwDQYJKoZIhvcNAQELBQAwFDESMBAGA1UEAwwJbG9jYWxo\n" + "b3N0MCAXDTIxMDYxNjE3MjYyOFoYDzk5OTkxMjMxMjM1OTU5WjAUMRIwEAYDVQQDDAlsb2NhbGhv\n" + "c3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCVjENomtpMqHkg1yJ/uYZgSWmf/0Gb\n" + "U4yMDf30muPvMYb3gO6peEnoXa2b0WDOjLbLrcltp1YdjTlLhRRTYgDo9TAvHoUdoMGlTnfQtQne\n" + "2o+/92bnlZTroRIjUT0lqSxQ6UNXcOi9tNqVD4tML3vk20fudwBur8Plx+3hOhM/v64GbV46k06+\n" + "AblrFwBt9u6V0uIVtvgraOd+NgL4yNf594uND30mbB7Q7xe/Y6DiPhI6cVI/CbLlXVwKLvC5OziS\n" + "JKZ7svP0K3DBRxk+dOD9pg4SdaAEQVtR734ZlDh1XJ+mZssuDDda3NGZAjpCU4rkeV/J3Tr5KKMD\n" + "g3NEOmifAgMBAAEwDQYJKoZIhvcNAQELBQADggEBABejZGeRNCyPdIqac6cyAf99JPp5OySEMWHU\n" + "QXVCHEbQ8Eh6hsmrXSEaZS2zy/5dixPb5Rin0xaX5fqZdfLIUc0Mw/zXV/RiOIjrtUKez15Ko/4K\n" + "ONyxELjUq+SaJx2C1UcKEMfQBeq7O6XO60CLQ2AtVozmvJU9pt4KYQv0Kr+br3iNFpRuR43IYHyx\n" + "HP7QsD3L3LEqIqW/QtYEnAAngZofUiq0XELh4GB0L8DbcSJIxfZmYagFl7c2go9OZPD14mlaTnMV\n" + "Pjd+OkwMif5T7v+r+KVSmDSMQwa+NfW+V6Xngg5/bN3kWHdw9qFQGANojl9wsRVN/B3pu3Cc2XFD\n" + "MmQ=\n" + "-----END PRIVATE KEY-----\n").getBytes(CharsetUtil.US_ASCII); ByteArrayInputStream in = new ByteArrayInputStream(key); ByteBuf buf = PemReader.readPrivateKey(in); assertThat(buf.readableBytes()).isEqualTo(686); buf.release(); } }
PemReaderTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java
{ "start": 5930, "end": 6076 }
interface ____ { @SuppressWarnings("unchecked") <V extends MyInterface> boolean doWithVarargs(V... args); } public static
VarargTestInterface
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/sqlprovider/ProviderMethodResolutionTest.java
{ "start": 7048, "end": 7263 }
class ____ { public static String provideSql() { return "DELETE FROM memos WHERE id = 1"; } private ReservedMethodNameBasedSqlProvider() { } }
ReservedMethodNameBasedSqlProvider
java
apache__camel
components/camel-aws/camel-aws2-iam/src/test/java/org/apache/camel/component/aws2/iam/integration/IAMGetUserIT.java
{ "start": 1357, "end": 2846 }
class ____ extends Aws2IAMBase { @EndpointInject("mock:result") private MockEndpoint mock; @Test public void iamCreateUserTest() throws Exception { mock.expectedMessageCount(1); Exchange exchange = template.request("direct:createUser", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(IAM2Constants.OPERATION, IAM2Operations.createUser); exchange.getIn().setHeader(IAM2Constants.USERNAME, "test"); } }); exchange = template.request("direct:getUser", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(IAM2Constants.OPERATION, IAM2Operations.getUser); exchange.getIn().setHeader(IAM2Constants.USERNAME, "test"); } }); MockEndpoint.assertIsSatisfied(context); GetUserResponse resultGet = (GetUserResponse) exchange.getIn().getBody(); assertEquals("test", resultGet.user().userName()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:createUser").to("aws2-iam://test?operation=createUser"); from("direct:getUser").to("aws2-iam://test?operation=getUser").to("mock:result"); } }; } }
IAMGetUserIT
java
quarkusio__quarkus
integration-tests/test-extension/extension/deployment/src/test/java/io/quarkus/extest/UnknownConfigTest.java
{ "start": 696, "end": 1981 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addAsResource("application.properties")) .setLogRecordPredicate(record -> record.getLevel().intValue() >= Level.WARNING.intValue()) .assertLogRecords(logRecords -> { Set<String> properties = logRecords.stream().flatMap( logRecord -> Stream.of(Optional.ofNullable(logRecord.getParameters()).orElse(new Object[0]))) .map(Object::toString).collect(Collectors.toSet()); assertTrue(properties.contains("quarkus.unknown.prop")); assertFalse(properties.contains("quarkus.build.unknown.prop")); assertFalse(properties.contains("proprietary.should.not.report.unknown")); }); @Inject Config config; @Inject VertxHttpBuildTimeConfig httpBuildTimeConfig; @Inject VertxHttpConfig httpConfig; @Test void unknown() { assertEquals("1234", config.getConfigValue("quarkus.unknown.prop").getValue()); assertEquals("/1234", httpBuildTimeConfig.nonApplicationRootPath()); assertEquals(4443, httpConfig.sslPort()); } }
UnknownConfigTest
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_3317/Issue3317Mapper.java
{ "start": 308, "end": 454 }
interface ____ { Issue3317Mapper INSTANCE = Mappers.getMapper( Issue3317Mapper.class ); Target map(int id, long value);
Issue3317Mapper
java
elastic__elasticsearch
x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/exporter/Exporter.java
{ "start": 8579, "end": 10398 }
class ____ { private final String exporterName; private final String exporterType; private final boolean complete; private final List<Exception> exceptions; public ExporterResourceStatus(String exporterName, String exporterType, boolean complete, List<Exception> exceptions) { this.exporterName = exporterName; this.exporterType = exporterType; this.complete = complete; this.exceptions = exceptions; } public static ExporterResourceStatus ready(String exporterName, String exporterType) { return new ExporterResourceStatus(exporterName, exporterType, true, null); } public static ExporterResourceStatus notReady(String exporterName, String exporterType, String reason, Object... args) { return notReady(exporterName, exporterType, new ElasticsearchException(reason, args)); } public static ExporterResourceStatus notReady(String exporterName, String exporterType, Exception reason) { return new ExporterResourceStatus(exporterName, exporterType, false, Collections.singletonList(reason)); } public static ExporterResourceStatus determineReadiness(String exporterName, String exporterType, List<Exception> exceptions) { return new ExporterResourceStatus(exporterName, exporterType, exceptions.size() <= 0, exceptions); } public String getExporterName() { return exporterName; } public String getExporterType() { return exporterType; } public boolean isComplete() { return complete; } @Nullable public List<Exception> getExceptions() { return exceptions; } } }
ExporterResourceStatus
java
apache__camel
core/camel-core-processor/src/main/java/org/apache/camel/processor/validator/ProcessorValidator.java
{ "start": 1449, "end": 4102 }
class ____ extends Validator { private static final Logger LOG = LoggerFactory.getLogger(ProcessorValidator.class); private Processor processor; private String validatorString; public ProcessorValidator(CamelContext context) { setCamelContext(context); } /** * Perform content validation with specified type using Processor. * * @param message message to apply validation * @param type 'from' data type */ @Override public void validate(Message message, DataType type) throws ValidationException { Exchange exchange = message.getExchange(); LOG.debug("Sending to validate processor '{}'", processor); // create a new exchange to use during validation to avoid side-effects on original exchange Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, false, true); try { processor.process(copy); // if the validation failed then propagate the exception if (copy.getException() != null) { exchange.setException(copy.getException()); } else { // success copy result ExchangeHelper.copyResults(exchange, copy); } } catch (Exception e) { if (e instanceof ValidationException validationException) { throw validationException; } else { throw new ValidationException(String.format("Validation failed for '%s'", type), exchange, e); } } } /** * Set processor to use * * @param processor Processor * @return this ProcessorTransformer instance */ public ProcessorValidator setProcessor(Processor processor) { this.processor = processor; this.validatorString = null; return this; } @Override public String toString() { if (validatorString == null) { validatorString = String.format("ProcessorValidator[type='%s', processor='%s']", getType(), processor); } return validatorString; } @Override protected void doBuild() throws Exception { ServiceHelper.buildService(processor); } @Override protected void doInit() throws Exception { ServiceHelper.initService(processor); } @Override protected void doStart() throws Exception { ObjectHelper.notNull(processor, "processor", this); ServiceHelper.startService(this.processor); } @Override protected void doStop() throws Exception { ServiceHelper.stopService(this.processor); } }
ProcessorValidator
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/util/collections/binary/BytesHashMapTest.java
{ "start": 1164, "end": 1776 }
class ____ extends BytesHashMapTestBase<BinaryRowData> { public BytesHashMapTest() { super(new BinaryRowDataSerializer(KEY_TYPES.length)); } @Override public AbstractBytesHashMap<BinaryRowData> createBytesHashMap( MemoryManager memoryManager, int memorySize, LogicalType[] keyTypes, LogicalType[] valueTypes) { return new BytesHashMap(this, memoryManager, memorySize, keyTypes, valueTypes); } @Override public BinaryRowData[] generateRandomKeys(int num) { return getRandomizedInputs(num); } }
BytesHashMapTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java
{ "start": 1990, "end": 2439 }
class ____ extends FsCheckpointStreamFactory.FsCheckpointStateOutputStream { private static final Logger LOG = LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class); /** * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files. */ public
FileMergingCheckpointStateOutputStream
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/conditional/propertyname/EmployeeDto.java
{ "start": 269, "end": 2049 }
class ____ implements DomainModel { private String firstName; private String lastName; private String title; private String originCountry; private boolean active; private int age; private EmployeeDto boss; private AddressDto primaryAddress; private List<AddressDto> originAddresses; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getOriginCountry() { return originCountry; } public void setOriginCountry(String originCountry) { this.originCountry = originCountry; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public EmployeeDto getBoss() { return boss; } public void setBoss(EmployeeDto boss) { this.boss = boss; } public AddressDto getPrimaryAddress() { return primaryAddress; } public void setPrimaryAddress(AddressDto primaryAddress) { this.primaryAddress = primaryAddress; } public List<AddressDto> getOriginAddresses() { return originAddresses; } public void setOriginAddresses(List<AddressDto> originAddresses) { this.originAddresses = originAddresses; } }
EmployeeDto
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/inject/FieldInjectionPoint.java
{ "start": 1034, "end": 1608 }
interface ____<B, T> extends InjectionPoint<B>, AnnotationMetadataProvider, AnnotatedElement, ArgumentCoercible<T> { /** * @return The name of the field */ @Override String getName(); /** * Resolves the underlying field. Note that this method will cause reflection * metadata to be initialized and should be avoided. * * @return The target field */ @Deprecated(since = "4", forRemoval = true) Field getField(); /** * @return The required component type */ Class<T> getType(); }
FieldInjectionPoint
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/store/DataBlocks.java
{ "start": 5548, "end": 8842 }
class ____ implements Closeable { private final File file; private InputStream uploadStream; private byte[] byteArray; private boolean isClosed; /** * Constructor for byteArray upload data block. File and uploadStream * would be null. * * @param byteArray byteArray used to construct BlockUploadData. */ public BlockUploadData(byte[] byteArray) { this.file = null; this.uploadStream = null; this.byteArray = requireNonNull(byteArray); } /** * File constructor; input stream and byteArray will be null. * * @param file file to upload */ BlockUploadData(File file) { Preconditions.checkArgument(file.exists(), "No file: %s", file); this.file = file; this.uploadStream = null; this.byteArray = null; } /** * Stream constructor, file and byteArray field will be null. * * @param uploadStream stream to upload. */ BlockUploadData(InputStream uploadStream) { requireNonNull(uploadStream, "rawUploadStream"); this.uploadStream = uploadStream; this.file = null; this.byteArray = null; } /** * Predicate: does this instance contain a file reference. * * @return true if there is a file. */ boolean hasFile() { return file != null; } /** * Get the file, if there is one. * * @return the file for uploading, or null. */ File getFile() { return file; } /** * Get the raw upload stream, if the object was * created with one. * * @return the upload stream or null. */ InputStream getUploadStream() { return uploadStream; } /** * Convert to a byte array. * If the data is stored in a file, it will be read and returned. * If the data was passed in via an input stream (which happens if the * data is stored in a bytebuffer) then it will be converted to a byte * array -which will then be cached for any subsequent use. * * @return byte[] after converting the uploadBlock. * @throws IOException throw if an exception is caught while reading * File/InputStream or closing InputStream. */ public byte[] toByteArray() throws IOException { Preconditions.checkState(!isClosed, "Block is closed"); if (byteArray != null) { return byteArray; } if (file != null) { // Need to save byteArray here so that we don't read File if // byteArray() is called more than once on the same file. byteArray = FileUtils.readFileToByteArray(file); return byteArray; } byteArray = IOUtils.toByteArray(uploadStream); IOUtils.close(uploadStream); uploadStream = null; return byteArray; } /** * Close: closes any upload stream and byteArray provided in the * constructor. * * @throws IOException inherited exception. */ @Override public void close() throws IOException { isClosed = true; cleanupWithLogger(LOG, uploadStream); byteArray = null; if (file != null) { LOG.debug("File deleted in BlockUploadData close: {}", file.delete()); } } } /** * Base
BlockUploadData
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/expression/SearchedCaseExpressionTest.java
{ "start": 1143, "end": 5296 }
class ____ { @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test public void testCaseClause(SessionFactoryScope scope) { scope.inTransaction( session -> { CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Event> criteria = cb.createQuery( Event.class ); Root<Event> event = criteria.from( Event.class ); Path<EventType> type = event.get( "type" ); Expression<String> caseWhen = cb.<EventType, String>selectCase( type ) .when( EventType.TYPE1, "Admin Event" ) .when( EventType.TYPE2, "User Event" ) .when( EventType.TYPE3, "Reporter Event" ) .otherwise( "" ); criteria.select( event ); criteria.where( cb.equal( caseWhen, "Admin Event" ) ); // OK when use cb.like() method and others List<Event> resultList = session.createQuery( criteria ).getResultList(); assertThat( resultList ).isNotNull(); } ); } @Test public void testEqualClause(SessionFactoryScope scope) { scope.inTransaction( session -> { CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Event> criteria = cb.createQuery( Event.class ); Root<Event> event = criteria.from( Event.class ); Path<EventType> type = event.get( "type" ); Expression<String> caseWhen = cb.<String>selectCase() .when( cb.equal( type, EventType.TYPE1 ), "Type1" ) .otherwise( "" ); criteria.select( event ); criteria.where( cb.equal( caseWhen, "Admin Event" ) ); // OK when use cb.like() method and others List<Event> resultList = session.createQuery( criteria ).getResultList(); assertThat( resultList ).isNotNull(); } ); } @Test @JiraKey(value = "HHH-13167") public void testMissingElseClause(SessionFactoryScope scope) { scope.inTransaction( session -> { Event event = new Event(); event.id = 1L; event.type = EventType.TYPE1; session.persist( event ); } ); scope.inTransaction( session -> { CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Event> criteria = cb.createQuery( Event.class ); Root<Event> root = criteria.from( Event.class ); Path<EventType> type = root.get( "type" ); Expression<String> caseWhen = cb.<String>selectCase() .when( cb.equal( type, EventType.TYPE1 ), "Matched" ); criteria.select( root ); criteria.where( cb.equal( caseWhen, "Matched" ) ); Event event = session.createQuery( criteria ).getSingleResult(); assertThat( event.id ).isEqualTo( 1L ); } ); } @Test @JiraKey( "HHH-19896" ) public void testCaseWhenWithOtherwiseClauseExecutedAfterOneWithout(SessionFactoryScope scope) { scope.inTransaction( session -> { Event event = new Event(); event.id = 1L; event.type = EventType.TYPE1; session.persist( event ); } ); scope.inTransaction( session -> { CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Event> criteria = cb.createQuery( Event.class ); Root<Event> root = criteria.from( Event.class ); Path<EventType> type = root.get( "type" ); Expression<String> caseWhen = cb.<String>selectCase() .when( cb.equal( type, EventType.TYPE1 ), "Matched" ); criteria.select( root ); criteria.where( cb.equal( caseWhen, "Matched" ) ); Event event = session.createQuery( criteria ).getSingleResult(); assertThat( event.id ).isEqualTo( 1L ); } ); scope.inTransaction( session -> { CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Event> criteria = cb.createQuery( Event.class ); Root<Event> event = criteria.from( Event.class ); Path<EventType> type = event.get( "type" ); Expression<String> caseWhen = cb.<String>selectCase() .when( cb.equal( type, EventType.TYPE1 ), "Type1" ) .otherwise( "" ); criteria.select( event ); criteria.where( cb.equal( caseWhen, "Admin Event" ) ); // OK when use cb.like() method and others List<Event> resultList = session.createQuery( criteria ).getResultList(); assertThat( resultList ).isNotNull(); assertThat( resultList ).hasSize( 0 ); } ); } @Entity(name = "Event") public static
SearchedCaseExpressionTest
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/bugs/creation/PackagePrivateWithContextClassLoaderTest.java
{ "start": 3893, "end": 4895 }
class ____ delegates loading of mockito/JDK classes to its parent, * but defines in its own for others. If mockito selects the defining classloader of the mock * to the classloader of mockito, calling the abstract package-private method will fail - the * defining classloader of the mocked type's package is different from the generated mock class * package. Because the nonDelegatingLoader is a child of mockito's loader, it's more specific * and should be preferred. */ @Test public void classloader_with_parent_but_does_not_delegate() throws Exception { ClassLoader nonDelegatingLoader = new NotAlwaysDelegatingClassLoader(); Thread.currentThread().setContextClassLoader(nonDelegatingLoader); Class<?> loaded = Class.forName(LoadedByCustomLoader.class.getName(), false, nonDelegatingLoader); Method attemptMock = loaded.getDeclaredMethod("attemptMock"); attemptMock.invoke(null); } public static
that
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/message/BinaryMessageDecoder.java
{ "start": 3212, "end": 3950 }
class ____ decode messages * that were encoded using the {@code readSchema} (if any) and other schemas * that are added using {@link #addSchema(Schema)}. * * @param model the {@link GenericData data model} for datum instances * @param readSchema the {@link Schema} used to construct datum instances */ public BinaryMessageDecoder(GenericData model, Schema readSchema) { this(model, readSchema, null); } /** * Creates a new {@link BinaryMessageEncoder} that uses the given * {@link GenericData data model} to construct datum instances described by the * {@link Schema schema}. * <p> * The {@code readSchema} is used as the expected schema (read schema). Datum * instances created by this
can
java
quarkusio__quarkus
extensions/grpc/runtime/src/main/java/io/quarkus/grpc/runtime/devmode/GrpcServices.java
{ "start": 910, "end": 2190 }
class ____ extends AbstractMap<String, ServiceDefinitionAndStatus> { @Inject GrpcConfiguration configuration; @Inject GrpcHealthStorage healthStorage; @Inject DelegatingGrpcBeansStorage delegatingBeansMapping; public List<ServiceDefinitionAndStatus> getInfos() { List<GrpcServiceDefinition> services = GrpcServerRecorder.getServices(); List<ServiceDefinitionAndStatus> infos = new ArrayList<>(services.size()); for (GrpcServiceDefinition service : services) { infos.add(new ServiceDefinitionAndStatus(service, healthStorage.getStatuses() .getOrDefault(service.definition.getServiceDescriptor().getName(), ServingStatus.UNKNOWN))); } return infos; } @Override public Set<Entry<String, ServiceDefinitionAndStatus>> entrySet() { Set<Entry<String, ServiceDefinitionAndStatus>> entries = new HashSet<>(); for (GrpcServiceDefinition definition : GrpcServerRecorder.getServices()) { entries.add(new ServiceDefinitionAndStatus(definition, healthStorage.getStatuses() .getOrDefault(definition.definition.getServiceDescriptor().getName(), ServingStatus.UNKNOWN))); } return entries; } public
GrpcServices
java
junit-team__junit5
documentation/src/test/java/example/TestingAStackDemo.java
{ "start": 1597, "end": 2263 }
class ____ { String anElement = "an element"; @BeforeEach void pushAnElement() { stack.push(anElement); } @Test @DisplayName("it is no longer empty") void isNotEmpty() { assertFalse(stack.isEmpty()); } @Test @DisplayName("returns the element when popped and is empty") void returnElementWhenPopped() { assertEquals(anElement, stack.pop()); assertTrue(stack.isEmpty()); } @Test @DisplayName("returns the element when peeked but remains not empty") void returnElementWhenPeeked() { assertEquals(anElement, stack.peek()); assertFalse(stack.isEmpty()); } } } } // end::user_guide[]
AfterPushing
java
apache__dubbo
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/PenetrateAttachmentSelectorMock.java
{ "start": 1059, "end": 1942 }
class ____ implements PenetrateAttachmentSelector { @Override public Map<String, Object> select( Invocation invocation, RpcContextAttachment clientAttachment, RpcContextAttachment serverAttachment) { Map<String, Object> objectAttachments = RpcContext.getServerAttachment().getObjectAttachments(); objectAttachments.put("testKey", "testVal"); return objectAttachments; } @Override public Map<String, Object> selectReverse( Invocation invocation, RpcContextAttachment clientResponseContext, RpcContextAttachment serverResponseContext) { Map<String, Object> objectAttachments = RpcContext.getServerResponseContext().getObjectAttachments(); objectAttachments.put("reverseKey", "reverseVal"); return objectAttachments; } }
PenetrateAttachmentSelectorMock
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/origin/OriginLookupTests.java
{ "start": 965, "end": 1911 }
class ____ { @Test void getOriginWhenSourceIsNullShouldReturnNull() { assertThat(OriginLookup.getOrigin(null, "foo")).isNull(); } @Test void getOriginWhenSourceIsNotLookupShouldReturnLookupOrigin() { Object source = new Object(); assertThat(OriginLookup.getOrigin(source, "foo")).isNull(); } @Test @SuppressWarnings("unchecked") void getOriginWhenSourceIsLookupShouldReturnLookupOrigin() { OriginLookup<String> source = mock(OriginLookup.class); Origin origin = MockOrigin.of("bar"); given(source.getOrigin("foo")).willReturn(origin); assertThat(OriginLookup.getOrigin(source, "foo")).isEqualTo(origin); } @Test @SuppressWarnings("unchecked") void getOriginWhenSourceLookupThrowsAndErrorShouldReturnNull() { OriginLookup<String> source = mock(OriginLookup.class); willThrow(RuntimeException.class).given(source).getOrigin("foo"); assertThat(OriginLookup.getOrigin(source, "foo")).isNull(); } }
OriginLookupTests
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/PutFilterAction.java
{ "start": 1066, "end": 1365 }
class ____ extends ActionType<PutFilterAction.Response> { public static final PutFilterAction INSTANCE = new PutFilterAction(); public static final String NAME = "cluster:admin/xpack/ml/filters/put"; private PutFilterAction() { super(NAME); } public static
PutFilterAction
java
apache__flink
flink-table/flink-table-api-java/src/test/java/org/apache/flink/table/expressions/resolver/ExpressionResolverTest.java
{ "start": 20253, "end": 20733 }
class ____ extends ScalarFunction { public int eval(Object... any) { return 0; } @Override public TypeInformation<?> getResultType(Class<?>[] signature) { return Types.INT; } @Override public int hashCode() { return 0; } @Override public boolean equals(Object obj) { return obj instanceof ScalarFunc; } } private static
LegacyScalarFunc
java
apache__flink
flink-core-api/src/main/java/org/apache/flink/api/common/state/StateDeclaration.java
{ "start": 1037, "end": 1549 }
interface ____ extends Serializable { /** Get the name of this state. */ String getName(); /** * Get the {@link RedistributionMode} of this state. More details see the doc of {@link * RedistributionMode}. */ RedistributionMode getRedistributionMode(); /** * {@link RedistributionMode} is used to indicate whether this state supports redistribution * between partitions and how to redistribute this state during rescaling. */ @Experimental
StateDeclaration
java
apache__dubbo
dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/transport/DubboMcpSseTransportProviderTest.java
{ "start": 2405, "end": 6812 }
class ____ { @Mock private StreamObserver<ServerSentEvent<String>> responseObserver; @Mock private HttpRequest httpRequest; @Mock private HttpResponse httpResponse; @Mock private McpServerSession.Factory sessionFactory; @Mock private RpcServiceContext rpcServiceContext; @Mock private McpServerSession mockSession; private MockedStatic<RpcContext> rpcContextMockedStatic; @InjectMocks private DubboMcpSseTransportProvider transportProvider; private final ObjectMapper objectMapper = new ObjectMapper(); @BeforeEach void setUp() { rpcContextMockedStatic = mockStatic(RpcContext.class); rpcContextMockedStatic.when(RpcContext::getServiceContext).thenReturn(rpcServiceContext); when(rpcServiceContext.getRequest(HttpRequest.class)).thenReturn(httpRequest); when(rpcServiceContext.getResponse(HttpResponse.class)).thenReturn(httpResponse); transportProvider = new DubboMcpSseTransportProvider(objectMapper); transportProvider.setSessionFactory(sessionFactory); } @Test void handleRequestHandlesGetRequest() { when(httpRequest.method()).thenReturn(HttpMethods.GET.name()); when(sessionFactory.create(any())).thenReturn(mockSession); when(mockSession.getId()).thenReturn("1"); transportProvider.handleRequest(responseObserver); verify(httpRequest, times(1)).method(); ArgumentCaptor<ServerSentEvent> captor = ArgumentCaptor.forClass(ServerSentEvent.class); verify(responseObserver, times(1)).onNext(captor.capture()); ServerSentEvent evt = captor.getValue(); Assertions.assertEquals("endpoint", evt.getEvent()); Assertions.assertTrue(((String) evt.getData()).startsWith("/mcp/message?sessionId=")); } @Test void handleRequestHandlesPostRequest() { when(httpRequest.method()).thenReturn(HttpMethods.GET.name()); when(sessionFactory.create(any())).thenReturn(mockSession); when(mockSession.getId()).thenReturn("1"); when(httpRequest.parameter("sessionId")).thenReturn("1"); when(httpRequest.inputStream()) .thenReturn(new ByteArrayInputStream("{\"jsonrpc\":\"2.0\",\"method\":\"test\"}".getBytes())); when(mockSession.handle(any(McpSchema.JSONRPCMessage.class))).thenReturn(mock()); transportProvider.handleRequest(responseObserver); when(httpRequest.method()).thenReturn(HttpMethods.POST.name()); transportProvider.handleRequest(responseObserver); verify(httpRequest, times(3)).method(); verify(httpResponse).setStatus(HttpStatus.OK.getCode()); } @Test void handleRequestIgnoresUnsupportedMethods() { when(httpRequest.method()).thenReturn(HttpMethods.PUT.name()); transportProvider.handleRequest(responseObserver); verify(httpRequest, times(2)).method(); verifyNoInteractions(responseObserver); verifyNoInteractions(httpResponse); } @Test void handleMessageReturnsBadRequestWhenSessionIdIsMissing() { when(httpRequest.parameter("sessionId")).thenReturn(null); try { transportProvider.handleMessage(); } catch (Exception e) { Assertions.assertInstanceOf(HttpResultPayloadException.class, e); HttpResultPayloadException httpResultPayloadException = (HttpResultPayloadException) e; Assertions.assertEquals( HttpStatus.BAD_REQUEST.getCode(), httpResultPayloadException.getResult().getStatus()); } } @Test void handleMessageReturnsNotFoundForUnknownSessionId() { when(httpRequest.parameter("sessionId")).thenReturn("unknownSessionId"); try { transportProvider.handleMessage(); } catch (Exception e) { Assertions.assertInstanceOf(HttpResultPayloadException.class, e); HttpResultPayloadException httpResultPayloadException = (HttpResultPayloadException) e; Assertions.assertEquals( HttpStatus.NOT_FOUND.getCode(), httpResultPayloadException.getResult().getStatus()); } } @AfterEach public void tearDown() { if (rpcContextMockedStatic != null) { rpcContextMockedStatic.close(); } } }
DubboMcpSseTransportProviderTest
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/admin/internals/ApiRequestScope.java
{ "start": 893, "end": 1316 }
interface ____ used by {@link AdminApiDriver} to bridge the gap * to the internal `NodeProvider` defined in * {@link org.apache.kafka.clients.admin.KafkaAdminClient}. However, a * request scope is more than just a target broker specification. It also * provides a way to group key lookups according to different batching * mechanics. See {@link AdminApiLookupStrategy#lookupScope(Object)} for * more detail. */ public
is
java
google__dagger
hilt-core/main/java/dagger/hilt/internal/GeneratedComponentManager.java
{ "start": 806, "end": 875 }
interface ____<T> { T generatedComponent(); }
GeneratedComponentManager
java
quarkusio__quarkus
extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/QuartzBuildTimeConfig.java
{ "start": 1785, "end": 3791 }
class ____ of the thread pool implementation to use. * <p> * It's important to bear in mind that Quartz threads are not used to execute scheduled methods, instead the regular Quarkus * thread pool is used by default. See also {@code quarkus.quartz.run-blocking-scheduled-method-on-quartz-thread}. */ @WithDefault("org.quartz.simpl.SimpleThreadPool") String threadPoolClass(); /** * The name of the datasource to use. * <p> * Ignored if using a `ram` store i.e {@link StoreType#RAM}. * <p> * Optionally needed when using the `jdbc-tx` or `jdbc-cmt` store types. * If not specified, defaults to using the default datasource. */ @WithName("datasource") Optional<String> dataSourceName(); /** * If set to true, defers datasource check to runtime. * False by default. * <p> * Used in combination with runtime configuration {@link QuartzRuntimeConfig#deferredDatasourceName()}. * <p> * It is considered a configuration error to specify a datasource via {@link QuartzBuildTimeConfig#dataSourceName()} along * with setting this property to {@code true}. */ @WithDefault("false") boolean deferDatasourceCheck(); /** * The prefix for quartz job store tables. * <p> * Ignored if using a `ram` store i.e {@link StoreType#RAM} */ @WithDefault("QRTZ_") String tablePrefix(); /** * The SQL string that selects a row in the "LOCKS" table and places a lock on the row. * <p> * Ignored if using a `ram` store i.e {@link StoreType#RAM}. * <p> * If not set, the default value of Quartz applies, for which the "{0}" is replaced during run-time with the * `table-prefix`, the "{1}" with the `instance-name`. * <p> * An example SQL string `SELECT * FROM {0}LOCKS WHERE SCHED_NAME = {1} AND LOCK_NAME = ? FOR UPDATE` */ Optional<String> selectWithLockSql(); /** * Allows users to specify fully qualified
name
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/ApplicationClassLoader.java
{ "start": 5686, "end": 6311 }
class ____ this classloader's URLs. Note that this is like // the servlet spec, not the usual Java 2 behaviour where we ask the // parent to attempt to load first. try { c = findClass(name); if (LOG.isDebugEnabled() && c != null) { LOG.debug("Loaded class: " + name + " "); } } catch (ClassNotFoundException e) { if (LOG.isDebugEnabled()) { LOG.debug(e.toString()); } ex = e; } } if (c == null) { // try parent c = parent.loadClass(name); if (LOG.isDebugEnabled() && c != null) { LOG.debug("Loaded
from
java
quarkusio__quarkus
extensions/elytron-security-properties-file/runtime/src/main/java/io/quarkus/elytron/security/properties/runtime/MPRealmRuntimeConfig.java
{ "start": 731, "end": 2479 }
interface ____ { /** * If the passwords are stored in the property file as plain text, e.g. * {@code quarkus.security.users.embedded.users.alice=AlicesSecretPassword}. * If this is false (the default) then it is expected that passwords are hashed as per the {@code algorithm} config * property. */ @WithDefault("false") boolean plainText(); /** * The algorithm with which user password is hashed. The library expects a password prepended with the username and the * realm, * in the form ALG( username ":" realm ":" password ) in hexadecimal format. * <p> * For example, on a Unix-like system we can produce the expected hash for Alice logging in to the Quarkus realm with * password AlicesSecretPassword using {@code echo -n "alice:Quarkus:AlicesSecretPassword" | sha512sum}, and thus set * {@code quarkus.security.users.embedded.users.alice=c8131...4546} (full hash output abbreviated here). * This property is ignored if {@code plainText} is true. */ @WithDefault(DigestPassword.ALGORITHM_DIGEST_SHA_512) DigestAlgorithm algorithm(); /** * The realm users user1=password\nuser2=password2... mapping. * See <a href="#embedded-users">Embedded Users</a>. */ @ConfigDocDefault("none") Map<@WithConverter(TrimmedStringConverter.class) String, @WithConverter(TrimmedStringConverter.class) String> users(); /** * The realm roles user1=role1,role2,...\nuser2=role1,role2,... mapping * See <a href="#embedded-roles">Embedded Roles</a>. */ @ConfigDocDefault("none") Map<@WithConverter(TrimmedStringConverter.class) String, @WithConverter(TrimmedStringConverter.class) String> roles(); }
MPRealmRuntimeConfig
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/ExceptionInMultipleInputOperatorException.java
{ "start": 1268, "end": 1695 }
class ____ extends WrappingRuntimeException { private static final long serialVersionUID = 1L; public ExceptionInMultipleInputOperatorException(Throwable cause) { this("Could not forward element to next operator", cause); } public ExceptionInMultipleInputOperatorException(String message, Throwable cause) { super(message, requireNonNull(cause)); } }
ExceptionInMultipleInputOperatorException
java
netty__netty
codec-memcache/src/main/java/io/netty/handler/codec/memcache/binary/BinaryMemcacheRequest.java
{ "start": 864, "end": 1450 }
interface ____ extends BinaryMemcacheMessage { /** * Returns the reserved field value. * * @return the reserved field value. */ short reserved(); /** * Sets the reserved field value. * * @param reserved the reserved field value. */ BinaryMemcacheRequest setReserved(short reserved); @Override BinaryMemcacheRequest retain(); @Override BinaryMemcacheRequest retain(int increment); @Override BinaryMemcacheRequest touch(); @Override BinaryMemcacheRequest touch(Object hint); }
BinaryMemcacheRequest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestCapacitySchedulerMetrics.java
{ "start": 1980, "end": 2013 }
class ____ CS metrics. */ public
for
java
quarkusio__quarkus
integration-tests/gradle/src/main/resources/multi-module-named-injection/common/src/main/java/org/acme/common/health/HealthStatus.java
{ "start": 41, "end": 250 }
class ____ { private boolean healthy = true; public boolean isHealthy() { return healthy; } public void setHealthy(boolean healthy) { this.healthy = healthy; } }
HealthStatus
java
spring-projects__spring-security
oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJweEncoderTests.java
{ "start": 9004, "end": 13917 }
class ____ implements JwtEncoder { private static final String ENCODING_ERROR_MESSAGE_TEMPLATE = "An error occurred while attempting to encode the Jwt: %s"; private static final Converter<JweHeader, JWEHeader> JWE_HEADER_CONVERTER = new JweHeaderConverter(); private static final Converter<JwtClaimsSet, JWTClaimsSet> JWT_CLAIMS_SET_CONVERTER = new JwtClaimsSetConverter(); private final JWKSource<SecurityContext> jwkSource; private final JwtEncoder jwsEncoder; private NimbusJweEncoder(JWKSource<SecurityContext> jwkSource) { Assert.notNull(jwkSource, "jwkSource cannot be null"); this.jwkSource = jwkSource; this.jwsEncoder = new NimbusJwtEncoder(jwkSource); } @Override public Jwt encode(JwtEncoderParameters parameters) throws JwtEncodingException { Assert.notNull(parameters, "parameters cannot be null"); // @formatter:off // ********************** // Assume future API: // JwtEncoderParameters.getJweHeader() // ********************** // @formatter:on JweHeader jweHeader = DEFAULT_JWE_HEADER; // Assume this is accessed via // JwtEncoderParameters.getJweHeader() JwsHeader jwsHeader = parameters.getJwsHeader(); JwtClaimsSet claims = parameters.getClaims(); JWK jwk = selectJwk(jweHeader); jweHeader = addKeyIdentifierHeadersIfNecessary(jweHeader, jwk); JWEHeader jweHeader2 = JWE_HEADER_CONVERTER.convert(jweHeader); JWTClaimsSet jwtClaimsSet = JWT_CLAIMS_SET_CONVERTER.convert(claims); String payload; if (jwsHeader != null) { // Sign then encrypt Jwt jws = this.jwsEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims)); payload = jws.getTokenValue(); // @formatter:off jweHeader = JweHeader.from(jweHeader) .contentType("JWT") // Indicates Nested JWT (REQUIRED) .build(); // @formatter:on } else { // Encrypt only payload = jwtClaimsSet.toString(); } JWEObject jweObject = new JWEObject(jweHeader2, new Payload(payload)); try { // FIXME // Resolve type of JWEEncrypter using the JWK key type // For now, assuming RSA key type jweObject.encrypt(new RSAEncrypter(jwk.toRSAKey())); } catch (JOSEException ex) { throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to encrypt the JWT -> " + ex.getMessage()), ex); } String jwe = jweObject.serialize(); // NOTE: // For the Nested JWS use case, we lose access to the JWS Header in the // returned JWT. // If this is needed, we can simply add the new method Jwt.getNestedHeaders(). return new Jwt(jwe, claims.getIssuedAt(), claims.getExpiresAt(), jweHeader.getHeaders(), claims.getClaims()); } private JWK selectJwk(JweHeader headers) { List<JWK> jwks; try { JWKSelector jwkSelector = new JWKSelector(createJwkMatcher(headers)); jwks = this.jwkSource.get(jwkSelector, null); } catch (Exception ex) { throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK encryption key -> " + ex.getMessage()), ex); } if (jwks.size() > 1) { throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Found multiple JWK encryption keys for algorithm '" + headers.getAlgorithm().getName() + "'")); } if (jwks.isEmpty()) { throw new JwtEncodingException( String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK encryption key")); } return jwks.get(0); } private static JWKMatcher createJwkMatcher(JweHeader headers) { JWEAlgorithm jweAlgorithm = JWEAlgorithm.parse(headers.getAlgorithm().getName()); // @formatter:off return new JWKMatcher.Builder() .keyType(KeyType.forAlgorithm(jweAlgorithm)) .keyID(headers.getKeyId()) .keyUses(KeyUse.ENCRYPTION, null) .algorithms(jweAlgorithm, null) .x509CertSHA256Thumbprint(Base64URL.from(headers.getX509SHA256Thumbprint())) .build(); // @formatter:on } private static JweHeader addKeyIdentifierHeadersIfNecessary(JweHeader headers, JWK jwk) { // Check if headers have already been added if (StringUtils.hasText(headers.getKeyId()) && StringUtils.hasText(headers.getX509SHA256Thumbprint())) { return headers; } // Check if headers can be added from JWK if (!StringUtils.hasText(jwk.getKeyID()) && jwk.getX509CertSHA256Thumbprint() == null) { return headers; } JweHeader.Builder headersBuilder = JweHeader.from(headers); if (!StringUtils.hasText(headers.getKeyId()) && StringUtils.hasText(jwk.getKeyID())) { headersBuilder.keyId(jwk.getKeyID()); } if (!StringUtils.hasText(headers.getX509SHA256Thumbprint()) && jwk.getX509CertSHA256Thumbprint() != null) { headersBuilder.x509SHA256Thumbprint(jwk.getX509CertSHA256Thumbprint().toString()); } return headersBuilder.build(); } } private static
NimbusJweEncoder
java
apache__kafka
connect/mirror-client/src/main/java/org/apache/kafka/connect/mirror/Heartbeat.java
{ "start": 1262, "end": 5352 }
class ____ { public static final String SOURCE_CLUSTER_ALIAS_KEY = "sourceClusterAlias"; public static final String TARGET_CLUSTER_ALIAS_KEY = "targetClusterAlias"; public static final String TIMESTAMP_KEY = "timestamp"; public static final String VERSION_KEY = "version"; public static final short VERSION = 0; public static final Schema VALUE_SCHEMA_V0 = new Schema( new Field(TIMESTAMP_KEY, Type.INT64)); public static final Schema KEY_SCHEMA = new Schema( new Field(SOURCE_CLUSTER_ALIAS_KEY, Type.STRING), new Field(TARGET_CLUSTER_ALIAS_KEY, Type.STRING)); public static final Schema HEADER_SCHEMA = new Schema( new Field(VERSION_KEY, Type.INT16)); private final String sourceClusterAlias; private final String targetClusterAlias; private final long timestamp; public Heartbeat(String sourceClusterAlias, String targetClusterAlias, long timestamp) { this.sourceClusterAlias = sourceClusterAlias; this.targetClusterAlias = targetClusterAlias; this.timestamp = timestamp; } public String sourceClusterAlias() { return sourceClusterAlias; } public String targetClusterAlias() { return targetClusterAlias; } public long timestamp() { return timestamp; } @Override public String toString() { return String.format("Heartbeat{sourceClusterAlias=%s, targetClusterAlias=%s, timestamp=%d}", sourceClusterAlias, targetClusterAlias, timestamp); } ByteBuffer serializeValue(short version) { Schema valueSchema = valueSchema(version); Struct header = headerStruct(version); Struct value = valueStruct(valueSchema); ByteBuffer buffer = ByteBuffer.allocate(HEADER_SCHEMA.sizeOf(header) + valueSchema.sizeOf(value)); HEADER_SCHEMA.write(buffer, header); valueSchema.write(buffer, value); buffer.flip(); return buffer; } ByteBuffer serializeKey() { Struct struct = keyStruct(); ByteBuffer buffer = ByteBuffer.allocate(KEY_SCHEMA.sizeOf(struct)); KEY_SCHEMA.write(buffer, struct); buffer.flip(); return buffer; } public static Heartbeat deserializeRecord(ConsumerRecord<byte[], byte[]> record) { ByteBuffer value = ByteBuffer.wrap(record.value()); Struct headerStruct = HEADER_SCHEMA.read(value); short version = headerStruct.getShort(VERSION_KEY); Struct valueStruct = valueSchema(version).read(value); long timestamp = valueStruct.getLong(TIMESTAMP_KEY); Struct keyStruct = KEY_SCHEMA.read(ByteBuffer.wrap(record.key())); String sourceClusterAlias = keyStruct.getString(SOURCE_CLUSTER_ALIAS_KEY); String targetClusterAlias = keyStruct.getString(TARGET_CLUSTER_ALIAS_KEY); return new Heartbeat(sourceClusterAlias, targetClusterAlias, timestamp); } private Struct headerStruct(short version) { Struct struct = new Struct(HEADER_SCHEMA); struct.set(VERSION_KEY, version); return struct; } private Struct valueStruct(Schema schema) { Struct struct = new Struct(schema); struct.set(TIMESTAMP_KEY, timestamp); return struct; } private Struct keyStruct() { Struct struct = new Struct(KEY_SCHEMA); struct.set(SOURCE_CLUSTER_ALIAS_KEY, sourceClusterAlias); struct.set(TARGET_CLUSTER_ALIAS_KEY, targetClusterAlias); return struct; } Map<String, ?> connectPartition() { Map<String, Object> partition = new HashMap<>(); partition.put(SOURCE_CLUSTER_ALIAS_KEY, sourceClusterAlias); partition.put(TARGET_CLUSTER_ALIAS_KEY, targetClusterAlias); return partition; } byte[] recordKey() { return serializeKey().array(); } byte[] recordValue() { return serializeValue(VERSION).array(); } private static Schema valueSchema(short version) { assert version == 0; return VALUE_SCHEMA_V0; } }
Heartbeat
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedStructWithArrayEmbeddableTest.java
{ "start": 2836, "end": 17619 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { session.persist( new StructHolder( 1L, "XYZ", 10, "String \"<abc>A&B</abc>\"", EmbeddableWithArrayAggregate.createAggregate1() ) ); session.persist( new StructHolder( 2L, null, 20, "String 'abc'", EmbeddableWithArrayAggregate.createAggregate2() ) ); } ); } @AfterEach protected void cleanupTest(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testUpdate(SessionFactoryScope scope) { scope.inTransaction( session -> { StructHolder structHolder = session.find( StructHolder.class, 1L ); structHolder.setAggregate( EmbeddableWithArrayAggregate.createAggregate2() ); session.flush(); session.clear(); structHolder = session.find( StructHolder.class, 1L ); assertEquals( "XYZ", structHolder.struct.stringField ); assertArrayEquals( new Integer[]{ 10 }, structHolder.struct.simpleEmbeddable.integerField ); assertStructEquals( EmbeddableWithArrayAggregate.createAggregate2(), structHolder.getAggregate() ); } ); } @Test public void testFetch(SessionFactoryScope scope) { scope.inSession( session -> { List<StructHolder> structHolders = session.createQuery( "from StructHolder b where b.id = 1", StructHolder.class ).getResultList(); assertEquals( 1, structHolders.size() ); StructHolder structHolder = structHolders.get( 0 ); assertEquals( 1L, structHolder.getId() ); assertEquals( "XYZ", structHolder.struct.stringField ); assertArrayEquals( new Integer[]{ 10 }, structHolder.struct.simpleEmbeddable.integerField ); assertEquals( "String \"<abc>A&B</abc>\"", structHolder.struct.simpleEmbeddable.doubleNested.leaf[0].stringField ); assertStructEquals( EmbeddableWithArrayAggregate.createAggregate1(), structHolder.getAggregate() ); } ); } @Test public void testFetchNull(SessionFactoryScope scope) { scope.inSession( session -> { List<StructHolder> structHolders = session.createQuery( "from StructHolder b where b.id = 2", StructHolder.class ).getResultList(); assertEquals( 1, structHolders.size() ); StructHolder structHolder = structHolders.get( 0 ); assertEquals( 2L, structHolder.getId() ); assertNull( structHolder.struct.stringField ); assertArrayEquals( new Integer[]{ 20 }, structHolder.struct.simpleEmbeddable.integerField ); assertStructEquals( EmbeddableWithArrayAggregate.createAggregate2(), structHolder.getAggregate() ); } ); } @Test public void testDomainResult(SessionFactoryScope scope) { scope.inSession( session -> { List<TheStruct> structs = session.createQuery( "select b.struct from StructHolder b where b.id = 1", TheStruct.class ).getResultList(); assertEquals( 1, structs.size() ); TheStruct theStruct = structs.get( 0 ); assertEquals( "XYZ", theStruct.stringField ); assertArrayEquals( new Integer[]{ 10 }, theStruct.simpleEmbeddable.integerField ); assertEquals( "String \"<abc>A&B</abc>\"", theStruct.simpleEmbeddable.doubleNested.leaf[0].stringField ); assertStructEquals( EmbeddableWithArrayAggregate.createAggregate1(), theStruct.nested[0] ); } ); } @Test @SkipForDialect(dialectClass = OracleDialect.class, reason = "We have to use TABLE storage in this test because Oracle doesn't support LOBs in struct arrays, but TABLE is not indexed") public void testSelectionItems(SessionFactoryScope scope) { scope.inSession( session -> { List<Tuple> tuples = session.createQuery( "select " + "b.struct.nested[1].theInt," + "b.struct.nested[1].theDouble," + "b.struct.nested[1].theBoolean," + "b.struct.nested[1].theNumericBoolean," + "b.struct.nested[1].theStringBoolean," + "b.struct.nested[1].theString," + "b.struct.nested[1].theInteger," + "b.struct.nested[1].theUrl," + "b.struct.nested[1].theClob," + "b.struct.nested[1].theBinary," + "b.struct.nested[1].theDate," + "b.struct.nested[1].theTime," + "b.struct.nested[1].theTimestamp," + "b.struct.nested[1].theInstant," + "b.struct.nested[1].theUuid," + "b.struct.nested[1].gender," + "b.struct.nested[1].convertedGender," + "b.struct.nested[1].ordinalGender," + "b.struct.nested[1].theDuration," + "b.struct.nested[1].theLocalDateTime," + "b.struct.nested[1].theLocalDate," + "b.struct.nested[1].theLocalTime," + "b.struct.nested[1].theZonedDateTime," + "b.struct.nested[1].theOffsetDateTime," + "b.struct.nested[1].mutableValue," + "b.struct.simpleEmbeddable," + "b.struct.simpleEmbeddable.doubleNested," + "b.struct.simpleEmbeddable.doubleNested.leaf " + "from StructHolder b where b.id = 1", Tuple.class ).getResultList(); assertEquals( 1, tuples.size() ); final Tuple tuple = tuples.get( 0 ); final EmbeddableWithArrayAggregate struct = new EmbeddableWithArrayAggregate(); struct.setTheInt( tuple.get( 0, int[].class ) ); struct.setTheDouble( tuple.get( 1, double[].class ) ); struct.setTheBoolean( tuple.get( 2, Boolean[].class ) ); struct.setTheNumericBoolean( tuple.get( 3, Boolean[].class ) ); struct.setTheStringBoolean( tuple.get( 4, Boolean[].class ) ); struct.setTheString( tuple.get( 5, String[].class ) ); struct.setTheInteger( tuple.get( 6, Integer[].class ) ); struct.setTheUrl( tuple.get( 7, URL[].class ) ); struct.setTheClob( tuple.get( 8, String[].class ) ); struct.setTheBinary( tuple.get( 9, byte[][].class ) ); struct.setTheDate( tuple.get( 10, Date[].class ) ); struct.setTheTime( tuple.get( 11, Time[].class ) ); struct.setTheTimestamp( tuple.get( 12, Timestamp[].class ) ); struct.setTheInstant( tuple.get( 13, Instant[].class ) ); struct.setTheUuid( tuple.get( 14, UUID[].class ) ); struct.setGender( tuple.get( 15, EntityOfBasics.Gender[].class ) ); struct.setConvertedGender( tuple.get( 16, EntityOfBasics.Gender[].class ) ); struct.setOrdinalGender( tuple.get( 17, EntityOfBasics.Gender[].class ) ); struct.setTheDuration( tuple.get( 18, Duration[].class ) ); struct.setTheLocalDateTime( tuple.get( 19, LocalDateTime[].class ) ); struct.setTheLocalDate( tuple.get( 20, LocalDate[].class ) ); struct.setTheLocalTime( tuple.get( 21, LocalTime[].class ) ); struct.setTheZonedDateTime( tuple.get( 22, ZonedDateTime[].class ) ); struct.setTheOffsetDateTime( tuple.get( 23, OffsetDateTime[].class ) ); struct.setMutableValue( tuple.get( 24, MutableValue[].class ) ); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), struct ); SimpleEmbeddable simpleEmbeddable = tuple.get( 25, SimpleEmbeddable.class ); assertEquals( simpleEmbeddable.doubleNested, tuple.get( 26, DoubleNested.class ) ); assertArrayEquals( simpleEmbeddable.doubleNested.leaf, tuple.get( 27, Leaf[].class ) ); assertArrayEquals( new Integer[]{ 10 }, simpleEmbeddable.integerField ); assertEquals( "String \"<abc>A&B</abc>\"", simpleEmbeddable.doubleNested.leaf[0].stringField ); } ); } @Test public void testDeleteWhere(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "delete StructHolder b where b.struct is not null" ).executeUpdate(); assertNull( session.find( StructHolder.class, 1L ) ); } ); } @Test public void testUpdateAggregate(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "update StructHolder b set b.struct = null" ).executeUpdate(); assertNull( session.find( StructHolder.class, 1L ).getAggregate() ); } ); } @Test @FailureExpected(jiraKey = "HHH-18051") @SkipForDialect(dialectClass = OracleDialect.class, reason = "We have to use TABLE storage in this test because Oracle doesn't support LOBs in struct arrays, but TABLE is not indexed") public void testUpdateAggregateMember(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "update StructHolder b set b.struct.nested[1].theString = null" ).executeUpdate(); EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); struct.setTheString( null ); assertStructEquals( struct, session.find( StructHolder.class, 1L ).getAggregate() ); } ); } @Test @FailureExpected(jiraKey = "HHH-18051") @SkipForDialect(dialectClass = OracleDialect.class, reason = "We have to use TABLE storage in this test because Oracle doesn't support LOBs in struct arrays, but TABLE is not indexed") public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "update StructHolder b set b.struct.nested[1].theString = null, b.struct.nested[1].theUuid = null" ).executeUpdate(); EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); struct.setTheString( null ); struct.setTheUuid( null ); assertStructEquals( struct, session.find( StructHolder.class, 1L ).getAggregate() ); } ); } @Test @FailureExpected(jiraKey = "HHH-18051") @SkipForDialect(dialectClass = OracleDialect.class, reason = "We have to use TABLE storage in this test because Oracle doesn't support LOBs in struct arrays, but TABLE is not indexed") public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { scope.inTransaction( session -> { EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); session.createMutationQuery( "update StructHolder b set " + "b.struct.nested[1].theInt = :theInt," + "b.struct.nested[1].theDouble = :theDouble," + "b.struct.nested[1].theBoolean = :theBoolean," + "b.struct.nested[1].theNumericBoolean = :theNumericBoolean," + "b.struct.nested[1].theStringBoolean = :theStringBoolean," + "b.struct.nested[1].theString = :theString," + "b.struct.nested[1].theInteger = :theInteger," + "b.struct.nested[1].theUrl = :theUrl," + "b.struct.nested[1].theClob = :theClob," + "b.struct.nested[1].theBinary = :theBinary," + "b.struct.nested[1].theDate = :theDate," + "b.struct.nested[1].theTime = :theTime," + "b.struct.nested[1].theTimestamp = :theTimestamp," + "b.struct.nested[1].theInstant = :theInstant," + "b.struct.nested[1].theUuid = :theUuid," + "b.struct.nested[1].gender = :gender," + "b.struct.nested[1].convertedGender = :convertedGender," + "b.struct.nested[1].ordinalGender = :ordinalGender," + "b.struct.nested[1].theDuration = :theDuration," + "b.struct.nested[1].theLocalDateTime = :theLocalDateTime," + "b.struct.nested[1].theLocalDate = :theLocalDate," + "b.struct.nested[1].theLocalTime = :theLocalTime," + "b.struct.nested[1].theZonedDateTime = :theZonedDateTime," + "b.struct.nested[1].theOffsetDateTime = :theOffsetDateTime," + "b.struct.nested[1].mutableValue = :mutableValue," + "b.struct.simpleEmbeddable.integerField = :integerField " + "where b.id = 2" ) .setParameter( "theInt", struct.getTheInt() ) .setParameter( "theDouble", struct.getTheDouble() ) .setParameter( "theBoolean", struct.getTheBoolean() ) .setParameter( "theNumericBoolean", struct.getTheNumericBoolean() ) .setParameter( "theStringBoolean", struct.getTheStringBoolean() ) .setParameter( "theString", struct.getTheString() ) .setParameter( "theInteger", struct.getTheInteger() ) .setParameter( "theUrl", struct.getTheUrl() ) .setParameter( "theClob", struct.getTheClob() ) .setParameter( "theBinary", struct.getTheBinary() ) .setParameter( "theDate", struct.getTheDate() ) .setParameter( "theTime", struct.getTheTime() ) .setParameter( "theTimestamp", struct.getTheTimestamp() ) .setParameter( "theInstant", struct.getTheInstant() ) .setParameter( "theUuid", struct.getTheUuid() ) .setParameter( "gender", struct.getGender() ) .setParameter( "convertedGender", struct.getConvertedGender() ) .setParameter( "ordinalGender", struct.getOrdinalGender() ) .setParameter( "theDuration", struct.getTheDuration() ) .setParameter( "theLocalDateTime", struct.getTheLocalDateTime() ) .setParameter( "theLocalDate", struct.getTheLocalDate() ) .setParameter( "theLocalTime", struct.getTheLocalTime() ) .setParameter( "theZonedDateTime", struct.getTheZonedDateTime() ) .setParameter( "theOffsetDateTime", struct.getTheOffsetDateTime() ) .setParameter( "mutableValue", struct.getMutableValue() ) .setParameter( "integerField", new Integer[]{ 5 } ) .executeUpdate(); StructHolder structHolder = session.find( StructHolder.class, 2L ); assertArrayEquals( new Integer[]{ 5 }, structHolder.struct.simpleEmbeddable.integerField ); assertStructEquals( EmbeddableWithArrayAggregate.createAggregate1(), structHolder.getAggregate() ); } ); } @Test public void testNativeQuery(SessionFactoryScope scope) { scope.inTransaction( session -> { //noinspection unchecked List<Object> resultList = session.createNativeQuery( "select b.struct from StructHolder b where b.id = 1", Object.class ) .getResultList(); assertEquals( 1, resultList.size() ); assertInstanceOf( TheStruct.class, resultList.get( 0 ) ); TheStruct theStruct = (TheStruct) resultList.get( 0 ); assertEquals( "XYZ", theStruct.stringField ); assertArrayEquals( new Integer[]{ 10 }, theStruct.simpleEmbeddable.integerField ); assertEquals( "String \"<abc>A&B</abc>\"", theStruct.simpleEmbeddable.doubleNested.leaf[0].stringField ); assertStructEquals( EmbeddableWithArrayAggregate.createAggregate1(), theStruct.nested[0] ); } ); } private static void assertStructEquals(EmbeddableWithArrayAggregate struct, EmbeddableWithArrayAggregate struct2) { assertArrayEquals( struct.getTheBinary(), struct2.getTheBinary() ); assertArrayEquals( struct.getTheString(), struct2.getTheString() ); assertArrayEquals( struct.getTheLocalDateTime(), struct2.getTheLocalDateTime() ); assertArrayEquals( struct.getTheUuid(), struct2.getTheUuid() ); } @Entity(name = "StructHolder") public static
NestedStructWithArrayEmbeddableTest
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/snapshots/SnapshotStressTestsIT.java
{ "start": 69868, "end": 78841 }
class ____ { private final Semaphore permits = new Semaphore(Integer.MAX_VALUE); private final String indexName; // these fields are only changed when all permits held by the delete/recreate process: private int shardCount; private Semaphore docPermits; private TrackedIndex(String indexName) { this.indexName = indexName; } @Override public String toString() { return "TrackedIndex[" + indexName + "]"; } public void start() { try (TransferableReleasables localReleasables = new TransferableReleasables()) { assertNotNull(localReleasables.add(blockNodeRestarts())); assertNotNull(localReleasables.add(tryAcquireAllPermits(permits))); createIndexAndContinue(localReleasables.transfer()); } } private void createIndexAndContinue(Releasable releasable) { shardCount = between(1, 5); docPermits = new Semaphore(between(1000, 3000)); logger.info("--> create index [{}] with max [{}] docs", indexName, docPermits.availablePermits()); indicesAdmin().prepareCreate(indexName) .setSettings(indexSettings(shardCount, between(0, cluster.numDataNodes() - 1))) .execute(mustSucceed(response -> { assertTrue(response.isAcknowledged()); logger.info("--> finished create index [{}]", indexName); Releasables.close(releasable); scheduleIndexingAndPossibleDelete(); })); } private void scheduleIndexingAndPossibleDelete() { enqueueAction(() -> { boolean forked = false; try (TransferableReleasables localReleasables = new TransferableReleasables()) { if (localReleasables.add(blockNodeRestarts()) == null) { return; } if (usually()) { // index some more docs if (localReleasables.add(tryAcquirePermit(permits)) == null) { return; } final int maxDocCount = docPermits.drainPermits(); assert maxDocCount >= 0 : maxDocCount; if (maxDocCount == 0) { return; } final int docCount = between(1, Math.min(maxDocCount, 200)); docPermits.release(maxDocCount - docCount); final Releasable releaseAll = localReleasables.transfer(); final ListenableFuture<ClusterHealthResponse> ensureYellowStep = new ListenableFuture<>(); logger.info("--> waiting for yellow health of [{}] prior to indexing [{}] docs", indexName, docCount); prepareClusterHealthRequest(indexName).setWaitForYellowStatus().execute(ensureYellowStep); final ListenableFuture<BulkResponse> bulkStep = new ListenableFuture<>(); ensureYellowStep.addListener(mustSucceed(clusterHealthResponse -> { assertFalse( "timed out waiting for yellow state of [" + indexName + "]", clusterHealthResponse.isTimedOut() ); final BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(indexName); logger.info("--> indexing [{}] docs into [{}]", docCount, indexName); for (int i = 0; i < docCount; i++) { bulkRequestBuilder.add( new IndexRequest().source( jsonBuilder().startObject().field("field-" + between(1, 5), randomAlphaOfLength(10)).endObject() ) ); } bulkRequestBuilder.execute(bulkStep); })); bulkStep.addListener(mustSucceed(bulkItemResponses -> { for (BulkItemResponse bulkItemResponse : bulkItemResponses.getItems()) { assertNull(bulkItemResponse.getFailure()); } logger.info("--> indexing into [{}] finished", indexName); Releasables.close(releaseAll); scheduleIndexingAndPossibleDelete(); })); forked = true; } else if (localReleasables.add(tryAcquireAllPermits(permits)) != null) { // delete the index and create a new one final Releasable releaseAll = localReleasables.transfer(); logger.info("--> deleting index [{}]", indexName); indicesAdmin().prepareDelete(indexName).execute(mustSucceed(acknowledgedResponse -> { logger.info("--> deleting index [{}] finished", indexName); assertTrue(acknowledgedResponse.isAcknowledged()); createIndexAndContinue(releaseAll); })); forked = true; } } finally { if (forked == false) { scheduleIndexingAndPossibleDelete(); } } }); } /** * We must not close an index while it's being partially snapshotted; this counter tracks the number of ongoing * close operations (positive) or partial snapshot operations (negative) in order to avoid them happening concurrently. * <p> * This is only a problem for partial snapshots because we release the index permit once a partial snapshot has started. With * non-partial snapshots we retain the index permit until it completes which blocks other operations. */ private final AtomicInteger closingOrPartialSnapshottingCount = new AtomicInteger(); private static boolean closingPermitAvailable(int value) { return value >= 0 && value != Integer.MAX_VALUE; } private static boolean partialSnapshottingPermitAvailable(int value) { return value <= 0 && value != Integer.MIN_VALUE; } Releasable tryAcquireClosingPermit() { final var previous = closingOrPartialSnapshottingCount.getAndUpdate(c -> closingPermitAvailable(c) ? c + 1 : c); if (closingPermitAvailable(previous)) { return () -> assertThat(closingOrPartialSnapshottingCount.getAndDecrement(), greaterThan(0)); } else { return null; } } Releasable tryAcquirePartialSnapshottingPermit() { final var previous = closingOrPartialSnapshottingCount.getAndUpdate(c -> partialSnapshottingPermitAvailable(c) ? c - 1 : c); if (partialSnapshottingPermitAvailable(previous)) { return () -> assertThat(closingOrPartialSnapshottingCount.getAndIncrement(), lessThan(0)); } else { return null; } } } } // Prepares a health request with twice the default (30s) timeout that waits for all cluster tasks to finish as well as all cluster // nodes before returning private static ClusterHealthRequestBuilder prepareClusterHealthRequest(String... targetIndexNames) { return clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT, targetIndexNames) .setTimeout(TimeValue.timeValueSeconds(60)) .setWaitForNodes(Integer.toString(internalCluster().getNodeNames().length)) .setWaitForEvents(Priority.LANGUID); } private static String stringFromSnapshotInfo(SnapshotInfo snapshotInfo) { return Strings.toString((b, p) -> snapshotInfo.toXContent(b, SNAPSHOT_ONLY_FORMAT_PARAMS), true, false); } /** * A client to a node that is blocked from restarting; close this {@link Releasable} to release the block. */ private static
TrackedIndex
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ser/impl/ObjectIdWriter.java
{ "start": 300, "end": 2789 }
class ____ { public final JavaType idType; /** * Name of id property to write, if not null: if null, should * only write references, but id property is handled by some * other entity. */ public final SerializableString propertyName; /** * Blueprint generator instance: actual instance will be * fetched from {@link SerializationContext} using this as * the key. */ public final ObjectIdGenerator<?> generator; /** * Serializer used for serializing id values. */ public final ValueSerializer<Object> serializer; /** * Marker that indicates what the first reference is to be * serialized as full POJO, or as Object Id (other references * will always be serialized as Object Id) * * @since 2.1 */ public final boolean alwaysAsId; /* /********************************************************** /* Life-cycle /********************************************************** */ @SuppressWarnings("unchecked") protected ObjectIdWriter(JavaType t, SerializableString propName, ObjectIdGenerator<?> gen, ValueSerializer<?> ser, boolean alwaysAsId) { idType = t; propertyName = propName; generator = gen; serializer = (ValueSerializer<Object>) ser; this.alwaysAsId = alwaysAsId; } /** * Factory method called by {@link tools.jackson.databind.ser.bean.BeanSerializerBase} * with the initial information based on standard settings for the type * for which serializer is being built. * * @since 2.3 */ public static ObjectIdWriter construct(JavaType idType, PropertyName propName, ObjectIdGenerator<?> generator, boolean alwaysAsId) { String simpleName = (propName == null) ? null : propName.getSimpleName(); SerializableString serName = (simpleName == null) ? null : new SerializedString(simpleName); return new ObjectIdWriter(idType, serName, generator, null, alwaysAsId); } public ObjectIdWriter withSerializer(ValueSerializer<?> ser) { return new ObjectIdWriter(idType, propertyName, generator, ser, alwaysAsId); } /** * @since 2.1 */ public ObjectIdWriter withAlwaysAsId(boolean newState) { if (newState == alwaysAsId) { return this; } return new ObjectIdWriter(idType, propertyName, generator, serializer, newState); } }
ObjectIdWriter
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/reflect/exception/InstantiationException.java
{ "start": 763, "end": 1147 }
class ____ extends RuntimeException { /** * @param message The message * @param cause The throwable */ public InstantiationException(String message, Throwable cause) { super(message, cause); } /** * @param message The message */ public InstantiationException(String message) { super(message); } }
InstantiationException
java
bumptech__glide
annotation/compiler/src/main/java/com/bumptech/glide/annotation/compiler/IndexerGenerator.java
{ "start": 1312, "end": 1527 }
class ____ a GlideExtension looks like this: * * <pre> * <code> * {@literal @com.bumptech.glide.annotation.compiler.Index(} * extensions = "com.bumptech.glide.integration.gif.GifOptions" * ) * public
with
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimeProcessor.java
{ "start": 742, "end": 1900 }
class ____ extends BinaryProcessor { private final ZoneId zoneId; public BinaryDateTimeProcessor(Processor source1, Processor source2, ZoneId zoneId) { super(source1, source2); this.zoneId = zoneId; } public BinaryDateTimeProcessor(StreamInput in) throws IOException { super(in); zoneId = SqlStreamInput.asSqlStream(in).zoneId(); } @Override protected void doWrite(StreamOutput out) throws IOException {} ZoneId zoneId() { return zoneId; } @Override protected abstract Object doProcess(Object left, Object right); @Override public int hashCode() { return Objects.hash(left(), right(), zoneId); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } BinaryDateTimeProcessor other = (BinaryDateTimeProcessor) obj; return Objects.equals(left(), other.left()) && Objects.equals(right(), other.right()) && Objects.equals(zoneId(), other.zoneId()); } }
BinaryDateTimeProcessor
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/SpringJmxEndpointInjectBeanTest.java
{ "start": 1520, "end": 2678 }
class ____ extends SpringTestSupport { @Override protected boolean useJmx() { return true; } @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/spring/management/SpringJmxEndpointInjectBeanTest.xml"); } protected MBeanServer getMBeanServer() { return context.getManagementStrategy().getManagementAgent().getMBeanServer(); } @Test public void testJmxEndpointInjectBean() throws Exception { MBeanServer mbeanServer = getMBeanServer(); ObjectName on = getCamelObjectName(TYPE_COMPONENT, "seda"); assertTrue(mbeanServer.isRegistered(on)); on = getCamelObjectName(TYPE_ENDPOINT, "seda://foo"); assertTrue(mbeanServer.isRegistered(on)); String uri = (String) mbeanServer.getAttribute(on, "EndpointUri"); assertEquals("seda://foo", uri); getMockEndpoint("mock:result").expectedBodiesReceived("Hello World"); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } }
SpringJmxEndpointInjectBeanTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/crypto/CipherSuite.java
{ "start": 1089, "end": 3089 }
enum ____ { UNKNOWN("Unknown", 0), AES_CTR_NOPADDING("AES/CTR/NoPadding", 16), SM4_CTR_NOPADDING("SM4/CTR/NoPadding", 16); private final String name; private final int algoBlockSize; private Integer unknownValue = null; CipherSuite(String name, int algoBlockSize) { this.name = name; this.algoBlockSize = algoBlockSize; } public void setUnknownValue(int unknown) { this.unknownValue = unknown; } public int getUnknownValue() { return unknownValue; } /** * @return name of cipher suite, as in {@link javax.crypto.Cipher} */ public String getName() { return name; } /** * @return size of an algorithm block in bytes */ public int getAlgorithmBlockSize() { return algoBlockSize; } @Override public String toString() { StringBuilder builder = new StringBuilder("{"); builder.append("name: " + name) .append(", algorithmBlockSize: " + algoBlockSize); if (unknownValue != null) { builder.append(", unknownValue: " + unknownValue); } builder.append("}"); return builder.toString(); } /** * Convert to CipherSuite from name, {@link #algoBlockSize} is fixed for * certain cipher suite, just need to compare the name. * @param name cipher suite name * @return CipherSuite cipher suite */ public static CipherSuite convert(String name) { CipherSuite[] suites = CipherSuite.values(); for (CipherSuite suite : suites) { if (suite.getName().equals(name)) { return suite; } } throw new IllegalArgumentException("Invalid cipher suite name: " + name); } /** * Returns suffix of cipher suite configuration. * @return String configuration suffix */ public String getConfigSuffix() { String[] parts = name.split("/"); StringBuilder suffix = new StringBuilder(); for (String part : parts) { suffix.append(".").append(StringUtils.toLowerCase(part)); } return suffix.toString(); } }
CipherSuite
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ExplicitArrayForVarargsTest.java
{ "start": 2131, "end": 2539 }
class ____ { List<Object[]> test() { return Arrays.asList(new Object[] {1, 2}, new Object[] {3, 4}); } } """) .doTest(); } @Test public void emptyInitializers() { helper .addSourceLines( "Test.java", """ import java.util.Arrays; import java.util.List;
Test
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/jdk/NumberSerTest.java
{ "start": 1503, "end": 1642 }
class ____ { public BigDecimal value; public BigDecimalWrapper(BigDecimal v) { value = v; } } static
BigDecimalWrapper
java
google__dagger
javatests/dagger/functional/basic/ComponentMethodTest.java
{ "start": 1146, "end": 1206 }
class ____ { @Inject Dep3() {} } @Component
Dep3
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/query/CombinedFieldsQueryBuilder.java
{ "start": 14837, "end": 15124 }
class ____ { final MappedFieldType fieldType; final float boost; FieldAndBoost(MappedFieldType fieldType, float boost) { this.fieldType = Objects.requireNonNull(fieldType); this.boost = boost; } } private static
FieldAndBoost
java
apache__avro
lang/java/mapred/src/test/java/org/apache/avro/mapred/TestAvroMultipleInputs.java
{ "start": 5059, "end": 8660 }
class ____ extends AvroReducer<KeyRecord, JoinableRecord, CompleteRecord> { @Override public void reduce(KeyRecord ID, Iterable<JoinableRecord> joinables, AvroCollector<CompleteRecord> collector, Reporter reporter) throws IOException { CompleteRecord rec = new CompleteRecord(); for (JoinableRecord joinable : joinables) { rec.setId(joinable.id); if (joinable.recType.toString().contains("NamesRecord")) { rec.setName(joinable.name); } else { rec.setBalance(joinable.balance); } } collector.collect(rec); } } @Test void job() throws Exception { JobConf job = new JobConf(); Path inputPath1 = new Path(INPUT_DIR_1.getPath()); Path inputPath2 = new Path(INPUT_DIR_2.getPath()); Path outputPath = new Path(OUTPUT_DIR.getPath()); outputPath.getFileSystem(job).delete(outputPath, true); writeNamesFiles(new File(inputPath1.toUri().getPath())); writeBalancesFiles(new File(inputPath2.toUri().getPath())); job.setJobName("multiple-inputs-join"); AvroMultipleInputs.addInputPath(job, inputPath1, NamesMapImpl.class, ReflectData.get().getSchema(NamesRecord.class)); AvroMultipleInputs.addInputPath(job, inputPath2, BalancesMapImpl.class, ReflectData.get().getSchema(BalancesRecord.class)); Schema keySchema = ReflectData.get().getSchema(KeyRecord.class); Schema valueSchema = ReflectData.get().getSchema(JoinableRecord.class); AvroJob.setMapOutputSchema(job, Pair.getPairSchema(keySchema, valueSchema)); AvroJob.setOutputSchema(job, ReflectData.get().getSchema(CompleteRecord.class)); AvroJob.setReducerClass(job, ReduceImpl.class); job.setNumReduceTasks(1); FileOutputFormat.setOutputPath(job, outputPath); AvroJob.setReflect(job); JobClient.runJob(job); validateCompleteFile(new File(OUTPUT_DIR, "part-00000.avro")); } /** * Writes a "names.avro" file with five sequential <id, name> pairs. */ private void writeNamesFiles(File dir) throws IOException { DatumWriter<NamesRecord> writer = new ReflectDatumWriter<>(); File namesFile = new File(dir + "/names.avro"); try (DataFileWriter<NamesRecord> out = new DataFileWriter<>(writer)) { out.create(ReflectData.get().getSchema(NamesRecord.class), namesFile); for (int i = 0; i < 5; i++) { out.append(new NamesRecord(i, "record" + i)); } } } /** * Writes a "balances.avro" file with five sequential <id, balance> pairs. */ private void writeBalancesFiles(File dir) throws IOException { DatumWriter<BalancesRecord> writer = new ReflectDatumWriter<>(); File namesFile = new File(dir + "/balances.avro"); try (DataFileWriter<BalancesRecord> out = new DataFileWriter<>(writer)) { out.create(ReflectData.get().getSchema(BalancesRecord.class), namesFile); for (int i = 0; i < 5; i++) { out.append(new BalancesRecord(i, (long) i + 100)); } } } private void validateCompleteFile(File file) throws Exception { DatumReader<CompleteRecord> reader = new ReflectDatumReader<>(); int numRecs = 0; try (InputStream in = new BufferedInputStream(new FileInputStream(file))) { try (DataFileStream<CompleteRecord> records = new DataFileStream<>(in, reader)) { for (CompleteRecord rec : records) { assertEquals(rec.id, numRecs); assertEquals(rec.balance - 100, rec.id); assertEquals(rec.name, "record" + rec.id); numRecs++; } } } assertEquals(5, numRecs); } }
ReduceImpl
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/ValuesBytesRefAggregatorFunction.java
{ "start": 1001, "end": 6028 }
class ____ implements AggregatorFunction { private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of( new IntermediateStateDesc("values", ElementType.BYTES_REF) ); private final DriverContext driverContext; private final ValuesBytesRefAggregator.SingleState state; private final List<Integer> channels; public ValuesBytesRefAggregatorFunction(DriverContext driverContext, List<Integer> channels, ValuesBytesRefAggregator.SingleState state) { this.driverContext = driverContext; this.channels = channels; this.state = state; } public static ValuesBytesRefAggregatorFunction create(DriverContext driverContext, List<Integer> channels) { return new ValuesBytesRefAggregatorFunction(driverContext, channels, ValuesBytesRefAggregator.initSingle(driverContext.bigArrays())); } public static List<IntermediateStateDesc> intermediateStateDesc() { return INTERMEDIATE_STATE_DESC; } @Override public int intermediateBlockCount() { return INTERMEDIATE_STATE_DESC.size(); } @Override public void addRawInput(Page page, BooleanVector mask) { if (mask.allFalse()) { // Entire page masked away } else if (mask.allTrue()) { addRawInputNotMasked(page); } else { addRawInputMasked(page, mask); } } private void addRawInputMasked(Page page, BooleanVector mask) { BytesRefBlock vBlock = page.getBlock(channels.get(0)); BytesRefVector vVector = vBlock.asVector(); if (vVector == null) { addRawBlock(vBlock, mask); return; } addRawVector(vVector, mask); } private void addRawInputNotMasked(Page page) { BytesRefBlock vBlock = page.getBlock(channels.get(0)); BytesRefVector vVector = vBlock.asVector(); if (vVector == null) { addRawBlock(vBlock); return; } addRawVector(vVector); } private void addRawVector(BytesRefVector vVector) { BytesRef vScratch = new BytesRef(); for (int valuesPosition = 0; valuesPosition < vVector.getPositionCount(); valuesPosition++) { BytesRef vValue = vVector.getBytesRef(valuesPosition, vScratch); ValuesBytesRefAggregator.combine(state, vValue); } } private void addRawVector(BytesRefVector vVector, BooleanVector mask) { BytesRef vScratch = new BytesRef(); for (int valuesPosition = 0; valuesPosition < vVector.getPositionCount(); valuesPosition++) { if (mask.getBoolean(valuesPosition) == false) { continue; } BytesRef vValue = vVector.getBytesRef(valuesPosition, vScratch); ValuesBytesRefAggregator.combine(state, vValue); } } private void addRawBlock(BytesRefBlock vBlock) { BytesRef vScratch = new BytesRef(); for (int p = 0; p < vBlock.getPositionCount(); p++) { int vValueCount = vBlock.getValueCount(p); if (vValueCount == 0) { continue; } int vStart = vBlock.getFirstValueIndex(p); int vEnd = vStart + vValueCount; for (int vOffset = vStart; vOffset < vEnd; vOffset++) { BytesRef vValue = vBlock.getBytesRef(vOffset, vScratch); ValuesBytesRefAggregator.combine(state, vValue); } } } private void addRawBlock(BytesRefBlock vBlock, BooleanVector mask) { BytesRef vScratch = new BytesRef(); for (int p = 0; p < vBlock.getPositionCount(); p++) { if (mask.getBoolean(p) == false) { continue; } int vValueCount = vBlock.getValueCount(p); if (vValueCount == 0) { continue; } int vStart = vBlock.getFirstValueIndex(p); int vEnd = vStart + vValueCount; for (int vOffset = vStart; vOffset < vEnd; vOffset++) { BytesRef vValue = vBlock.getBytesRef(vOffset, vScratch); ValuesBytesRefAggregator.combine(state, vValue); } } } @Override public void addIntermediateInput(Page page) { assert channels.size() == intermediateBlockCount(); assert page.getBlockCount() >= channels.get(0) + intermediateStateDesc().size(); Block valuesUncast = page.getBlock(channels.get(0)); if (valuesUncast.areAllValuesNull()) { return; } BytesRefBlock values = (BytesRefBlock) valuesUncast; assert values.getPositionCount() == 1; BytesRef valuesScratch = new BytesRef(); ValuesBytesRefAggregator.combineIntermediate(state, values); } @Override public void evaluateIntermediate(Block[] blocks, int offset, DriverContext driverContext) { state.toIntermediate(blocks, offset, driverContext); } @Override public void evaluateFinal(Block[] blocks, int offset, DriverContext driverContext) { blocks[offset] = ValuesBytesRefAggregator.evaluateFinal(state, driverContext); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append("["); sb.append("channels=").append(channels); sb.append("]"); return sb.toString(); } @Override public void close() { state.close(); } }
ValuesBytesRefAggregatorFunction
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/asm/LoopTest.java
{ "start": 1185, "end": 1804 }
class ____ { private int id; private String name; private Department department; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } } }
Employee
java
quarkusio__quarkus
extensions/redis-client/runtime/src/main/java/io/quarkus/redis/runtime/datasource/RedisCommandExecutor.java
{ "start": 176, "end": 361 }
interface ____ { default Uni<Response> execute(RedisCommand cmd) { return execute(cmd.toRequest()); } Uni<Response> execute(Request toRequest); }
RedisCommandExecutor
java
quarkusio__quarkus
extensions/mutiny/runtime/src/main/java/io/quarkus/mutiny/runtime/ContextualRunnableScheduledFuture.java
{ "start": 301, "end": 1903 }
class ____<V> implements RunnableScheduledFuture<V> { private final RunnableScheduledFuture<V> runnable; private final Object context; private final ContextHandler<Object> contextHandler; public ContextualRunnableScheduledFuture(ContextHandler<Object> contextHandler, Object context, RunnableScheduledFuture<V> runnable) { this.contextHandler = contextHandler; this.context = context; this.runnable = runnable; } @Override public boolean isPeriodic() { return runnable.isPeriodic(); } @Override public long getDelay(TimeUnit unit) { return runnable.getDelay(unit); } @Override public int compareTo(Delayed o) { return runnable.compareTo(o); } @Override public void run() { if (contextHandler != null) { contextHandler.runWith(runnable, context); } else { runnable.run(); } } @Override public boolean cancel(boolean mayInterruptIfRunning) { return runnable.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return runnable.isCancelled(); } @Override public boolean isDone() { return runnable.isDone(); } @Override public V get() throws InterruptedException, ExecutionException { return runnable.get(); } @Override public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return runnable.get(timeout, unit); } }
ContextualRunnableScheduledFuture
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java
{ "start": 12857, "end": 13289 }
enum ____ custom enum // with values defined as static fields. Resulting value still needs // to be checked, hence we don't return it right away. try { Field enumField = requiredType.getField(trimmedValue); ReflectionUtils.makeAccessible(enumField); convertedValue = enumField.get(null); } catch (Throwable ex) { if (logger.isTraceEnabled()) { logger.trace("Field [" + convertedValue + "] isn't an
or
java
quarkusio__quarkus
extensions/panache/mongodb-panache/runtime/src/main/java/io/quarkus/mongodb/panache/reactive/ReactivePanacheMongoEntity.java
{ "start": 209, "end": 666 }
class ____ gain the ID field and auto-generated accessors * to all their public fields, as well as all the useful methods from {@link ReactivePanacheMongoEntityBase}. * * If you want a custom ID type or strategy, you can directly extend {@link ReactivePanacheMongoEntityBase} * instead, and write your own ID field. You will still get auto-generated accessors and * all the useful methods. * * @see ReactivePanacheMongoEntityBase */ public abstract
they
java
spring-projects__spring-boot
module/spring-boot-graphql-test/src/test/java/org/springframework/boot/graphql/test/autoconfigure/tester/GraphQlTesterAutoConfigurationTests.java
{ "start": 2082, "end": 2236 }
class ____ { @Bean ExecutionGraphQlService graphQlService() { return mock(ExecutionGraphQlService.class); } } }
CustomGraphQlServiceConfiguration
java
apache__dubbo
dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java
{ "start": 1965, "end": 14054 }
class ____ { @BeforeEach public void beforeEach() { DubboBootstrap.reset(); SysProps.clear(); SysProps.setProperty("dubbo.metrics.enabled", "false"); SysProps.setProperty("dubbo.metrics.protocol", "disabled"); } @AfterEach public void afterEach() { SysProps.clear(); DubboBootstrap.reset(); } @Test void testName() { ApplicationConfig application = new ApplicationConfig(); application.setName("app"); assertThat(application.getName(), equalTo("app")); assertThat(application.getId(), equalTo(null)); application = new ApplicationConfig("app2"); assertThat(application.getName(), equalTo("app2")); assertThat(application.getId(), equalTo(null)); Map<String, String> parameters = new HashMap<String, String>(); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry(APPLICATION_KEY, "app2")); } @Test void testVersion() { ApplicationConfig application = new ApplicationConfig("app"); application.setVersion("1.0.0"); assertThat(application.getVersion(), equalTo("1.0.0")); Map<String, String> parameters = new HashMap<String, String>(); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry("application.version", "1.0.0")); } @Test void testOwner() { ApplicationConfig application = new ApplicationConfig("app"); application.setOwner("owner"); assertThat(application.getOwner(), equalTo("owner")); } @Test void testOrganization() { ApplicationConfig application = new ApplicationConfig("app"); application.setOrganization("org"); assertThat(application.getOrganization(), equalTo("org")); } @Test void testArchitecture() { ApplicationConfig application = new ApplicationConfig("app"); application.setArchitecture("arch"); assertThat(application.getArchitecture(), equalTo("arch")); } @Test void testEnvironment1() { ApplicationConfig application = new ApplicationConfig("app"); application.setEnvironment("develop"); assertThat(application.getEnvironment(), equalTo("develop")); application.setEnvironment("test"); assertThat(application.getEnvironment(), equalTo("test")); application.setEnvironment("product"); assertThat(application.getEnvironment(), equalTo("product")); } @Test void testEnvironment2() { Assertions.assertThrows(IllegalStateException.class, () -> { ApplicationConfig application = new ApplicationConfig("app"); application.setEnvironment("illegal-env"); }); } @Test void testRegistry() { ApplicationConfig application = new ApplicationConfig("app"); RegistryConfig registry = new RegistryConfig(); application.setRegistry(registry); assertThat(application.getRegistry(), sameInstance(registry)); application.setRegistries(Collections.singletonList(registry)); assertThat(application.getRegistries(), contains(registry)); assertThat(application.getRegistries(), hasSize(1)); } @Test void testMonitor() { ApplicationConfig application = new ApplicationConfig("app"); application.setMonitor(new MonitorConfig("monitor-addr")); assertThat(application.getMonitor().getAddress(), equalTo("monitor-addr")); application.setMonitor("monitor-addr"); assertThat(application.getMonitor().getAddress(), equalTo("monitor-addr")); } @Test void testLogger() { ApplicationConfig application = new ApplicationConfig("app"); application.setLogger("log4j2"); assertThat(application.getLogger(), equalTo("log4j2")); } @Test void testDefault() { ApplicationConfig application = new ApplicationConfig("app"); application.setDefault(true); assertThat(application.isDefault(), is(true)); } @Test void testDumpDirectory() { ApplicationConfig application = new ApplicationConfig("app"); application.setDumpDirectory("/dump"); assertThat(application.getDumpDirectory(), equalTo("/dump")); Map<String, String> parameters = new HashMap<String, String>(); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry(DUMP_DIRECTORY, "/dump")); } @Test void testQosEnable() { ApplicationConfig application = new ApplicationConfig("app"); application.setQosEnable(true); assertThat(application.getQosEnable(), is(true)); Map<String, String> parameters = new HashMap<String, String>(); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry(QOS_ENABLE, "true")); } @Test void testQosPort() { ApplicationConfig application = new ApplicationConfig("app"); application.setQosPort(8080); assertThat(application.getQosPort(), equalTo(8080)); } @Test void testQosAcceptForeignIp() { ApplicationConfig application = new ApplicationConfig("app"); application.setQosAcceptForeignIp(true); assertThat(application.getQosAcceptForeignIp(), is(true)); Map<String, String> parameters = new HashMap<String, String>(); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry(ACCEPT_FOREIGN_IP, "true")); } @Test void testParameters() throws Exception { ApplicationConfig application = new ApplicationConfig("app"); application.setQosAcceptForeignIp(true); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("k1", "v1"); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry("k1", "v1")); assertThat(parameters, hasEntry(ACCEPT_FOREIGN_IP, "true")); } @Test void testAppendEnvironmentProperties() { ApplicationConfig application = new ApplicationConfig("app"); SysProps.setProperty("dubbo.labels", "tag1=value1;tag2=value2 ; tag3 = value3"); application.refresh(); Map<String, String> parameters = application.getParameters(); Assertions.assertEquals("value1", parameters.get("tag1")); Assertions.assertEquals("value2", parameters.get("tag2")); Assertions.assertEquals("value3", parameters.get("tag3")); ApplicationConfig application1 = new ApplicationConfig("app"); SysProps.setProperty("dubbo.env.keys", "tag1, tag2,tag3"); // mock environment variables SysProps.setProperty("tag1", "value1"); SysProps.setProperty("tag2", "value2"); SysProps.setProperty("tag3", "value3"); application1.refresh(); Map<String, String> parameters1 = application1.getParameters(); Assertions.assertEquals("value2", parameters1.get("tag2")); Assertions.assertEquals("value3", parameters1.get("tag3")); Map<String, String> urlParameters = new HashMap<>(); ApplicationConfig.appendParameters(urlParameters, application1); Assertions.assertEquals("value1", urlParameters.get("tag1")); Assertions.assertEquals("value2", urlParameters.get("tag2")); Assertions.assertEquals("value3", urlParameters.get("tag3")); } @Test void testMetaData() { ApplicationConfig config = new ApplicationConfig(); Map<String, String> metaData = config.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } @Test void testOverrideEmptyConfig() { String owner = "tom1"; SysProps.setProperty("dubbo.application.name", "demo-app"); SysProps.setProperty("dubbo.application.owner", owner); SysProps.setProperty("dubbo.application.version", "1.2.3"); ApplicationConfig applicationConfig = new ApplicationConfig(); DubboBootstrap.getInstance().application(applicationConfig).initialize(); Assertions.assertEquals(owner, applicationConfig.getOwner()); Assertions.assertEquals("1.2.3", applicationConfig.getVersion()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideConfigById() { String owner = "tom2"; SysProps.setProperty("dubbo.applications.demo-app.owner", owner); SysProps.setProperty("dubbo.applications.demo-app.version", "1.2.3"); SysProps.setProperty("dubbo.applications.demo-app.name", "demo-app"); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setId("demo-app"); DubboBootstrap.getInstance().application(applicationConfig).initialize(); Assertions.assertEquals("demo-app", applicationConfig.getId()); Assertions.assertEquals("demo-app", applicationConfig.getName()); Assertions.assertEquals(owner, applicationConfig.getOwner()); Assertions.assertEquals("1.2.3", applicationConfig.getVersion()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideConfigByName() { String owner = "tom3"; SysProps.setProperty("dubbo.applications.demo-app.owner", owner); SysProps.setProperty("dubbo.applications.demo-app.version", "1.2.3"); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("demo-app"); DubboBootstrap.getInstance().application(applicationConfig).initialize(); Assertions.assertEquals(owner, applicationConfig.getOwner()); Assertions.assertEquals("1.2.3", applicationConfig.getVersion()); DubboBootstrap.getInstance().destroy(); } @Test void testLoadConfig() { String owner = "tom4"; SysProps.setProperty("dubbo.applications.demo-app.owner", owner); SysProps.setProperty("dubbo.applications.demo-app.version", "1.2.3"); DubboBootstrap.getInstance().initialize(); ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication(); Assertions.assertEquals("demo-app", applicationConfig.getId()); Assertions.assertEquals("demo-app", applicationConfig.getName()); Assertions.assertEquals(owner, applicationConfig.getOwner()); Assertions.assertEquals("1.2.3", applicationConfig.getVersion()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideConfigConvertCase() { SysProps.setProperty("dubbo.application.NAME", "demo-app"); SysProps.setProperty("dubbo.application.qos-Enable", "false"); SysProps.setProperty("dubbo.application.qos_host", "127.0.0.1"); SysProps.setProperty("dubbo.application.qosPort", "2345"); DubboBootstrap.getInstance().initialize(); ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication(); Assertions.assertEquals(false, applicationConfig.getQosEnable()); Assertions.assertEquals("127.0.0.1", applicationConfig.getQosHost()); Assertions.assertEquals(2345, applicationConfig.getQosPort()); Assertions.assertEquals("demo-app", applicationConfig.getName()); DubboBootstrap.getInstance().destroy(); } @Test void testDefaultValue() { SysProps.setProperty("dubbo.application.NAME", "demo-app"); DubboBootstrap.getInstance().initialize(); ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication(); Assertions.assertEquals(DUBBO, applicationConfig.getProtocol()); Assertions.assertEquals(EXECUTOR_MANAGEMENT_MODE_ISOLATION, applicationConfig.getExecutorManagementMode()); Assertions.assertEquals(Boolean.TRUE, applicationConfig.getEnableFileCache()); DubboBootstrap.getInstance().destroy(); } }
ApplicationConfigTest
java
apache__camel
components/camel-aws/camel-aws2-kinesis/src/main/java/org/apache/camel/component/aws2/kinesis/Kinesis2ShardClosedStrategyEnum.java
{ "start": 860, "end": 935 }
enum ____ { ignore, fail, silent }
Kinesis2ShardClosedStrategyEnum
java
apache__dubbo
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InstanceAddressURLTest.java
{ "start": 2359, "end": 10658 }
class ____ { private static URL url = URL.valueOf( "dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=1000&deprecated=false&dubbo=2.0.2" + "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&a.timeout=7777&pid=66666&release=&revision=1.0.0&service-name-mapping=true" + "&side=provider&timeout=1000&timestamp=1629970909999&version=1.0.0&dubbo.tag=provider&params-filter=-default"); private static URL url2 = URL.valueOf( "dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService2?" + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService2" + "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + "&side=provider&timeout=5000&timestamp=1629970068002&version=1.0.0&dubbo.tag=provider2&uniqueKey=unique&params-filter=-default"); private static URL consumerURL = URL.valueOf("dubbo://30.225.21.30/org.apache.dubbo.registry.service.DemoService?" + "REGISTRY_CLUSTER=registry1&application=demo-consumer&dubbo=2.0.2" + "&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + "&version=1.0.0&timeout=9000&a.timeout=8888&dubbo.tag=consumer&protocol=dubbo"); private DefaultServiceInstance createInstance() { DefaultServiceInstance instance = new DefaultServiceInstance("demo-provider", "127.0.0.1", 8080, ApplicationModel.defaultModel()); Map<String, String> metadata = instance.getMetadata(); metadata.put("key1", "value1"); metadata.put("key2", "value2"); return instance; } private MetadataInfo createMetaDataInfo() { MetadataInfo metadataInfo = new MetadataInfo("demo"); // export normal url again metadataInfo.addService(url); metadataInfo.addService(url2); return metadataInfo; } private InstanceAddressURL instanceURL; private transient volatile Set<String> providerFirstParams; @BeforeEach public void setUp() { DefaultServiceInstance instance = createInstance(); MetadataInfo metadataInfo = createMetaDataInfo(); instanceURL = new InstanceAddressURL(instance, metadataInfo); Set<ProviderFirstParams> providerFirstParams = ApplicationModel.defaultModel() .getExtensionLoader(ProviderFirstParams.class) .getSupportedExtensionInstances(); if (CollectionUtils.isEmpty(providerFirstParams)) { this.providerFirstParams = null; } else { if (providerFirstParams.size() == 1) { this.providerFirstParams = Collections.unmodifiableSet( providerFirstParams.iterator().next().params()); } else { Set<String> params = new HashSet<>(); for (ProviderFirstParams paramsFilter : providerFirstParams) { if (paramsFilter.params() == null) { break; } params.addAll(paramsFilter.params()); } this.providerFirstParams = Collections.unmodifiableSet(params); } } instanceURL.setProviderFirstParams(this.providerFirstParams); } @Test void test1() { // test reading of keys in instance and metadata work fine assertEquals("value1", instanceURL.getParameter("key1")); // return instance key assertNull(instanceURL.getParameter("delay")); // no service key specified RpcServiceContext.getServiceContext().setConsumerUrl(consumerURL); assertEquals("1000", instanceURL.getParameter("delay")); assertEquals("1000", instanceURL.getServiceParameter(consumerURL.getProtocolServiceKey(), "delay")); assertEquals("9000", instanceURL.getMethodParameter("sayHello", "timeout")); assertEquals( "9000", instanceURL.getServiceMethodParameter(consumerURL.getProtocolServiceKey(), "sayHello", "timeout")); assertNull(instanceURL.getParameter("uniqueKey")); assertNull(instanceURL.getServiceParameter(consumerURL.getProtocolServiceKey(), "uniqueKey")); assertEquals("unique", instanceURL.getServiceParameter(url2.getProtocolServiceKey(), "uniqueKey")); // test some consumer keys have higher priority assertEquals( "8888", instanceURL.getServiceMethodParameter(consumerURL.getProtocolServiceKey(), "a", "timeout")); assertEquals("9000", instanceURL.getParameter("timeout")); // test some provider keys have higher priority assertEquals("provider", instanceURL.getParameter(TAG_KEY)); assertEquals(instanceURL.getVersion(), instanceURL.getParameter(VERSION_KEY)); assertEquals(instanceURL.getGroup(), instanceURL.getParameter(GROUP_KEY)); assertEquals(instanceURL.getApplication(), instanceURL.getParameter(APPLICATION_KEY)); assertEquals("demo-consumer", instanceURL.getParameter(APPLICATION_KEY)); assertEquals(instanceURL.getRemoteApplication(), instanceURL.getParameter(REMOTE_APPLICATION_KEY)); assertEquals("demo-provider", instanceURL.getParameter(REMOTE_APPLICATION_KEY)); assertEquals(instanceURL.getSide(), instanceURL.getParameter(SIDE_KEY)); // assertThat(Arrays.asList("7000", "8888"), hasItem(instanceURL.getAnyMethodParameter("timeout"))); assertThat(instanceURL.getAnyMethodParameter("timeout"), in(Arrays.asList("7000", "8888"))); Map<String, String> expectedAllParams = new HashMap<>(); expectedAllParams.putAll(instanceURL.getInstance().getMetadata()); expectedAllParams.putAll(instanceURL .getMetadataInfo() .getServiceInfo(consumerURL.getProtocolServiceKey()) .getAllParams()); Map<String, String> consumerURLParameters = consumerURL.getParameters(); providerFirstParams.forEach(consumerURLParameters::remove); expectedAllParams.putAll(consumerURLParameters); assertEquals(expectedAllParams.size(), instanceURL.getParameters().size()); assertEquals(url.getParameter(TAG_KEY), instanceURL.getParameters().get(TAG_KEY)); assertEquals( consumerURL.getParameter(TIMEOUT_KEY), instanceURL.getParameters().get(TIMEOUT_KEY)); assertTrue(instanceURL.hasServiceMethodParameter(url.getProtocolServiceKey(), "a")); assertTrue(instanceURL.hasServiceMethodParameter(url.getProtocolServiceKey(), "sayHello")); assertTrue(instanceURL.hasMethodParameter("a", TIMEOUT_KEY)); assertTrue(instanceURL.hasMethodParameter(null, TIMEOUT_KEY)); assertEquals("8888", instanceURL.getMethodParameter("a", TIMEOUT_KEY)); assertTrue(instanceURL.hasMethodParameter("a", null)); assertFalse(instanceURL.hasMethodParameter("notExistMethod", null)); // keys added to instance url are shared among services. instanceURL.addParameter("newKey", "newValue"); assertEquals("newValue", instanceURL.getParameter("newKey")); assertEquals("newValue", instanceURL.getParameters().get("newKey")); assertEquals( "newValue", instanceURL.getServiceParameters(url.getProtocolServiceKey()).get("newKey")); } @Test void test2() { RpcServiceContext.getServiceContext().setConsumerUrl(null); Assertions.assertNull(instanceURL.getScopeModel()); ModuleModel moduleModel = Mockito.mock(ModuleModel.class); RpcServiceContext.getServiceContext().setConsumerUrl(URL.valueOf("").setScopeModel(moduleModel)); Assertions.assertEquals(moduleModel, instanceURL.getScopeModel()); } }
InstanceAddressURLTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessorTests.java
{ "start": 2113, "end": 10628 }
class ____ { @Test void proxyCreated() { ConfigurableApplicationContext context = initContext( new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class)); Object target = context.getBean("target"); assertThat(AopUtils.isAopProxy(target)).isTrue(); context.close(); } @Test void invokedAsynchronously() { ConfigurableApplicationContext context = initContext( new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class)); ITestBean testBean = context.getBean("target", ITestBean.class); testBean.test(); Thread mainThread = Thread.currentThread(); testBean.await(3000); Thread asyncThread = testBean.getThread(); assertThat(asyncThread).isNotSameAs(mainThread); context.close(); } @Test void invokedAsynchronouslyOnProxyTarget() { StaticApplicationContext context = new StaticApplicationContext(); context.registerBeanDefinition("postProcessor", new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class)); TestBean tb = new TestBean(); ProxyFactory pf = new ProxyFactory(ITestBean.class, (MethodInterceptor) invocation -> invocation.getMethod().invoke(tb, invocation.getArguments())); context.registerBean("target", ITestBean.class, () -> (ITestBean) pf.getProxy()); context.refresh(); ITestBean testBean = context.getBean("target", ITestBean.class); testBean.test(); Thread mainThread = Thread.currentThread(); testBean.await(3000); Thread asyncThread = testBean.getThread(); assertThat(asyncThread).isNotSameAs(mainThread); context.close(); } @Test void threadNamePrefix() { BeanDefinition processorDefinition = new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setThreadNamePrefix("testExecutor"); executor.afterPropertiesSet(); processorDefinition.getPropertyValues().add("executor", executor); ConfigurableApplicationContext context = initContext(processorDefinition); ITestBean testBean = context.getBean("target", ITestBean.class); testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); assertThat(asyncThread.getName()).startsWith("testExecutor"); context.close(); } @Test void taskExecutorByBeanType() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinition processorDefinition = new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class); context.registerBeanDefinition("postProcessor", processorDefinition); BeanDefinition executorDefinition = new RootBeanDefinition(ThreadPoolTaskExecutor.class); executorDefinition.getPropertyValues().add("threadNamePrefix", "testExecutor"); context.registerBeanDefinition("myExecutor", executorDefinition); BeanDefinition targetDefinition = new RootBeanDefinition(AsyncAnnotationBeanPostProcessorTests.TestBean.class); context.registerBeanDefinition("target", targetDefinition); context.refresh(); ITestBean testBean = context.getBean("target", ITestBean.class); testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); assertThat(asyncThread.getName()).startsWith("testExecutor"); context.close(); } @Test void taskExecutorByBeanName() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinition processorDefinition = new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class); context.registerBeanDefinition("postProcessor", processorDefinition); BeanDefinition executorDefinition = new RootBeanDefinition(ThreadPoolTaskExecutor.class); executorDefinition.getPropertyValues().add("threadNamePrefix", "testExecutor"); context.registerBeanDefinition("myExecutor", executorDefinition); BeanDefinition executorDefinition2 = new RootBeanDefinition(ThreadPoolTaskExecutor.class); executorDefinition2.getPropertyValues().add("threadNamePrefix", "testExecutor2"); context.registerBeanDefinition("taskExecutor", executorDefinition2); BeanDefinition targetDefinition = new RootBeanDefinition(AsyncAnnotationBeanPostProcessorTests.TestBean.class); context.registerBeanDefinition("target", targetDefinition); context.refresh(); ITestBean testBean = context.getBean("target", ITestBean.class); testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); assertThat(asyncThread.getName()).startsWith("testExecutor2"); context.close(); } @Test void configuredThroughNamespace() { GenericXmlApplicationContext context = new GenericXmlApplicationContext(); context.load(new ClassPathResource("taskNamespaceTests.xml", getClass())); context.refresh(); ITestBean testBean = context.getBean("target", ITestBean.class); testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); assertThat(asyncThread.getName()).startsWith("testExecutor"); TestableAsyncUncaughtExceptionHandler exceptionHandler = context.getBean("exceptionHandler", TestableAsyncUncaughtExceptionHandler.class); assertThat(exceptionHandler.isCalled()).as("handler should not have been called yet").isFalse(); testBean.failWithVoid(); exceptionHandler.await(3000); Method m = ReflectionUtils.findMethod(TestBean.class, "failWithVoid"); exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class); context.close(); } @Test @SuppressWarnings("resource") public void handleExceptionWithFuture() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithExceptionHandler.class); ITestBean testBean = context.getBean("target", ITestBean.class); TestableAsyncUncaughtExceptionHandler exceptionHandler = context.getBean("exceptionHandler", TestableAsyncUncaughtExceptionHandler.class); assertThat(exceptionHandler.isCalled()).as("handler should not have been called yet").isFalse(); Future<Object> result = testBean.failWithFuture(); assertFutureWithException(result, exceptionHandler); } private void assertFutureWithException(Future<Object> result, TestableAsyncUncaughtExceptionHandler exceptionHandler) { assertThatExceptionOfType(ExecutionException.class).isThrownBy( result::get) .withCauseExactlyInstanceOf(UnsupportedOperationException.class); assertThat(exceptionHandler.isCalled()).as("handler should never be called with Future return type").isFalse(); } @Test void handleExceptionWithCustomExceptionHandler() { Method m = ReflectionUtils.findMethod(TestBean.class, "failWithVoid"); TestableAsyncUncaughtExceptionHandler exceptionHandler = new TestableAsyncUncaughtExceptionHandler(); BeanDefinition processorDefinition = new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class); processorDefinition.getPropertyValues().add("exceptionHandler", exceptionHandler); ConfigurableApplicationContext context = initContext(processorDefinition); ITestBean testBean = context.getBean("target", ITestBean.class); assertThat(exceptionHandler.isCalled()).as("Handler should not have been called").isFalse(); testBean.failWithVoid(); exceptionHandler.await(3000); exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class); } @Test void exceptionHandlerThrowsUnexpectedException() { Method m = ReflectionUtils.findMethod(TestBean.class, "failWithVoid"); TestableAsyncUncaughtExceptionHandler exceptionHandler = new TestableAsyncUncaughtExceptionHandler(true); BeanDefinition processorDefinition = new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class); processorDefinition.getPropertyValues().add("exceptionHandler", exceptionHandler); processorDefinition.getPropertyValues().add("executor", new DirectExecutor()); ConfigurableApplicationContext context = initContext(processorDefinition); ITestBean testBean = context.getBean("target", ITestBean.class); assertThat(exceptionHandler.isCalled()).as("Handler should not have been called").isFalse(); testBean.failWithVoid(); exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class); } private ConfigurableApplicationContext initContext(BeanDefinition asyncAnnotationBeanPostProcessorDefinition) { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinition targetDefinition = new RootBeanDefinition(TestBean.class); context.registerBeanDefinition("postProcessor", asyncAnnotationBeanPostProcessorDefinition); context.registerBeanDefinition("target", targetDefinition); context.refresh(); return context; } private
AsyncAnnotationBeanPostProcessorTests
java
quarkusio__quarkus
extensions/elytron-security-properties-file/deployment/src/test/java/io/quarkus/security/test/SubjectExposingResource.java
{ "start": 503, "end": 1680 }
class ____ { @Inject Principal principal; @GET @RolesAllowed("Tester") @Path("secured") public String getSubjectSecured(@Context SecurityContext sec) { Principal user = sec.getUserPrincipal(); String name = user != null ? user.getName() : "anonymous"; return name; } @GET @RolesAllowed("Tester") @Path("principalSecured") public String getPrincipalSecured(@Context SecurityContext sec) { if (principal == null) { throw new IllegalStateException("No injected principal"); } String name = principal.getName(); return name; } @GET @Path("unsecured") @PermitAll public String getSubjectUnsecured(@Context SecurityContext sec) { Principal user = sec.getUserPrincipal(); String name = user != null ? user.getName() : "anonymous"; return name; } @DenyAll @GET @Path("denied") public String getSubjectDenied(@Context SecurityContext sec) { Principal user = sec.getUserPrincipal(); String name = user != null ? user.getName() : "anonymous"; return name; } }
SubjectExposingResource
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/main/java/io/quarkus/vertx/http/deployment/devmode/RouteDescriptionBuildItem.java
{ "start": 244, "end": 1026 }
class ____ extends MultiBuildItem { private RouteDescription description; public RouteDescriptionBuildItem(String javaMethod, String path, String httpMethod, String[] produces, String[] consumes) { RouteDescription description = new RouteDescription(); description.setBasePath(path); description.addCall(new RouteMethodDescription(javaMethod, httpMethod, path, getMediaType(produces), getMediaType(consumes))); this.description = description; } public RouteDescription getDescription() { return description; } private String getMediaType(String[] all) { return all.length == 0 ? null : String.join(", ", all); } }
RouteDescriptionBuildItem
java
elastic__elasticsearch
x-pack/plugin/sql/qa/server/security/src/test/java/org/elasticsearch/xpack/sql/qa/security/JdbcShowTablesIT.java
{ "start": 455, "end": 932 }
class ____ extends ShowTablesTestCase { @Override protected Settings restClientSettings() { return RestSqlIT.securitySettings(); } @Override protected String getProtocol() { return RestSqlIT.SSL_ENABLED ? "https" : "http"; } @Override protected Properties connectionProperties() { Properties sp = super.connectionProperties(); sp.putAll(JdbcSecurityIT.adminProperties()); return sp; } }
JdbcShowTablesIT
java
alibaba__nacos
api/src/main/java/com/alibaba/nacos/api/ability/constant/AbilityStatus.java
{ "start": 803, "end": 1051 }
enum ____ { /**. * Support a certain ability */ SUPPORTED, /**. * Not support a certain ability */ NOT_SUPPORTED, /**. * Cannot find ability table, unknown */ UNKNOWN }
AbilityStatus
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestEncryptionZoneManager.java
{ "start": 1695, "end": 7207 }
class ____ { private FSDirectory mockedDir; private INodesInPath mockedINodesInPath; private INodeDirectory firstINode; private INodeDirectory secondINode; private INodeDirectory rootINode; private PermissionStatus defaultPermission; private EncryptionZoneManager ezManager; @BeforeEach public void setup() { this.mockedDir = mock(FSDirectory.class); this.mockedINodesInPath = mock(INodesInPath.class); this.defaultPermission = new PermissionStatus("test", "test", new FsPermission((short) 755)); this.rootINode = new INodeDirectory(0L, "".getBytes(), defaultPermission, System.currentTimeMillis()); this.firstINode = new INodeDirectory(1L, "first".getBytes(), defaultPermission, System.currentTimeMillis()); this.secondINode = new INodeDirectory(2L, "second".getBytes(), defaultPermission, System.currentTimeMillis()); when(this.mockedDir.hasReadLock()).thenReturn(true); when(this.mockedDir.hasWriteLock()).thenReturn(true); when(this.mockedDir.getInode(0L)).thenReturn(rootINode); when(this.mockedDir.getInode(1L)).thenReturn(firstINode); when(this.mockedDir.getInode(2L)).thenReturn(secondINode); } @Test public void testListEncryptionZonesOneValidOnly() throws Exception{ this.ezManager = new EncryptionZoneManager(mockedDir, new Configuration()); this.ezManager.addEncryptionZone(1L, CipherSuite.AES_CTR_NOPADDING, CryptoProtocolVersion.ENCRYPTION_ZONES, "test_key"); this.ezManager.addEncryptionZone(2L, CipherSuite.AES_CTR_NOPADDING, CryptoProtocolVersion.ENCRYPTION_ZONES, "test_key"); // sets root as proper parent for firstINode only this.firstINode.setParent(rootINode); when(mockedDir.getINodesInPath("/first", DirOp.READ_LINK)). thenReturn(mockedINodesInPath); when(mockedINodesInPath.getLastINode()). thenReturn(firstINode); BatchedListEntries<EncryptionZone> result = ezManager. listEncryptionZones(0); assertEquals(1, result.size()); assertEquals(1L, result.get(0).getId()); assertEquals("/first", result.get(0).getPath()); } @Test public void testListEncryptionZonesTwoValids() throws Exception { this.ezManager = new EncryptionZoneManager(mockedDir, new Configuration()); this.ezManager.addEncryptionZone(1L, CipherSuite.AES_CTR_NOPADDING, CryptoProtocolVersion.ENCRYPTION_ZONES, "test_key"); this.ezManager.addEncryptionZone(2L, CipherSuite.AES_CTR_NOPADDING, CryptoProtocolVersion.ENCRYPTION_ZONES, "test_key"); // sets root as proper parent for both inodes this.firstINode.setParent(rootINode); this.secondINode.setParent(rootINode); when(mockedDir.getINodesInPath("/first", DirOp.READ_LINK)). thenReturn(mockedINodesInPath); when(mockedINodesInPath.getLastINode()). thenReturn(firstINode); INodesInPath mockedINodesInPathForSecond = mock(INodesInPath.class); when(mockedDir.getINodesInPath("/second", DirOp.READ_LINK)). thenReturn(mockedINodesInPathForSecond); when(mockedINodesInPathForSecond.getLastINode()). thenReturn(secondINode); BatchedListEntries<EncryptionZone> result = ezManager.listEncryptionZones(0); assertEquals(2, result.size()); assertEquals(1L, result.get(0).getId()); assertEquals("/first", result.get(0).getPath()); assertEquals(2L, result.get(1).getId()); assertEquals("/second", result.get(1).getPath()); } @Test public void testListEncryptionZonesForRoot() throws Exception{ this.ezManager = new EncryptionZoneManager(mockedDir, new Configuration()); this.ezManager.addEncryptionZone(0L, CipherSuite.AES_CTR_NOPADDING, CryptoProtocolVersion.ENCRYPTION_ZONES, "test_key"); // sets root as proper parent for firstINode only when(mockedDir.getINodesInPath("/", DirOp.READ_LINK)). thenReturn(mockedINodesInPath); when(mockedINodesInPath.getLastINode()). thenReturn(rootINode); BatchedListEntries<EncryptionZone> result = ezManager. listEncryptionZones(-1); assertEquals(1, result.size()); assertEquals(0L, result.get(0).getId()); assertEquals("/", result.get(0).getPath()); } @Test public void testListEncryptionZonesSubDirInvalid() throws Exception{ INodeDirectory thirdINode = new INodeDirectory(3L, "third".getBytes(), defaultPermission, System.currentTimeMillis()); when(this.mockedDir.getInode(3L)).thenReturn(thirdINode); //sets "second" as parent thirdINode.setParent(this.secondINode); this.ezManager = new EncryptionZoneManager(mockedDir, new Configuration()); this.ezManager.addEncryptionZone(1L, CipherSuite.AES_CTR_NOPADDING, CryptoProtocolVersion.ENCRYPTION_ZONES, "test_key"); this.ezManager.addEncryptionZone(3L, CipherSuite.AES_CTR_NOPADDING, CryptoProtocolVersion.ENCRYPTION_ZONES, "test_key"); // sets root as proper parent for firstINode only, // leave secondINode with no parent this.firstINode.setParent(rootINode); when(mockedDir.getINodesInPath("/first", DirOp.READ_LINK)). thenReturn(mockedINodesInPath); when(mockedINodesInPath.getLastINode()). thenReturn(firstINode); BatchedListEntries<EncryptionZone> result = ezManager. listEncryptionZones(0); assertEquals(1, result.size()); assertEquals(1L, result.get(0).getId()); assertEquals("/first", result.get(0).getPath()); } }
TestEncryptionZoneManager
java
elastic__elasticsearch
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Expression.java
{ "start": 4826, "end": 6619 }
class ____, instead usually calling the utility methods on {@link TypeResolutions}. * </p> * <p> * Implementations should fail if {@link #childrenResolved()} returns {@code false}. * </p> */ protected TypeResolution resolveType() { return TypeResolution.TYPE_RESOLVED; } public final Expression canonical() { if (lazyCanonical == null) { lazyCanonical = canonicalize(); } return lazyCanonical; } protected Expression canonicalize() { if (children().isEmpty()) { return this; } List<Expression> canonicalChildren = Expressions.canonicalize(children()); // check if replacement is really needed if (children().equals(canonicalChildren)) { return this; } return replaceChildrenSameSize(canonicalChildren); } public boolean semanticEquals(Expression other) { return canonical().equals(other.canonical()); } public int semanticHash() { return canonical().hashCode(); } @Override public boolean resolved() { return childrenResolved() && typeResolved().resolved(); } /** * The {@link DataType} returned by executing the tree rooted at this * expression. If {@link #typeResolved()} returns an error then the behavior * of this method is undefined. It <strong>may</strong> return a valid * type. Or it may throw an exception. Or it may return a totally nonsensical * type. */ public abstract DataType dataType(); @Override public String toString() { return sourceText(); } @Override public String propertiesToString(boolean skipIfChild) { return super.propertiesToString(false); } }
directly
java
apache__camel
core/camel-api/src/generated/java/org/apache/camel/spi/annotations/ServiceFactory.java
{ "start": 1134, "end": 1220 }
interface ____ { String JDK_SERVICE = "#jdk#"; String value(); }
ServiceFactory
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/NamedNativeQueryAnnotation.java
{ "start": 1105, "end": 7736 }
class ____ implements NamedNativeQuery { private String name; private String query; private Class<?> resultClass; private String resultSetMapping; private FlushModeType flushMode; private QueryFlushMode flush; boolean cacheable; String cacheRegion; int fetchSize; int timeout; String comment; CacheStoreMode cacheStoreMode; CacheRetrieveMode cacheRetrieveMode; boolean readOnly; String[] querySpaces; /** * Used in creating dynamic annotation instances (e.g. from XML) */ public NamedNativeQueryAnnotation(ModelsContext modelContext) { resultClass = void.class; resultSetMapping = ""; flushMode = FlushModeType.PERSISTENCE_CONTEXT; flush = QueryFlushMode.DEFAULT; cacheable = false; cacheRegion = ""; fetchSize = -1; timeout = -1; comment = ""; cacheStoreMode = CacheStoreMode.USE; cacheRetrieveMode = CacheRetrieveMode.USE; readOnly = false; querySpaces = new String[0]; } /** * Used in creating annotation instances from JDK variant */ public NamedNativeQueryAnnotation(NamedNativeQuery annotation, ModelsContext modelContext) { this.name = annotation.name(); this.query = annotation.query(); this.resultClass = annotation.resultClass(); this.resultSetMapping = annotation.resultSetMapping(); this.flushMode = annotation.flushMode(); this.flush = annotation.flush(); this.cacheable = annotation.cacheable(); this.cacheRegion = annotation.cacheRegion(); this.fetchSize = annotation.fetchSize(); this.timeout = annotation.timeout(); this.comment = annotation.comment(); this.cacheStoreMode = annotation.cacheStoreMode(); this.cacheRetrieveMode = annotation.cacheRetrieveMode(); if ( annotation.cacheMode() != CacheMode.NORMAL ) { this.cacheStoreMode = annotation.cacheMode().getJpaStoreMode(); this.cacheRetrieveMode = annotation.cacheMode().getJpaRetrieveMode(); } this.readOnly = annotation.readOnly(); this.querySpaces = annotation.querySpaces(); } /** * Used in creating annotation instances from Jandex variant */ public NamedNativeQueryAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) { this.name = (String) attributeValues.get( "name" ); this.query = (String) attributeValues.get( "query" ); this.resultClass = (Class<?>) attributeValues.get( "resultClass" ); this.resultSetMapping = (String) attributeValues.get( "resultSetMapping" ); this.flushMode = (FlushModeType) attributeValues.get( "flushMode" ); this.flush = (QueryFlushMode) attributeValues.get( "flush" ); this.cacheable = (boolean) attributeValues.get( "cacheable" ); this.cacheRegion = (String) attributeValues.get( "cacheRegion" ); this.fetchSize = (int) attributeValues.get( "fetchSize" ); this.timeout = (int) attributeValues.get( "timeout" ); this.comment = (String) attributeValues.get( "comment" ); this.cacheStoreMode = (CacheStoreMode) attributeValues.get( "cacheStoreMode" ); this.cacheRetrieveMode = (CacheRetrieveMode) attributeValues.get( "cacheRetrieveMode" ); this.readOnly = (boolean) attributeValues.get( "readOnly" ); this.querySpaces = (String[]) attributeValues.get( "querySpaces" ); } @Override public Class<? extends Annotation> annotationType() { return NamedNativeQuery.class; } @Override public String name() { return name; } public void name(String value) { this.name = value; } @Override public String query() { return query; } public void query(String value) { this.query = value; } @Override public Class<?> resultClass() { return resultClass; } public void resultClass(Class<?> value) { this.resultClass = value; } @Override public String resultSetMapping() { return resultSetMapping; } public void resultSetMapping(String value) { this.resultSetMapping = value; } @Override public QueryFlushMode flush() { return flush; } public void flush(QueryFlushMode value) { this.flush = value; } @Override public FlushModeType flushMode() { return flushMode; } public void flushMode(FlushModeType value) { this.flushMode = value; } @Override public boolean cacheable() { return cacheable; } public void cacheable(boolean value) { this.cacheable = value; } @Override public String cacheRegion() { return cacheRegion; } public void cacheRegion(String value) { this.cacheRegion = value; } @Override public int fetchSize() { return fetchSize; } public void fetchSize(int value) { this.fetchSize = value; } @Override public int timeout() { return timeout; } public void timeout(int value) { this.timeout = value; } @Override public String comment() { return comment; } public void comment(String value) { this.comment = value; } @Override public CacheStoreMode cacheStoreMode() { return cacheStoreMode; } public void cacheStoreMode(CacheStoreMode value) { this.cacheStoreMode = value; } @Override public CacheRetrieveMode cacheRetrieveMode() { return cacheRetrieveMode; } public void cacheRetrieveMode(CacheRetrieveMode value) { this.cacheRetrieveMode = value; } @Override public CacheMode cacheMode() { return CacheMode.fromJpaModes( cacheRetrieveMode, cacheStoreMode ); } @Override public boolean readOnly() { return readOnly; } public void readOnly(boolean value) { this.readOnly = value; } @Override public String[] querySpaces() { return querySpaces; } public void querySpaces(String[] value) { this.querySpaces = value; } public void apply(JaxbNamedNativeQueryImpl jaxbNamedQuery, XmlDocumentContext xmlDocumentContext) { name( jaxbNamedQuery.getName() ); query( jaxbNamedQuery.getQuery() ); applyResultClassAndSynchronizations( jaxbNamedQuery, xmlDocumentContext ); if ( StringHelper.isNotEmpty( jaxbNamedQuery.getResultSetMapping() ) ) { resultSetMapping( jaxbNamedQuery.getResultSetMapping() ); } } private void applyResultClassAndSynchronizations( JaxbNamedNativeQueryImpl jaxbNamedQuery, XmlDocumentContext xmlDocumentContext) { final List<String> syncSpaces = new ArrayList<>(); if ( StringHelper.isNotEmpty( jaxbNamedQuery.getResultClass() ) ) { final MutableClassDetails resultClassDetails = xmlDocumentContext.resolveJavaType( jaxbNamedQuery.getResultClass() ); syncSpaces.add( resultClassDetails.getName() ); resultClass( resultClassDetails.toJavaClass() ); } for ( JaxbSynchronizedTableImpl synchronization : jaxbNamedQuery.getSynchronizations() ) { syncSpaces.add( synchronization.getTable() ); } if ( CollectionHelper.isNotEmpty( syncSpaces ) ) { querySpaces( syncSpaces.toArray( String[]::new ) ); } } }
NamedNativeQueryAnnotation
java
apache__flink
flink-core/src/main/java/org/apache/flink/util/InstantiationUtil.java
{ "start": 11229, "end": 11362 }
class ____ exceptions occurring later. * @return An instance of the given class. * @throws RuntimeException Thrown, if the
cast
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/service/repository/ConfigRowMapperInjector.java
{ "start": 21159, "end": 21854 }
class ____ implements RowMapper<ConfigInfoBase> { @Override public ConfigInfoBase mapRow(ResultSet rs, int rowNum) throws SQLException { ConfigInfoBase info = new ConfigInfoBase(); info.setDataId(rs.getString("data_id")); info.setGroup(rs.getString("group_id")); try { info.setContent(rs.getString("content")); } catch (SQLException ignore) { } try { info.setId(rs.getLong("id")); } catch (SQLException ignore) { } return info; } } public static final
ConfigInfoBaseRowMapper
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/requests/AlterUserScramCredentialsResponse.java
{ "start": 1098, "end": 2224 }
class ____ extends AbstractResponse { private final AlterUserScramCredentialsResponseData data; public AlterUserScramCredentialsResponse(AlterUserScramCredentialsResponseData responseData) { super(ApiKeys.ALTER_USER_SCRAM_CREDENTIALS); this.data = responseData; } @Override public AlterUserScramCredentialsResponseData data() { return data; } @Override public boolean shouldClientThrottle(short version) { return true; } @Override public int throttleTimeMs() { return data.throttleTimeMs(); } @Override public void maybeSetThrottleTimeMs(int throttleTimeMs) { data.setThrottleTimeMs(throttleTimeMs); } @Override public Map<Errors, Integer> errorCounts() { return errorCounts(data.results().stream().map(r -> Errors.forCode(r.errorCode()))); } public static AlterUserScramCredentialsResponse parse(Readable readable, short version) { return new AlterUserScramCredentialsResponse(new AlterUserScramCredentialsResponseData(readable, version)); } }
AlterUserScramCredentialsResponse
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/util/BigArrays.java
{ "start": 9132, "end": 11664 }
class ____ extends AbstractArrayWrapper implements LongArray { private final byte[] array; ByteArrayAsLongArrayWrapper(BigArrays bigArrays, long size, boolean clearOnResize) { super(bigArrays, size, null, clearOnResize); assert size >= 0 && size <= PageCacheRecycler.LONG_PAGE_SIZE; this.array = new byte[(int) size << 3]; } @Override public long ramBytesUsed() { return SHALLOW_SIZE + RamUsageEstimator.sizeOf(array); } @Override public long get(long index) { assert index >= 0 && index < size(); return (long) VH_PLATFORM_NATIVE_LONG.get(array, (int) index << 3); } @Override public long getAndSet(long index, long value) { assert index >= 0 && index < size(); final long ret = (long) VH_PLATFORM_NATIVE_LONG.get(array, (int) index << 3); VH_PLATFORM_NATIVE_LONG.set(array, (int) index << 3, value); return ret; } @Override public void set(long index, long value) { assert index >= 0 && index < size(); VH_PLATFORM_NATIVE_LONG.set(array, (int) index << 3, value); } @Override public long increment(long index, long inc) { assert index >= 0 && index < size(); final long ret = (long) VH_PLATFORM_NATIVE_LONG.get(array, (int) index << 3) + inc; VH_PLATFORM_NATIVE_LONG.set(array, (int) index << 3, ret); return ret; } @Override public void fill(long fromIndex, long toIndex, long value) { assert fromIndex >= 0 && fromIndex <= toIndex; assert toIndex >= 0 && toIndex <= size(); BigLongArray.fill(array, (int) fromIndex, (int) toIndex, value); } @Override public void set(long index, byte[] buf, int offset, int len) { assert index >= 0 && index < size(); System.arraycopy(buf, offset << 3, array, (int) index << 3, len << 3); } @Override public void writeTo(StreamOutput out) throws IOException { int size = Math.toIntExact(size()) * Long.BYTES; out.writeVInt(size); out.write(array, 0, size); } @Override public void fillWith(StreamInput in) throws IOException { int len = in.readVInt(); in.readBytes(array, 0, len); } } private static
ByteArrayAsLongArrayWrapper
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/io/value/ValueResourceLoader.java
{ "start": 2836, "end": 3197 }
class ____ extends URLStreamHandler { private final byte[] bytes; StreamHandlerImpl(byte[] bytes) { this.bytes = bytes; } @Override protected URLConnection openConnection(URL u) throws IOException { return new FixedURLConnection(u, bytes); } } private static final
StreamHandlerImpl
java
apache__camel
dsl/camel-xml-io-dsl/src/test/java/org/apache/camel/dsl/xml/io/XmlKameletTest.java
{ "start": 960, "end": 1401 }
class ____ { @Test public void testMainKameletAsXml() throws Exception { Main main = new Main(); main.configure().withRoutesIncludePattern("file:src/test/resources/org/apache/camel/kamelet/camel-kamelet.xml"); main.start(); Object out = main.getCamelTemplate().requestBody("direct:start", "Hello World"); Assertions.assertEquals("HELLO WORLD", out); main.stop(); } }
XmlKameletTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GrapeEndpointBuilderFactory.java
{ "start": 4394, "end": 6711 }
interface ____ { /** * Grape (camel-grape) * Fetch, load and manage additional jars dynamically after Camel * Context was started. * * Category: management * Since: 2.16 * Maven coordinates: org.apache.camel:camel-grape * * @return the dsl builder for the headers' name. */ @Deprecated default GrapeHeaderNameBuilder grape() { return GrapeHeaderNameBuilder.INSTANCE; } /** * Grape (camel-grape) * Fetch, load and manage additional jars dynamically after Camel * Context was started. * * Category: management * Since: 2.16 * Maven coordinates: org.apache.camel:camel-grape * * Syntax: <code>grape:defaultCoordinates</code> * * Path parameter: defaultCoordinates (required) * Maven coordinates to use as default to grab if the message body is * empty. * * @param path defaultCoordinates * @return the dsl builder */ @Deprecated default GrapeEndpointBuilder grape(String path) { return GrapeEndpointBuilderFactory.endpointBuilder("grape", path); } /** * Grape (camel-grape) * Fetch, load and manage additional jars dynamically after Camel * Context was started. * * Category: management * Since: 2.16 * Maven coordinates: org.apache.camel:camel-grape * * Syntax: <code>grape:defaultCoordinates</code> * * Path parameter: defaultCoordinates (required) * Maven coordinates to use as default to grab if the message body is * empty. * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path defaultCoordinates * @return the dsl builder */ @Deprecated default GrapeEndpointBuilder grape(String componentName, String path) { return GrapeEndpointBuilderFactory.endpointBuilder(componentName, path); } } /** * The builder of headers' name for the Grape component. */ public static
GrapeBuilders
java
apache__flink
flink-datastream/src/test/java/org/apache/flink/datastream/impl/functions/ProcessFunctionTest.java
{ "start": 2360, "end": 9146 }
class ____ { @Test void testOneInputStreamProcessFunctionOpenAndCloseInvoked() throws Exception { AtomicBoolean openInvoked = new AtomicBoolean(false); AtomicBoolean closeInvoked = new AtomicBoolean(false); OneInputStreamProcessFunction<Integer, Integer> processFunction = new OneInputStreamProcessFunction<>() { @Override public void open(NonPartitionedContext<Integer> ctx) throws Exception { openInvoked.set(true); } @Override public void processRecord( Integer record, Collector<Integer> output, PartitionedContext<Integer> ctx) throws Exception {} @Override public void close() throws Exception { closeInvoked.set(true); } }; ProcessOperator<Integer, Integer> processOperator = new ProcessOperator<>(processFunction); try (OneInputStreamOperatorTestHarness<Integer, Integer> testHarness = new OneInputStreamOperatorTestHarness<>(processOperator)) { testHarness.open(); assertThat(openInvoked).isTrue(); testHarness.close(); assertThat(closeInvoked).isTrue(); } } @Test void testTwoInputBroadcastStreamProcessFunctionOpenAndCloseInvoked() throws Exception { AtomicBoolean openInvoked = new AtomicBoolean(false); AtomicBoolean closeInvoked = new AtomicBoolean(false); TwoInputBroadcastStreamProcessFunction<Integer, Integer, Integer> processFunction = new TwoInputBroadcastStreamProcessFunction<>() { @Override public void open(NonPartitionedContext<Integer> ctx) throws Exception { openInvoked.set(true); } @Override public void processRecordFromNonBroadcastInput( Integer record, Collector<Integer> output, PartitionedContext<Integer> ctx) throws Exception {} @Override public void processRecordFromBroadcastInput( Integer record, NonPartitionedContext<Integer> ctx) throws Exception {} @Override public void close() throws Exception { closeInvoked.set(true); } }; TwoInputBroadcastProcessOperator<Integer, Integer, Integer> processOperator = new TwoInputBroadcastProcessOperator<>(processFunction); try (TwoInputStreamOperatorTestHarness<Integer, Integer, Integer> testHarness = new TwoInputStreamOperatorTestHarness<>(processOperator)) { testHarness.open(); assertThat(openInvoked).isTrue(); testHarness.close(); assertThat(closeInvoked).isTrue(); } } @Test void testTwoInputNonBroadcastStreamProcessFunctionOpenAndCloseInvoked() throws Exception { AtomicBoolean openInvoked = new AtomicBoolean(false); AtomicBoolean closeInvoked = new AtomicBoolean(false); TwoInputNonBroadcastStreamProcessFunction<Integer, Integer, Integer> processFunction = new TwoInputNonBroadcastStreamProcessFunction<>() { @Override public void open(NonPartitionedContext<Integer> ctx) throws Exception { openInvoked.set(true); } @Override public void processRecordFromFirstInput( Integer record, Collector<Integer> output, PartitionedContext<Integer> ctx) throws Exception {} @Override public void processRecordFromSecondInput( Integer record, Collector<Integer> output, PartitionedContext<Integer> ctx) throws Exception {} @Override public void close() throws Exception { closeInvoked.set(true); } }; TwoInputNonBroadcastProcessOperator<Integer, Integer, Integer> processOperator = new TwoInputNonBroadcastProcessOperator<>(processFunction); try (TwoInputStreamOperatorTestHarness<Integer, Integer, Integer> testHarness = new TwoInputStreamOperatorTestHarness<>(processOperator)) { testHarness.open(); assertThat(openInvoked).isTrue(); testHarness.close(); assertThat(closeInvoked).isTrue(); } } @Test void testTwoOutputStreamProcessFunctionOpenAndCloseInvoked() throws Exception { AtomicBoolean openInvoked = new AtomicBoolean(false); AtomicBoolean closeInvoked = new AtomicBoolean(false); TwoOutputStreamProcessFunction<Integer, Integer, Integer> processFunction = new TwoOutputStreamProcessFunction<>() { @Override public void open(TwoOutputNonPartitionedContext<Integer, Integer> ctx) throws Exception { openInvoked.set(true); } @Override public void processRecord( Integer record, Collector<Integer> output1, Collector<Integer> output2, TwoOutputPartitionedContext<Integer, Integer> ctx) throws Exception {} @Override public void close() throws Exception { closeInvoked.set(true); } }; TwoOutputProcessOperator<Integer, Integer, Integer> processOperator = new TwoOutputProcessOperator<>( processFunction, new OutputTag<Integer>("side-output", Types.INT)); try (OneInputStreamOperatorTestHarness<Integer, Integer> testHarness = new OneInputStreamOperatorTestHarness<>(processOperator)) { testHarness.open(); assertThat(openInvoked).isTrue(); testHarness.close(); assertThat(closeInvoked).isTrue(); } } }
ProcessFunctionTest