language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
google__guava
android/guava/src/com/google/common/collect/Table.java
{ "start": 9950, "end": 10796 }
interface ____< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> { /** Returns the row key of this cell. */ @ParametricNullness R getRowKey(); /** Returns the column key of this cell. */ @ParametricNullness C getColumnKey(); /** Returns the value of this cell. */ @ParametricNullness V getValue(); /** * Compares the specified object with this cell for equality. Two cells are equal when they have * equal row keys, column keys, and values. */ @Override boolean equals(@Nullable Object obj); /** * Returns the hash code of this cell. * * <p>The hash code of a table cell is equal to {@link Objects#hashCode}{@code (e.getRowKey(), * e.getColumnKey(), e.getValue())}. */ @Override int hashCode(); } }
Cell
java
dropwizard__dropwizard
dropwizard-request-logging/src/main/java/io/dropwizard/request/logging/old/DropwizardSlf4jRequestLogWriter.java
{ "start": 520, "end": 1473 }
class ____ extends AbstractLifeCycle implements RequestLog.Writer { private AppenderAttachableImpl<ILoggingEvent> appenders; private final LoggerContext loggerContext; DropwizardSlf4jRequestLogWriter(AppenderAttachableImpl<ILoggingEvent> appenders) { this.appenders = appenders; this.loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); } @Override public void write(String entry) throws IOException { final LoggingEvent event = new LoggingEvent(); event.setLevel(Level.INFO); event.setLoggerName("http.request"); event.setMessage(entry); event.setTimeStamp(System.currentTimeMillis()); event.setLoggerContext(loggerContext); appenders.appendLoopOnAppenders(event); } @Override protected void doStop() throws Exception { appenders.detachAndStopAllAppenders(); super.doStop(); } }
DropwizardSlf4jRequestLogWriter
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/FetchTiming.java
{ "start": 300, "end": 637 }
enum ____ { /** * Perform fetching immediately. Also called eager fetching */ IMMEDIATE, /** * Performing fetching later, when needed. Also called lazy fetching. */ DELAYED; public static FetchTiming forType(FetchType type) { return switch (type) { case EAGER -> IMMEDIATE; case LAZY -> DELAYED; }; } }
FetchTiming
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/node/EBooleanComp.java
{ "start": 736, "end": 1837 }
class ____ extends AExpression { private final AExpression leftNode; private final AExpression rightNode; private final Operation operation; public EBooleanComp(int identifier, Location location, AExpression leftNode, AExpression rightNode, Operation operation) { super(identifier, location); this.operation = Objects.requireNonNull(operation); this.leftNode = Objects.requireNonNull(leftNode); this.rightNode = Objects.requireNonNull(rightNode); } public AExpression getLeftNode() { return leftNode; } public AExpression getRightNode() { return rightNode; } public Operation getOperation() { return operation; } @Override public <Scope> void visit(UserTreeVisitor<Scope> userTreeVisitor, Scope scope) { userTreeVisitor.visitBooleanComp(this, scope); } @Override public <Scope> void visitChildren(UserTreeVisitor<Scope> userTreeVisitor, Scope scope) { leftNode.visit(userTreeVisitor, scope); rightNode.visit(userTreeVisitor, scope); } }
EBooleanComp
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/core/context/ListeningSecurityContextHolderStrategyTests.java
{ "start": 1375, "end": 6155 }
class ____ { @Test public void setContextWhenInvokedThenListenersAreNotified() { SecurityContextHolderStrategy delegate = spy(new MockSecurityContextHolderStrategy()); SecurityContextChangedListener one = mock(SecurityContextChangedListener.class); SecurityContextChangedListener two = mock(SecurityContextChangedListener.class); SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, one, two); given(delegate.createEmptyContext()).willReturn(new SecurityContextImpl()); SecurityContext context = strategy.createEmptyContext(); strategy.setContext(context); strategy.getContext(); verify(one).securityContextChanged(any()); verify(two).securityContextChanged(any()); } @Test public void setContextWhenNoChangeToContextThenListenersAreNotNotified() { SecurityContextHolderStrategy delegate = mock(SecurityContextHolderStrategy.class); SecurityContextChangedListener listener = mock(SecurityContextChangedListener.class); SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, listener); SecurityContext context = new SecurityContextImpl(); given(delegate.getContext()).willReturn(context); strategy.setContext(strategy.getContext()); strategy.getContext(); verifyNoInteractions(listener); } @Test public void clearContextWhenNoGetContextThenContextIsNotRead() { SecurityContextHolderStrategy delegate = mock(SecurityContextHolderStrategy.class); SecurityContextChangedListener listener = mock(SecurityContextChangedListener.class); SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, listener); Supplier<SecurityContext> context = mock(Supplier.class); ArgumentCaptor<SecurityContextChangedEvent> event = ArgumentCaptor.forClass(SecurityContextChangedEvent.class); given(delegate.getDeferredContext()).willReturn(context); given(delegate.getContext()).willAnswer((invocation) -> context.get()); strategy.clearContext(); verifyNoInteractions(context); verify(listener).securityContextChanged(event.capture()); assertThat(event.getValue().isCleared()).isTrue(); strategy.getContext(); verify(context).get(); strategy.clearContext(); verifyNoMoreInteractions(context); } @Test public void getContextWhenCalledMultipleTimesThenEventPublishedOnce() { SecurityContextHolderStrategy delegate = new MockSecurityContextHolderStrategy(); SecurityContextChangedListener listener = mock(SecurityContextChangedListener.class); SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, listener); strategy.setContext(new SecurityContextImpl()); verifyNoInteractions(listener); strategy.getContext(); verify(listener).securityContextChanged(any()); strategy.getContext(); verifyNoMoreInteractions(listener); } @Test public void setContextWhenCalledMultipleTimesThenPublishedEventsAlign() { SecurityContextHolderStrategy delegate = new MockSecurityContextHolderStrategy(); SecurityContextChangedListener listener = mock(SecurityContextChangedListener.class); SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, listener); SecurityContext one = new SecurityContextImpl(new TestingAuthenticationToken("user", "pass")); SecurityContext two = new SecurityContextImpl(new TestingAuthenticationToken("admin", "pass")); ArgumentCaptor<SecurityContextChangedEvent> event = ArgumentCaptor.forClass(SecurityContextChangedEvent.class); strategy.setContext(one); strategy.setContext(two); verifyNoInteractions(listener); strategy.getContext(); verify(listener).securityContextChanged(event.capture()); assertThat(event.getValue().getOldContext()).isEqualTo(one); assertThat(event.getValue().getNewContext()).isEqualTo(two); strategy.getContext(); verifyNoMoreInteractions(listener); strategy.setContext(one); verifyNoMoreInteractions(listener); reset(listener); strategy.getContext(); verify(listener).securityContextChanged(event.capture()); assertThat(event.getValue().getOldContext()).isEqualTo(two); assertThat(event.getValue().getNewContext()).isEqualTo(one); } @Test public void constructorWhenNullDelegateThenIllegalArgument() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy( () -> new ListeningSecurityContextHolderStrategy((SecurityContextHolderStrategy) null, (event) -> { })); } @Test public void constructorWhenNullListenerThenIllegalArgument() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new ListeningSecurityContextHolderStrategy(new ThreadLocalSecurityContextHolderStrategy(), (SecurityContextChangedListener) null)); } }
ListeningSecurityContextHolderStrategyTests
java
apache__camel
components/camel-kubernetes/src/generated/java/org/apache/camel/component/kubernetes/hpa/KubernetesHPAComponentConfigurer.java
{ "start": 741, "end": 3233 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { KubernetesHPAComponent target = (KubernetesHPAComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "kubernetesclient": case "kubernetesClient": target.setKubernetesClient(property(camelContext, io.fabric8.kubernetes.client.KubernetesClient.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public String[] getAutowiredNames() { return new String[]{"kubernetesClient"}; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "kubernetesclient": case "kubernetesClient": return io.fabric8.kubernetes.client.KubernetesClient.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { KubernetesHPAComponent target = (KubernetesHPAComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "kubernetesclient": case "kubernetesClient": return target.getKubernetesClient(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); default: return null; } } }
KubernetesHPAComponentConfigurer
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/state/TestTaskStateManager.java
{ "start": 2776, "end": 14405 }
class ____ implements TaskStateManager { private long reportedCheckpointId; private long notifiedCompletedCheckpointId; private long notifiedAbortedCheckpointId; private Optional<SubTaskInitializationMetrics> reportedInitializationMetrics = Optional.empty(); private final JobID jobId; private final ExecutionAttemptID executionAttemptID; private final Map<Long, TaskStateSnapshot> jobManagerTaskStateSnapshotsByCheckpointId; private final Map<Long, TaskStateSnapshot> taskManagerTaskStateSnapshotsByCheckpointId; private final CheckpointResponder checkpointResponder; private final OneShotLatch waitForReportLatch; private final LocalRecoveryConfig localRecoveryDirectoryProvider; private final StateChangelogStorage<?> stateChangelogStorage; public TestTaskStateManager() { this(TestLocalRecoveryConfig.disabled()); } public TestTaskStateManager(LocalRecoveryConfig localRecoveryConfig) { this( new JobID(), createExecutionAttemptId(), new TestCheckpointResponder(), localRecoveryConfig, new InMemoryStateChangelogStorage(), new HashMap<>(), -1L, new OneShotLatch()); } public TestTaskStateManager( JobID jobId, ExecutionAttemptID executionAttemptID, CheckpointResponder checkpointResponder, LocalRecoveryConfig localRecoveryConfig, @Nullable StateChangelogStorage<?> changelogStorage, Map<Long, TaskStateSnapshot> jobManagerTaskStateSnapshotsByCheckpointId, long reportedCheckpointId, OneShotLatch waitForReportLatch) { this.jobId = checkNotNull(jobId); this.executionAttemptID = checkNotNull(executionAttemptID); this.checkpointResponder = checkNotNull(checkpointResponder); this.localRecoveryDirectoryProvider = checkNotNull(localRecoveryConfig); this.stateChangelogStorage = changelogStorage; this.jobManagerTaskStateSnapshotsByCheckpointId = checkNotNull(jobManagerTaskStateSnapshotsByCheckpointId); this.taskManagerTaskStateSnapshotsByCheckpointId = new HashMap<>(); this.reportedCheckpointId = reportedCheckpointId; this.notifiedCompletedCheckpointId = -1L; this.notifiedAbortedCheckpointId = -1L; this.waitForReportLatch = checkNotNull(waitForReportLatch); } @Override public void reportTaskStateSnapshots( @Nonnull CheckpointMetaData checkpointMetaData, @Nonnull CheckpointMetrics checkpointMetrics, @Nullable TaskStateSnapshot acknowledgedState, @Nullable TaskStateSnapshot localState) { jobManagerTaskStateSnapshotsByCheckpointId.put( checkpointMetaData.getCheckpointId(), acknowledgedState); taskManagerTaskStateSnapshotsByCheckpointId.put( checkpointMetaData.getCheckpointId(), localState); if (checkpointResponder != null) { checkpointResponder.acknowledgeCheckpoint( jobId, executionAttemptID, checkpointMetaData.getCheckpointId(), checkpointMetrics, acknowledgedState); } this.reportedCheckpointId = checkpointMetaData.getCheckpointId(); if (waitForReportLatch != null) { waitForReportLatch.trigger(); } } @Override public InflightDataRescalingDescriptor getInputRescalingDescriptor() { return InflightDataRescalingDescriptor.NO_RESCALE; } @Override public InflightDataRescalingDescriptor getOutputRescalingDescriptor() { return InflightDataRescalingDescriptor.NO_RESCALE; } @Override public void reportIncompleteTaskStateSnapshots( CheckpointMetaData checkpointMetaData, CheckpointMetrics checkpointMetrics) { reportedCheckpointId = checkpointMetaData.getCheckpointId(); } @Override public void reportInitializationMetrics( SubTaskInitializationMetrics subTaskInitializationMetrics) { reportedInitializationMetrics = Optional.of(subTaskInitializationMetrics); } @Override public boolean isTaskDeployedAsFinished() { TaskStateSnapshot jmTaskStateSnapshot = getLastJobManagerTaskStateSnapshot(); if (jmTaskStateSnapshot != null) { return jmTaskStateSnapshot.isTaskDeployedAsFinished(); } return false; } @Override public Optional<Long> getRestoreCheckpointId() { TaskStateSnapshot jmTaskStateSnapshot = getLastJobManagerTaskStateSnapshot(); if (jmTaskStateSnapshot == null) { return Optional.empty(); } return Optional.of(reportedCheckpointId); } @Nonnull @Override public PrioritizedOperatorSubtaskState prioritizedOperatorState(OperatorID operatorID) { TaskStateSnapshot jmTaskStateSnapshot = getLastJobManagerTaskStateSnapshot(); TaskStateSnapshot tmTaskStateSnapshot = getLastTaskManagerTaskStateSnapshot(); if (jmTaskStateSnapshot == null) { return PrioritizedOperatorSubtaskState.emptyNotRestored(); } else { OperatorSubtaskState jmOpState = jmTaskStateSnapshot.getSubtaskStateByOperatorID(operatorID); if (jmOpState == null) { return PrioritizedOperatorSubtaskState.emptyNotRestored(); } else { List<OperatorSubtaskState> tmStateCollection = Collections.emptyList(); if (tmTaskStateSnapshot != null) { OperatorSubtaskState tmOpState = tmTaskStateSnapshot.getSubtaskStateByOperatorID(operatorID); if (tmOpState != null) { tmStateCollection = Collections.singletonList(tmOpState); } } PrioritizedOperatorSubtaskState.Builder builder = new PrioritizedOperatorSubtaskState.Builder( jmOpState, tmStateCollection, reportedCheckpointId); return builder.build(); } } } @Override public Optional<OperatorSubtaskState> getSubtaskJobManagerRestoredState(OperatorID operatorID) { TaskStateSnapshot taskStateSnapshot = jobManagerTaskStateSnapshotsByCheckpointId.get(reportedCheckpointId); if (taskStateSnapshot == null) { return Optional.empty(); } OperatorSubtaskState subtaskState = taskStateSnapshot.getSubtaskStateByOperatorID(operatorID); if (subtaskState == null) { return Optional.empty(); } return Optional.of(subtaskState); } @Nonnull @Override public LocalRecoveryConfig createLocalRecoveryConfig() { return checkNotNull( localRecoveryDirectoryProvider, "Local state directory was never set for this test object!"); } @Override public SequentialChannelStateReader getSequentialChannelStateReader() { return SequentialChannelStateReader.NO_OP; } @Nullable @Override public StateChangelogStorage<?> getStateChangelogStorage() { return stateChangelogStorage; } @Nullable @Override public StateChangelogStorageView<?> getStateChangelogStorageView( Configuration configuration, ChangelogStateHandle changelogStateHandle) { StateChangelogStorageView<?> storageView = null; try { storageView = StateChangelogStorageLoader.loadFromStateHandle( configuration, changelogStateHandle); } catch (IOException e) { ExceptionUtils.rethrow(e); } return storageView; } @Nullable @Override public FileMergingSnapshotManager getFileMergingSnapshotManager() { return null; } @Override public void notifyCheckpointComplete(long checkpointId) throws Exception { this.notifiedCompletedCheckpointId = checkpointId; } @Override public void notifyCheckpointAborted(long checkpointId) { this.notifiedAbortedCheckpointId = checkpointId; } public JobID getJobId() { return jobId; } public Optional<SubTaskInitializationMetrics> getReportedInitializationMetrics() { return reportedInitializationMetrics; } public ExecutionAttemptID getExecutionAttemptID() { return executionAttemptID; } public CheckpointResponder getCheckpointResponder() { return checkpointResponder; } public Map<Long, TaskStateSnapshot> getJobManagerTaskStateSnapshotsByCheckpointId() { return jobManagerTaskStateSnapshotsByCheckpointId; } public void setJobManagerTaskStateSnapshotsByCheckpointId( Map<Long, TaskStateSnapshot> jobManagerTaskStateSnapshotsByCheckpointId) { this.jobManagerTaskStateSnapshotsByCheckpointId.clear(); this.jobManagerTaskStateSnapshotsByCheckpointId.putAll( jobManagerTaskStateSnapshotsByCheckpointId); } public Map<Long, TaskStateSnapshot> getTaskManagerTaskStateSnapshotsByCheckpointId() { return taskManagerTaskStateSnapshotsByCheckpointId; } public void setTaskManagerTaskStateSnapshotsByCheckpointId( Map<Long, TaskStateSnapshot> taskManagerTaskStateSnapshotsByCheckpointId) { this.taskManagerTaskStateSnapshotsByCheckpointId.clear(); this.taskManagerTaskStateSnapshotsByCheckpointId.putAll( taskManagerTaskStateSnapshotsByCheckpointId); } public long getReportedCheckpointId() { return reportedCheckpointId; } public long getNotifiedCompletedCheckpointId() { return notifiedCompletedCheckpointId; } public long getNotifiedAbortedCheckpointId() { return notifiedAbortedCheckpointId; } public void setReportedCheckpointId(long reportedCheckpointId) { this.reportedCheckpointId = reportedCheckpointId; } public TaskStateSnapshot getLastJobManagerTaskStateSnapshot() { return jobManagerTaskStateSnapshotsByCheckpointId != null ? jobManagerTaskStateSnapshotsByCheckpointId.get(reportedCheckpointId) : null; } public TaskStateSnapshot getLastTaskManagerTaskStateSnapshot() { return taskManagerTaskStateSnapshotsByCheckpointId != null ? taskManagerTaskStateSnapshotsByCheckpointId.get(reportedCheckpointId) : null; } public OneShotLatch getWaitForReportLatch() { return waitForReportLatch; } public void restoreLatestCheckpointState( Map<Long, TaskStateSnapshot> taskStateSnapshotsByCheckpointId) { if (taskStateSnapshotsByCheckpointId == null || taskStateSnapshotsByCheckpointId.isEmpty()) { return; } long latestId = -1; for (long id : taskStateSnapshotsByCheckpointId.keySet()) { if (id > latestId) { latestId = id; } } setReportedCheckpointId(latestId); setJobManagerTaskStateSnapshotsByCheckpointId(taskStateSnapshotsByCheckpointId); } @Override public void close() throws Exception {} public static TestTaskStateManagerBuilder builder() { return new TestTaskStateManagerBuilder(); } }
TestTaskStateManager
java
google__dagger
javatests/dagger/internal/codegen/KeyFactoryTest.java
{ "start": 6775, "end": 7527 }
interface ____ { int param1() default 3145; String value() default "default"; } @Test public void forProvidesMethod_sets() { XTypeElement moduleElement = processingEnv.requireTypeElement(SetProvidesMethodsModule.class.getCanonicalName()); for (XMethodElement providesMethod : moduleElement.getDeclaredMethods()) { Key key = keyFactory.forProvidesMethod(providesMethod, moduleElement); assertThat(key.toString()) .isEqualTo( String.format( "java.util.Set<java.lang.String> " + "dagger.internal.codegen.KeyFactoryTest.SetProvidesMethodsModule#%s", getSimpleName(providesMethod))); } } @Module static final
InnerAnnotation
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/StoreQueryUtils.java
{ "start": 2952, "end": 3145 }
interface ____ facilitate stores' query dispatch logic, * allowing them to generically store query execution logic as the values * in a map. */ @FunctionalInterface public
to
java
spring-projects__spring-boot
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/jvm/JvmMetricsAutoConfigurationTests.java
{ "start": 6893, "end": 7085 }
class ____ { @Bean JvmMemoryMetrics customJvmMemoryMetrics() { return new JvmMemoryMetrics(); } } @Configuration(proxyBeanMethods = false) static
CustomJvmMemoryMetricsConfiguration
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/objectarrays/ObjectArrays_assertHasExactlyElementsOfTypes_Test.java
{ "start": 1152, "end": 6150 }
class ____ extends ObjectArraysBaseTest { private static final Object[] ACTUAL = { "a", new LinkedList<>(), 10L }; @Test void should_pass_if_actual_has_exactly_elements_of_the_expected_types_in_order() { arrays.assertHasExactlyElementsOfTypes(INFO, ACTUAL, String.class, LinkedList.class, Long.class); } @Test void should_fail_if_actual_is_null() { // WHEN var error = expectAssertionError(() -> arrays.assertHasExactlyElementsOfTypes(INFO, null, String.class)); // THEN then(error).hasMessage(actualIsNull()); } @Test void should_fail_if_one_element_in_actual_does_not_have_the_expected_type() { // GIVEN Class<?>[] expected = { String.class, LinkedList.class, Double.class }; // WHEN var error = expectAssertionError(() -> arrays.assertHasExactlyElementsOfTypes(INFO, ACTUAL, expected)); // THEN then(error).hasMessage(shouldHaveTypes(ACTUAL, list(expected), list(Double.class), list(Long.class)).create()); } @Test void should_fail_if_types_of_elements_are_not_in_the_same_order_as_expected() { // GIVEN Class<?>[] expected = { LinkedList.class, String.class, Long.class }; // WHEN var error = expectAssertionError(() -> arrays.assertHasExactlyElementsOfTypes(INFO, ACTUAL, expected)); // THEN then(error).hasMessage(elementsTypesDifferAtIndex(ACTUAL[0], LinkedList.class, 0).create()); } @Test void should_fail_if_actual_has_more_elements_than_expected() { // GIVEN Class<?>[] expected = { String.class }; // WHEN var error = expectAssertionError(() -> arrays.assertHasExactlyElementsOfTypes(INFO, ACTUAL, expected)); // THEN then(error).hasMessage(shouldHaveTypes(ACTUAL, list(expected), list(), list(LinkedList.class, Long.class)).create()); } @Test void should_fail_if_actual_elements_types_are_found_but_there_are_not_enough_expected_type_elements() { // GIVEN Class<?>[] expected = { String.class, LinkedList.class, Long.class, Long.class }; // WHEN var error = expectAssertionError(() -> arrays.assertHasExactlyElementsOfTypes(INFO, ACTUAL, expected)); // THEN then(error).hasMessage(shouldHaveTypes(ACTUAL, list(expected), list(Long.class), list()).create()); } // ------------------------------------------------------------------------------------------------------------------ // tests using a custom comparison strategy // ------------------------------------------------------------------------------------------------------------------ @Test void should_pass_if_actual_has_exactly_elements_of_the_expected_types_whatever_the_custom_comparison_strategy_is() { arraysWithCustomComparisonStrategy.assertHasExactlyElementsOfTypes(INFO, ACTUAL, String.class, LinkedList.class, Long.class); } @Test void should_fail_if_one_element_in_actual_does_not_have_the_expected_type_whatever_the_custom_comparison_strategy_is() { // GIVEN Class<?>[] expected = { String.class, LinkedList.class, Double.class }; // WHEN var error = expectAssertionError(() -> arraysWithCustomComparisonStrategy.assertHasExactlyElementsOfTypes(INFO, ACTUAL, expected)); // THEN then(error).hasMessage(shouldHaveTypes(ACTUAL, list(expected), list(Double.class), list(Long.class)).create()); } @Test void should_fail_if_types_of_elements_are_not_in_the_same_order_as_expected_whatever_the_custom_comparison_strategy_is() { // GIVEN Class<?>[] expected = { LinkedList.class, String.class, Long.class }; // WHEN var error = expectAssertionError(() -> arraysWithCustomComparisonStrategy.assertHasExactlyElementsOfTypes(INFO, ACTUAL, expected)); // THEN then(error).hasMessage(elementsTypesDifferAtIndex(ACTUAL[0], LinkedList.class, 0).create()); } @Test void should_fail_if_actual_elements_types_are_found_but_there_are_not_enough_expected_type_elements_whatever_the_custom_comparison_strategy_is() { // GIVEN Class<?>[] expected = { String.class, LinkedList.class, Long.class, Long.class }; // WHEN var error = expectAssertionError(() -> arraysWithCustomComparisonStrategy.assertHasExactlyElementsOfTypes(INFO, ACTUAL, expected)); // THEN then(error).hasMessage(shouldHaveTypes(ACTUAL, list(expected), list(Long.class), list()).create()); } }
ObjectArrays_assertHasExactlyElementsOfTypes_Test
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/MergedContextConfiguration.java
{ "start": 8335, "end": 10673 }
class ____ which the configuration was merged * @param locations the merged context resource locations * @param classes the merged annotated classes * @param contextInitializerClasses the merged context initializer classes * @param activeProfiles the merged active bean definition profiles * @param propertySourceLocations the merged {@code PropertySource} locations * @param propertySourceProperties the merged {@code PropertySource} properties * @param contextLoader the resolved {@code ContextLoader} * @param cacheAwareContextLoaderDelegate a cache-aware context loader * delegate with which to retrieve the parent {@code ApplicationContext} * @param parent the parent configuration or {@code null} if there is no parent * @since 4.1 * @deprecated since 6.1 in favor of * {@link #MergedContextConfiguration(Class, String[], Class[], Set, String[], List, String[], Set, ContextLoader, CacheAwareContextLoaderDelegate, MergedContextConfiguration)} */ @Deprecated(since = "6.1") public MergedContextConfiguration(Class<?> testClass, String @Nullable [] locations, Class<?> @Nullable [] classes, @Nullable Set<Class<? extends ApplicationContextInitializer<?>>> contextInitializerClasses, String @Nullable [] activeProfiles, String @Nullable [] propertySourceLocations, String @Nullable [] propertySourceProperties, ContextLoader contextLoader, @Nullable CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate, @Nullable MergedContextConfiguration parent) { this(testClass, locations, classes, contextInitializerClasses, activeProfiles, propertySourceLocations, propertySourceProperties, EMPTY_CONTEXT_CUSTOMIZERS, contextLoader, cacheAwareContextLoaderDelegate, parent); } /** * Create a new {@code MergedContextConfiguration} instance for the * supplied parameters. * <p>If a {@code null} value is supplied for {@code locations}, * {@code classes}, {@code activeProfiles}, {@code propertySourceLocations}, * or {@code propertySourceProperties} an empty array will be stored instead. * If a {@code null} value is supplied for {@code contextInitializerClasses} * or {@code contextCustomizers}, an empty set will be stored instead. * Furthermore, active profiles will be sorted, and duplicate profiles * will be removed. * @param testClass the test
for
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/java/typeutils/runtime/NullableSerializer.java
{ "start": 10067, "end": 12966 }
class ____<T> extends CompositeTypeSerializerSnapshot<T, NullableSerializer<T>> { private static final int VERSION = 2; private int nullPaddingLength; @SuppressWarnings("unused") public NullableSerializerSnapshot() {} public NullableSerializerSnapshot(NullableSerializer<T> serializerInstance) { super(serializerInstance); this.nullPaddingLength = serializerInstance.nullPaddingLength(); } private NullableSerializerSnapshot(int nullPaddingLength) { checkArgument( nullPaddingLength >= 0, "Computed NULL padding can not be negative. %s", nullPaddingLength); this.nullPaddingLength = nullPaddingLength; } @Override protected int getCurrentOuterSnapshotVersion() { return VERSION; } @Override protected TypeSerializer<?>[] getNestedSerializers(NullableSerializer<T> outerSerializer) { return new TypeSerializer[] {outerSerializer.originalSerializer()}; } @Override protected NullableSerializer<T> createOuterSerializerWithNestedSerializers( TypeSerializer<?>[] nestedSerializers) { checkState( nullPaddingLength >= 0, "Negative padding size after serializer construction: %s", nullPaddingLength); final byte[] padding = (nullPaddingLength == 0) ? EMPTY_BYTE_ARRAY : new byte[nullPaddingLength]; TypeSerializer<T> nestedSerializer = (TypeSerializer<T>) nestedSerializers[0]; return new NullableSerializer<>(nestedSerializer, padding); } @Override protected void writeOuterSnapshot(DataOutputView out) throws IOException { out.writeInt(nullPaddingLength); } @Override protected void readOuterSnapshot( int readOuterSnapshotVersion, DataInputView in, ClassLoader userCodeClassLoader) throws IOException { nullPaddingLength = in.readInt(); } @Override protected OuterSchemaCompatibility resolveOuterSchemaCompatibility( TypeSerializerSnapshot<T> oldSerializerSnapshot) { if (!(oldSerializerSnapshot instanceof NullableSerializerSnapshot)) { return OuterSchemaCompatibility.INCOMPATIBLE; } NullableSerializerSnapshot<T> oldNullableSerializerSnapshot = (NullableSerializerSnapshot<T>) oldSerializerSnapshot; return (nullPaddingLength == oldNullableSerializerSnapshot.nullPaddingLength) ? OuterSchemaCompatibility.COMPATIBLE_AS_IS : OuterSchemaCompatibility.INCOMPATIBLE; } } }
NullableSerializerSnapshot
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/azureaistudio/completion/AzureAiStudioChatCompletionModelTests.java
{ "start": 1135, "end": 7887 }
class ____ extends ESTestCase { public void testOverrideWith_OverridesWithoutValues() { var model = createModel( "id", "target", AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey", 1.0, 2.0, false, 512, null ); var requestTaskSettingsMap = getTaskSettingsMap(null, null, null, null); var overriddenModel = AzureAiStudioChatCompletionModel.of(model, requestTaskSettingsMap); assertThat(overriddenModel, sameInstance(overriddenModel)); } public void testOverrideWith_temperature() { var model = createModel( "id", "target", AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey", 1.0, null, null, null, null ); var requestTaskSettings = getTaskSettingsMap(0.5, null, null, null); var overriddenModel = AzureAiStudioChatCompletionModel.of(model, requestTaskSettings); assertThat( overriddenModel, is( createModel( "id", "target", AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey", 0.5, null, null, null, null ) ) ); } public void testOverrideWith_topP() { var model = createModel( "id", "target", AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey", null, 0.8, null, null, null ); var requestTaskSettings = getTaskSettingsMap(null, 0.5, null, null); var overriddenModel = AzureAiStudioChatCompletionModel.of(model, requestTaskSettings); assertThat( overriddenModel, is( createModel( "id", "target", AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey", null, 0.5, null, null, null ) ) ); } public void testOverrideWith_doSample() { var model = createModel( "id", "target", AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey", null, null, true, null, null ); var requestTaskSettings = getTaskSettingsMap(null, null, false, null); var overriddenModel = AzureAiStudioChatCompletionModel.of(model, requestTaskSettings); assertThat( overriddenModel, is( createModel( "id", "target", AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey", null, null, false, null, null ) ) ); } public void testOverrideWith_maxNewTokens() { var model = createModel( "id", "target", AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey", null, null, null, 512, null ); var requestTaskSettings = getTaskSettingsMap(null, null, null, 128); var overriddenModel = AzureAiStudioChatCompletionModel.of(model, requestTaskSettings); assertThat( overriddenModel, is( createModel( "id", "target", AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey", null, null, null, 128, null ) ) ); } public void testSetsProperUrlForOpenAITokenModel() throws URISyntaxException { var model = createModel("id", "http://testtarget.local", AzureAiStudioProvider.OPENAI, AzureAiStudioEndpointType.TOKEN, "apikey"); assertThat(model.getEndpointUri().toString(), is("http://testtarget.local")); } public void testSetsProperUrlForNonOpenAiTokenModel() throws URISyntaxException { var model = createModel("id", "http://testtarget.local", AzureAiStudioProvider.COHERE, AzureAiStudioEndpointType.TOKEN, "apikey"); assertThat(model.getEndpointUri().toString(), is("http://testtarget.local/v1/chat/completions")); } public void testSetsProperUrlForRealtimeEndpointModel() throws URISyntaxException { var model = createModel( "id", "http://testtarget.local", AzureAiStudioProvider.MISTRAL, AzureAiStudioEndpointType.REALTIME, "apikey" ); assertThat(model.getEndpointUri().toString(), is("http://testtarget.local")); } public static AzureAiStudioChatCompletionModel createModel( String id, String target, AzureAiStudioProvider provider, AzureAiStudioEndpointType endpointType, String apiKey ) { return createModel(id, target, provider, endpointType, apiKey, null, null, null, null, null); } public static AzureAiStudioChatCompletionModel createModel( String id, String target, AzureAiStudioProvider provider, AzureAiStudioEndpointType endpointType, String apiKey, @Nullable Double temperature, @Nullable Double topP, @Nullable Boolean doSample, @Nullable Integer maxNewTokens, @Nullable RateLimitSettings rateLimitSettings ) { return new AzureAiStudioChatCompletionModel( id, TaskType.COMPLETION, "azureaistudio", new AzureAiStudioChatCompletionServiceSettings(target, provider, endpointType, rateLimitSettings), new AzureAiStudioChatCompletionTaskSettings(temperature, topP, doSample, maxNewTokens), new DefaultSecretSettings(new SecureString(apiKey.toCharArray())) ); } }
AzureAiStudioChatCompletionModelTests
java
mockito__mockito
mockito-extensions/mockito-junit-jupiter/src/test/java/org/mockitousage/JunitJupiterSkippedTest.java
{ "start": 1499, "end": 1702 }
class ____ implements BeforeEachCallback { @Override public void beforeEach(ExtensionContext context) { skipTest(); } } private static
SkipTestBeforeEachExtension
java
google__dagger
javatests/dagger/internal/codegen/SubcomponentCreatorValidationTest.java
{ "start": 13168, "end": 13856 }
class ____ {", " Builder(String unused) {}", " abstract ChildComponent build();", " }", "}"); CompilerTests.daggerCompiler(childComponentFile) .compile( subject -> { subject.hasErrorCount(1); subject.hasErrorContaining(messages.invalidConstructor()) .onSource(childComponentFile); }); } @Test public void testCreatorMoreThanOneConstructorFails() { Source childComponentFile = preprocessedJavaSource("test.ChildComponent", "package test;", "", "import dagger.Subcomponent;", "", "@Subcomponent", "abstract
Builder
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/spi/tls/DefaultSslContextFactory.java
{ "start": 1368, "end": 6907 }
class ____ implements SslContextFactory { private final SslProvider sslProvider; private final boolean sslSessionCacheEnabled; public DefaultSslContextFactory(SslProvider sslProvider, boolean sslSessionCacheEnabled) { this.sslProvider = sslProvider; this.sslSessionCacheEnabled = sslSessionCacheEnabled; } private boolean forClient; private boolean forServer; private String serverName; private String endpointIdentificationAlgorithm; private Set<String> enabledProtocols; private Set<String> enabledCipherSuites; private List<String> applicationProtocols; private boolean useAlpn; private ClientAuth clientAuth; private KeyManagerFactory kmf; private TrustManagerFactory tmf; @Override public SslContextFactory useAlpn(boolean useAlpn) { this.useAlpn = useAlpn; return this; } @Override public SslContextFactory forServer(ClientAuth clientAuth) { this.clientAuth = clientAuth; this.forServer = true; return this; } @Override public SslContextFactory forClient(String serverName, String endpointIdentificationAlgorithm) { this.forClient = true; this.serverName = serverName; this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm; return this; } @Override public SslContextFactory enabledProtocols(Set<String> enabledProtocols) { this.enabledProtocols = enabledProtocols; return this; } @Override public SslContextFactory keyMananagerFactory(KeyManagerFactory kmf) { this.kmf = kmf; return this; } @Override public SslContextFactory trustManagerFactory(TrustManagerFactory tmf) { this.tmf = tmf; return this; } @Override public SslContext create() throws SSLException { if (forClient == forServer) { throw new IllegalStateException("Invalid configuration"); } return createContext(useAlpn, forClient, kmf, tmf); } @Override public SslContextFactory enabledCipherSuites(Set<String> enabledCipherSuites) { this.enabledCipherSuites = enabledCipherSuites; return this; } @Override public SslContextFactory applicationProtocols(List<String> applicationProtocols) { this.applicationProtocols = applicationProtocols; return this; } /* If you don't specify a trust store, and you haven't set system properties, the system will try to use either a file called jsssecacerts or cacerts in the JDK/JRE security directory. You can override this by specifying the javax.echo.ssl.trustStore system property If you don't specify a key store, and don't specify a system property no key store will be used You can override this by specifying the javax.echo.ssl.keyStore system property */ private SslContext createContext(boolean useAlpn, boolean client, KeyManagerFactory kmf, TrustManagerFactory tmf) throws SSLException { SslContextBuilder builder; if (client) { builder = SslContextBuilder.forClient(); if (kmf != null) { builder.keyManager(kmf); } } else { builder = SslContextBuilder.forServer(kmf); } Collection<String> cipherSuites = enabledCipherSuites; switch (sslProvider) { case OPENSSL: builder.sslProvider(SslProvider.OPENSSL); if (cipherSuites == null || cipherSuites.isEmpty()) { cipherSuites = OpenSsl.availableOpenSslCipherSuites(); } break; case JDK: builder.sslProvider(SslProvider.JDK); if (cipherSuites == null || cipherSuites.isEmpty()) { cipherSuites = DefaultJDKCipherSuite.get(); } break; default: throw new UnsupportedOperationException(); } if (tmf != null) { builder.trustManager(tmf); } if (cipherSuites != null && cipherSuites.size() > 0) { builder.ciphers(cipherSuites); } if (useAlpn && applicationProtocols != null && applicationProtocols.size() > 0) { ApplicationProtocolConfig.SelectorFailureBehavior sfb; ApplicationProtocolConfig.SelectedListenerFailureBehavior slfb; if (sslProvider == SslProvider.JDK) { sfb = ApplicationProtocolConfig.SelectorFailureBehavior.FATAL_ALERT; slfb = ApplicationProtocolConfig.SelectedListenerFailureBehavior.FATAL_ALERT; } else { // Fatal alert not supportd by OpenSSL sfb = ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE; slfb = ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT; } builder.applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, sfb, slfb, applicationProtocols )); } if (client) { if (serverName != null) { builder.serverName(new SNIHostName(serverName)); } builder.endpointIdentificationAlgorithm(endpointIdentificationAlgorithm == null ? "" : endpointIdentificationAlgorithm); } else { if (clientAuth != null) { builder.clientAuth(clientAuth); } } if (enabledProtocols != null) { builder.protocols(enabledProtocols); } SslContext ctx = builder.build(); if (ctx instanceof OpenSslServerContext){ SSLSessionContext sslSessionContext = ctx.sessionContext(); if (sslSessionContext instanceof OpenSslServerSessionContext){ ((OpenSslServerSessionContext)sslSessionContext).setSessionCacheEnabled(sslSessionCacheEnabled); } } return ctx; } }
DefaultSslContextFactory
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/PluralTableGroup.java
{ "start": 298, "end": 740 }
interface ____ extends TableGroup { PluralAttributeMapping getModelPart(); TableGroup getElementTableGroup(); TableGroup getIndexTableGroup(); default TableGroup getTableGroup(CollectionPart.Nature nature) { switch ( nature ) { case ELEMENT: return getElementTableGroup(); case INDEX: return getIndexTableGroup(); } throw new IllegalStateException( "Could not find table group for: " + nature ); } }
PluralTableGroup
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/data/columnar/vector/RowColumnVector.java
{ "start": 1007, "end": 1093 }
interface ____ extends ColumnVector { ColumnarRowData getRow(int i); }
RowColumnVector
java
alibaba__nacos
api/src/test/java/com/alibaba/nacos/api/naming/remote/response/QueryServiceResponseTest.java
{ "start": 1150, "end": 2929 }
class ____ { protected static ObjectMapper mapper; @BeforeAll static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test void testSerializeSuccessResponse() throws JsonProcessingException { QueryServiceResponse response = QueryServiceResponse.buildSuccessResponse(new ServiceInfo()); String json = mapper.writeValueAsString(response); assertTrue(json.contains("\"serviceInfo\":{")); assertTrue(json.contains("\"resultCode\":200")); assertTrue(json.contains("\"errorCode\":0")); assertTrue(json.contains("\"success\":true")); } @Test void testSerializeFailResponse() throws JsonProcessingException { QueryServiceResponse response = QueryServiceResponse.buildFailResponse("test"); String json = mapper.writeValueAsString(response); assertTrue(json.contains("\"resultCode\":500")); assertTrue(json.contains("\"errorCode\":0")); assertTrue(json.contains("\"message\":\"test\"")); assertTrue(json.contains("\"success\":false")); } @Test void testDeserialize() throws JsonProcessingException { String json = "{\"resultCode\":200,\"errorCode\":0,\"serviceInfo\":{\"cacheMillis\":1000,\"hosts\":[]," + "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"reachProtectionThreshold\":false," + "\"valid\":true},\"success\":true}"; QueryServiceResponse response = mapper.readValue(json, QueryServiceResponse.class); assertNotNull(response.getServiceInfo()); } }
QueryServiceResponseTest
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/TestShufflePlugin.java
{ "start": 2440, "end": 5994 }
interface ____.getReduceId(); context.getJobConf(); context.getLocalFS(); context.getUmbilical(); context.getLocalDirAllocator(); context.getReporter(); context.getCodec(); context.getCombinerClass(); context.getCombineCollector(); context.getSpilledRecordsCounter(); context.getReduceCombineInputCounter(); context.getShuffledMapsCounter(); context.getReduceShuffleBytes(); context.getFailedShuffleCounter(); context.getMergedMapOutputsCounter(); context.getStatus(); context.getCopyPhase(); context.getMergePhase(); context.getReduceTask(); context.getMapOutputFile(); } @Override public void close(){ } @Override public RawKeyValueIterator run() throws java.io.IOException, java.lang.InterruptedException{ return null; } } @Test /** * A testing method instructing core hadoop to load an external ShuffleConsumerPlugin * as if it came from a 3rd party. */ public void testPluginAbility() { try{ // create JobConf with mapreduce.job.shuffle.consumer.plugin=TestShuffleConsumerPlugin JobConf jobConf = new JobConf(); jobConf.setClass(MRConfig.SHUFFLE_CONSUMER_PLUGIN, TestShufflePlugin.TestShuffleConsumerPlugin.class, ShuffleConsumerPlugin.class); ShuffleConsumerPlugin shuffleConsumerPlugin = null; Class<? extends ShuffleConsumerPlugin> clazz = jobConf.getClass(MRConfig.SHUFFLE_CONSUMER_PLUGIN, Shuffle.class, ShuffleConsumerPlugin.class); assertNotNull(clazz, "Unable to get " + MRConfig.SHUFFLE_CONSUMER_PLUGIN); // load 3rd party plugin through core's factory method shuffleConsumerPlugin = ReflectionUtils.newInstance(clazz, jobConf); assertNotNull(shuffleConsumerPlugin, "Unable to load " + MRConfig.SHUFFLE_CONSUMER_PLUGIN); } catch (Exception e) { assertTrue(false, "Threw exception:" + e); } } @Test /** * A testing method verifying availability and accessibility of API that is needed * for sub-classes of ShuffleConsumerPlugin */ public void testConsumerApi() { JobConf jobConf = new JobConf(); ShuffleConsumerPlugin<K, V> shuffleConsumerPlugin = new TestShuffleConsumerPlugin<K, V>(); //mock creation ReduceTask mockReduceTask = mock(ReduceTask.class); TaskUmbilicalProtocol mockUmbilical = mock(TaskUmbilicalProtocol.class); Reporter mockReporter = mock(Reporter.class); FileSystem mockFileSystem = mock(FileSystem.class); Class<? extends org.apache.hadoop.mapred.Reducer> combinerClass = jobConf.getCombinerClass(); @SuppressWarnings("unchecked") // needed for mock with generic CombineOutputCollector<K, V> mockCombineOutputCollector = (CombineOutputCollector<K, V>) mock(CombineOutputCollector.class); org.apache.hadoop.mapreduce.TaskAttemptID mockTaskAttemptID = mock(org.apache.hadoop.mapreduce.TaskAttemptID.class); LocalDirAllocator mockLocalDirAllocator = mock(LocalDirAllocator.class); CompressionCodec mockCompressionCodec = mock(CompressionCodec.class); Counter mockCounter = mock(Counter.class); TaskStatus mockTaskStatus = mock(TaskStatus.class); Progress mockProgress = mock(Progress.class); MapOutputFile mockMapOutputFile = mock(MapOutputFile.class); Task mockTask = mock(Task.class); try { String [] dirs = jobConf.getLocalDirs(); // verify that these APIs are available through super
context
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cache/PendingBulkOperationCleanupActionTest.java
{ "start": 2631, "end": 4945 }
class ____ implements SettingProvider.Provider<TestCachingRegionFactory> { @Override public TestCachingRegionFactory getSetting() { return CACHING_REGION_FACTORY; } } @BeforeEach public void before(SessionFactoryScope scope) { scope.inTransaction( session -> session.persist( new Customer( 1, "Samuel" ) ) ); CACHING_REGION_FACTORY.getTestDomainDataRegion().getTestEntityDataAccess().reset(); } @AfterEach public void after(SessionFactoryScope scope) { scope.inTransaction( session -> session.createQuery( "delete Customer" ).executeUpdate() ); CACHING_REGION_FACTORY.getTestDomainDataRegion().getTestEntityDataAccess().reset(); } @Test public void testUpdateCachedEntity(SessionFactoryScope scope) { scope.inTransaction( session -> session.createNativeQuery( "update Customer set id = id" ).executeUpdate() ); assertThat( isLockRegionCalled() ) .as( "EntityDataAccess lockRegion method has not been called" ) .isTrue(); // Region unlock is a BulkOperationCleanUpAction executed after Transaction commit assertThat( isUnlockRegionCalled() ) .as( "EntityDataAccess unlockRegion method has not been called" ) .isTrue(); } @Test public void testPendingBulkOperationActionsAreExecutedWhenSessionIsClosed(SessionFactoryScope scope) { scope.inSession( session -> session.createNativeQuery( "update Customer set id = id" ).executeUpdate() ); assertThat( isLockRegionCalled() ) .as( "EntityDataAccess lockRegion method has not been called" ) .isTrue(); // Because the update is executed outside a transaction, region unlock BulkOperationCleanUpAction has not been executed // and when the session is closed it's a pending action assertThat( isUnlockRegionCalled() ) .as( "EntityDataAccess unlockRegion method has not been called" ) .isTrue(); } private static boolean isUnlockRegionCalled() { return CACHING_REGION_FACTORY.getTestDomainDataRegion() .getTestEntityDataAccess() .isUnlockRegionCalled(); } private static boolean isLockRegionCalled() { return CACHING_REGION_FACTORY.getTestDomainDataRegion() .getTestEntityDataAccess() .isLockRegionCalled(); } @Entity(name = "Customer") @Table(name = "Customer") @Cacheable public static
CacheRegionFactoryProvider
java
micronaut-projects__micronaut-core
aop/src/main/java/io/micronaut/aop/runtime/RuntimeProxy.java
{ "start": 1144, "end": 1395 }
class ____ should be used at runtime to create a proxy. * * @return The runtime proxy creator bean class */ Class<? extends RuntimeProxyCreator> value(); /** * <p>By default Micronaut will compile subclasses of the target
that
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesPodsEndpointBuilderFactory.java
{ "start": 23062, "end": 33279 }
interface ____ extends EndpointProducerBuilder { default AdvancedKubernetesPodsEndpointProducerBuilder advanced() { return (AdvancedKubernetesPodsEndpointProducerBuilder) this; } /** * The Kubernetes API Version to use. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param apiVersion the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder apiVersion(String apiVersion) { doSetProperty("apiVersion", apiVersion); return this; } /** * The dns domain, used for ServiceCall EIP. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param dnsDomain the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder dnsDomain(String dnsDomain) { doSetProperty("dnsDomain", dnsDomain); return this; } /** * Default KubernetesClient to use if provided. * * The option is a: * <code>io.fabric8.kubernetes.client.KubernetesClient</code> type. * * Group: common * * @param kubernetesClient the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder kubernetesClient(io.fabric8.kubernetes.client.KubernetesClient kubernetesClient) { doSetProperty("kubernetesClient", kubernetesClient); return this; } /** * Default KubernetesClient to use if provided. * * The option will be converted to a * <code>io.fabric8.kubernetes.client.KubernetesClient</code> type. * * Group: common * * @param kubernetesClient the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder kubernetesClient(String kubernetesClient) { doSetProperty("kubernetesClient", kubernetesClient); return this; } /** * The namespace. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param namespace the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder namespace(String namespace) { doSetProperty("namespace", namespace); return this; } /** * The port name, used for ServiceCall EIP. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param portName the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder portName(String portName) { doSetProperty("portName", portName); return this; } /** * The port protocol, used for ServiceCall EIP. * * The option is a: <code>java.lang.String</code> type. * * Default: tcp * Group: common * * @param portProtocol the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder portProtocol(String portProtocol) { doSetProperty("portProtocol", portProtocol); return this; } /** * Producer operation to do on Kubernetes. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param operation the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder operation(String operation) { doSetProperty("operation", operation); return this; } /** * The CA Cert Data. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param caCertData the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder caCertData(String caCertData) { doSetProperty("caCertData", caCertData); return this; } /** * The CA Cert File. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param caCertFile the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder caCertFile(String caCertFile) { doSetProperty("caCertFile", caCertFile); return this; } /** * The Client Cert Data. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param clientCertData the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder clientCertData(String clientCertData) { doSetProperty("clientCertData", clientCertData); return this; } /** * The Client Cert File. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param clientCertFile the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder clientCertFile(String clientCertFile) { doSetProperty("clientCertFile", clientCertFile); return this; } /** * The Key Algorithm used by the client. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param clientKeyAlgo the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder clientKeyAlgo(String clientKeyAlgo) { doSetProperty("clientKeyAlgo", clientKeyAlgo); return this; } /** * The Client Key data. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param clientKeyData the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder clientKeyData(String clientKeyData) { doSetProperty("clientKeyData", clientKeyData); return this; } /** * The Client Key file. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param clientKeyFile the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder clientKeyFile(String clientKeyFile) { doSetProperty("clientKeyFile", clientKeyFile); return this; } /** * The Client Key Passphrase. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param clientKeyPassphrase the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder clientKeyPassphrase(String clientKeyPassphrase) { doSetProperty("clientKeyPassphrase", clientKeyPassphrase); return this; } /** * The Auth Token. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param oauthToken the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder oauthToken(String oauthToken) { doSetProperty("oauthToken", oauthToken); return this; } /** * Password to connect to Kubernetes. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param password the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder password(String password) { doSetProperty("password", password); return this; } /** * Define if the certs we used are trusted anyway or not. * * The option is a: <code>java.lang.Boolean</code> type. * * Default: false * Group: security * * @param trustCerts the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder trustCerts(Boolean trustCerts) { doSetProperty("trustCerts", trustCerts); return this; } /** * Define if the certs we used are trusted anyway or not. * * The option will be converted to a <code>java.lang.Boolean</code> * type. * * Default: false * Group: security * * @param trustCerts the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder trustCerts(String trustCerts) { doSetProperty("trustCerts", trustCerts); return this; } /** * Username to connect to Kubernetes. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param username the value to set * @return the dsl builder */ default KubernetesPodsEndpointProducerBuilder username(String username) { doSetProperty("username", username); return this; } } /** * Advanced builder for endpoint producers for the Kubernetes Pods component. */ public
KubernetesPodsEndpointProducerBuilder
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/struct/TestPOJOAsArray.java
{ "start": 2578, "end": 2693 }
class ____ { public int x = 1; public int y = 2; } @JsonFormat(shape=Shape.ARRAY) static
B
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SmooksEndpointBuilderFactory.java
{ "start": 1498, "end": 1621 }
interface ____ { /** * Builder for endpoint for the Smooks component. */ public
SmooksEndpointBuilderFactory
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/aggs/changepoint/ChangeDetector.java
{ "start": 23079, "end": 24779 }
class ____ { double sumOfSqrs; double sum; double count; static RunningStats from(double[] values, IntToDoubleFunction weightFunction) { return new RunningStats().addValues(values, weightFunction, 0, values.length); } RunningStats() {} double count() { return count; } double mean() { return sum / count; } double variance() { return Math.max((sumOfSqrs - ((sum * sum) / count)) / count, 0.0); } double std() { return Math.sqrt(variance()); } RunningStats addValues(double[] value, IntToDoubleFunction weightFunction, int start, int end) { for (int i = start; i < value.length && i < end; i++) { addValue(value[i], weightFunction.applyAsDouble(i)); } return this; } RunningStats addValue(double value, double weight) { sumOfSqrs += (value * value * weight); count += weight; sum += (value * weight); return this; } RunningStats removeValue(double value, double weight) { sumOfSqrs = Math.max(sumOfSqrs - value * value * weight, 0); count = Math.max(count - weight, 0); sum -= (value * weight); return this; } RunningStats removeValues(double[] value, IntToDoubleFunction weightFunction, int start, int end) { for (int i = start; i < value.length && i < end; i++) { removeValue(value[i], weightFunction.applyAsDouble(i)); } return this; } } }
RunningStats
java
apache__camel
components/camel-cometd/src/test/java/org/apache/camel/component/cometd/CometdProducerConsumerInteractiveExtensionManualTest.java
{ "start": 3324, "end": 4376 }
class ____ implements BayeuxServer.Extension, ServerSession.RemovedListener { private HashSet<String> forbidden = new HashSet<>(Arrays.asList("one", "two")); @Override public void removed(ServerSession session, ServerMessage message, boolean timeout) { // called on remove of client } @Override public boolean rcv(ServerSession from, ServerMessage.Mutable message) { return true; } @Override public boolean rcvMeta(ServerSession from, ServerMessage.Mutable message) { return true; } @Override public boolean send(ServerSession from, ServerSession to, ServerMessage.Mutable message) { Object data = message.getData(); if (forbidden.contains(data)) { message.put("data", "***"); } return true; } @Override public boolean sendMeta(ServerSession from, ServerMessage.Mutable message) { return true; } } }
Censor
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/web/server/OAuth2LoginTests.java
{ "start": 36869, "end": 37118 }
class ____ { @Bean InMemoryReactiveClientRegistrationRepository clientRegistrationRepository() { return new InMemoryReactiveClientRegistrationRepository(github, google); } } @EnableWebFlux static
OAuth2LoginWithMultipleClientRegistrations
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/asm/ClassVisitor.java
{ "start": 17088, "end": 17201 }
class ____ been visited. */ public void visitEnd() { if (cv != null) { cv.visitEnd(); } } }
have
java
elastic__elasticsearch
test/yaml-rest-runner/src/test/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCaseTests.java
{ "start": 814, "end": 3931 }
class ____ extends ESTestCase { public void testLoadAllYamlSuites() throws Exception { Map<String, Set<Path>> yamlSuites = ESClientYamlSuiteTestCase.loadSuites(""); assertEquals(2, yamlSuites.size()); } public void testLoadSingleYamlSuite() throws Exception { Map<String, Set<Path>> yamlSuites = ESClientYamlSuiteTestCase.loadSuites("suite1/10_basic"); assertSingleFile(yamlSuites, "suite1", "10_basic.yml"); // extension .yaml is optional yamlSuites = ESClientYamlSuiteTestCase.loadSuites("suite1/10_basic"); assertSingleFile(yamlSuites, "suite1", "10_basic.yml"); } public void testLoadMultipleYamlSuites() throws Exception { // single directory Map<String, Set<Path>> yamlSuites = ESClientYamlSuiteTestCase.loadSuites("suite1"); assertThat(yamlSuites, notNullValue()); assertThat(yamlSuites.size(), equalTo(1)); assertThat(yamlSuites.containsKey("suite1"), equalTo(true)); assertThat(yamlSuites.get("suite1").size(), greaterThan(1)); // multiple directories yamlSuites = ESClientYamlSuiteTestCase.loadSuites("suite1", "suite2"); assertThat(yamlSuites, notNullValue()); assertThat(yamlSuites.size(), equalTo(2)); assertThat(yamlSuites.containsKey("suite1"), equalTo(true)); assertEquals(2, yamlSuites.get("suite1").size()); assertThat(yamlSuites.containsKey("suite2"), equalTo(true)); assertEquals(2, yamlSuites.get("suite2").size()); // multiple paths, which can be both directories or yaml test suites (with optional file extension) yamlSuites = ESClientYamlSuiteTestCase.loadSuites("suite2/10_basic", "suite1"); assertThat(yamlSuites, notNullValue()); assertThat(yamlSuites.size(), equalTo(2)); assertThat(yamlSuites.containsKey("suite2"), equalTo(true)); assertThat(yamlSuites.get("suite2").size(), equalTo(1)); assertSingleFile(yamlSuites.get("suite2"), "suite2", "10_basic.yml"); assertThat(yamlSuites.containsKey("suite1"), equalTo(true)); assertThat(yamlSuites.get("suite1").size(), greaterThan(1)); // files can be loaded from classpath and from file system too Path dir = createTempDir(); Path file = dir.resolve("test_loading.yml"); Files.createFile(file); } private static void assertSingleFile(Map<String, Set<Path>> yamlSuites, String dirName, String fileName) { assertThat(yamlSuites, notNullValue()); assertThat(yamlSuites.size(), equalTo(1)); assertThat(yamlSuites.containsKey(dirName), equalTo(true)); assertSingleFile(yamlSuites.get(dirName), dirName, fileName); } private static void assertSingleFile(Set<Path> files, String dirName, String fileName) { assertThat(files.size(), equalTo(1)); Path file = files.iterator().next(); assertThat(file.getFileName().toString(), equalTo(fileName)); assertThat(file.toAbsolutePath().getParent().getFileName().toString(), equalTo(dirName)); } }
ESClientYamlSuiteTestCaseTests
java
quarkusio__quarkus
integration-tests/grpc-plain-text-mutiny/src/test/java/io/quarkus/grpc/examples/hello/GrpcMockTest.java
{ "start": 477, "end": 1437 }
class ____ { @InjectMock @GrpcClient("hello") Greeter greeter; @Inject BeanCallingservice beanCallingService; @Test void test1() { HelloRequest request = HelloRequest.newBuilder().setName("clement").build(); Mockito.when(greeter.sayHello(Mockito.any(HelloRequest.class))) .thenReturn(Uni.createFrom().item(HelloReply.newBuilder().setMessage("hello clement").build())); Assertions.assertEquals(greeter.sayHello(request).await().indefinitely().getMessage(), "hello clement"); } @Test void test2() { HelloRequest request = HelloRequest.newBuilder().setName("roxanne").build(); Mockito.when(greeter.sayHello(request)) .thenReturn(Uni.createFrom().item(HelloReply.newBuilder().setMessage("hello roxanne").build())); Assertions.assertEquals(beanCallingService.call(), "hello roxanne"); } @ApplicationScoped public static
GrpcMockTest
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/parameters/MatrixParamExtractor.java
{ "start": 148, "end": 650 }
class ____ implements ParameterExtractor { private final String name; private final boolean single; private final boolean encoded; public MatrixParamExtractor(String name, boolean single, boolean encoded) { this.name = name; this.single = single; this.encoded = encoded; } @Override public Object extractParameter(ResteasyReactiveRequestContext context) { return context.getMatrixParameter(name, single, encoded); } }
MatrixParamExtractor
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/operator/SequenceFloatBlockSourceOperator.java
{ "start": 807, "end": 2412 }
class ____ extends AbstractBlockSourceOperator { static final int DEFAULT_MAX_PAGE_POSITIONS = 8 * 1024; private final float[] values; public SequenceFloatBlockSourceOperator(BlockFactory blockFactory, Stream<Float> values) { this(blockFactory, values, DEFAULT_MAX_PAGE_POSITIONS); } public SequenceFloatBlockSourceOperator(BlockFactory blockFactory, Stream<Float> values, int maxPagePositions) { super(blockFactory, maxPagePositions); var l = values.toList(); this.values = new float[l.size()]; IntStream.range(0, l.size()).forEach(i -> this.values[i] = l.get(i)); } public SequenceFloatBlockSourceOperator(BlockFactory blockFactory, List<Float> values) { this(blockFactory, values, DEFAULT_MAX_PAGE_POSITIONS); } public SequenceFloatBlockSourceOperator(BlockFactory blockFactory, List<Float> values, int maxPagePositions) { super(blockFactory, maxPagePositions); this.values = new float[values.size()]; IntStream.range(0, this.values.length).forEach(i -> this.values[i] = values.get(i)); } @Override protected Page createPage(int positionOffset, int length) { FloatVector.FixedBuilder builder = blockFactory.newFloatVectorFixedBuilder(length); for (int i = 0; i < length; i++) { builder.appendFloat(values[positionOffset + i]); } currentPosition += length; return new Page(builder.build().asBlock()); } protected int remaining() { return values.length - currentPosition; } }
SequenceFloatBlockSourceOperator
java
netty__netty
codec-haproxy/src/main/java/io/netty/handler/codec/haproxy/HAProxyMessageEncoder.java
{ "start": 1202, "end": 5673 }
class ____ extends MessageToByteEncoder<HAProxyMessage> { private static final int V2_VERSION_BITMASK = 0x02 << 4; // Length for source/destination addresses for the UNIX family must be 108 bytes each. static final int UNIX_ADDRESS_BYTES_LENGTH = 108; static final int TOTAL_UNIX_ADDRESS_BYTES_LENGTH = UNIX_ADDRESS_BYTES_LENGTH * 2; public static final HAProxyMessageEncoder INSTANCE = new HAProxyMessageEncoder(); private HAProxyMessageEncoder() { super(HAProxyMessage.class); } @Override protected void encode(ChannelHandlerContext ctx, HAProxyMessage msg, ByteBuf out) throws Exception { switch (msg.protocolVersion()) { case V1: encodeV1(msg, out); break; case V2: encodeV2(msg, out); break; default: throw new HAProxyProtocolException("Unsupported version: " + msg.protocolVersion()); } } private static void encodeV1(HAProxyMessage msg, ByteBuf out) { out.writeBytes(TEXT_PREFIX); out.writeByte((byte) ' '); out.writeCharSequence(msg.proxiedProtocol().name(), CharsetUtil.US_ASCII); out.writeByte((byte) ' '); out.writeCharSequence(msg.sourceAddress(), CharsetUtil.US_ASCII); out.writeByte((byte) ' '); out.writeCharSequence(msg.destinationAddress(), CharsetUtil.US_ASCII); out.writeByte((byte) ' '); out.writeCharSequence(String.valueOf(msg.sourcePort()), CharsetUtil.US_ASCII); out.writeByte((byte) ' '); out.writeCharSequence(String.valueOf(msg.destinationPort()), CharsetUtil.US_ASCII); out.writeByte((byte) '\r'); out.writeByte((byte) '\n'); } private static void encodeV2(HAProxyMessage msg, ByteBuf out) { out.writeBytes(BINARY_PREFIX); out.writeByte(V2_VERSION_BITMASK | msg.command().byteValue()); out.writeByte(msg.proxiedProtocol().byteValue()); switch (msg.proxiedProtocol().addressFamily()) { case AF_IPv4: case AF_IPv6: byte[] srcAddrBytes = NetUtil.createByteArrayFromIpAddressString(msg.sourceAddress()); byte[] dstAddrBytes = NetUtil.createByteArrayFromIpAddressString(msg.destinationAddress()); // srcAddrLen + dstAddrLen + 4 (srcPort + dstPort) + numTlvBytes out.writeShort(srcAddrBytes.length + dstAddrBytes.length + 4 + msg.tlvNumBytes()); out.writeBytes(srcAddrBytes); out.writeBytes(dstAddrBytes); out.writeShort(msg.sourcePort()); out.writeShort(msg.destinationPort()); encodeTlvs(msg.tlvs(), out); break; case AF_UNIX: out.writeShort(TOTAL_UNIX_ADDRESS_BYTES_LENGTH + msg.tlvNumBytes()); int srcAddrBytesWritten = out.writeCharSequence(msg.sourceAddress(), CharsetUtil.US_ASCII); out.writeZero(UNIX_ADDRESS_BYTES_LENGTH - srcAddrBytesWritten); int dstAddrBytesWritten = out.writeCharSequence(msg.destinationAddress(), CharsetUtil.US_ASCII); out.writeZero(UNIX_ADDRESS_BYTES_LENGTH - dstAddrBytesWritten); encodeTlvs(msg.tlvs(), out); break; case AF_UNSPEC: out.writeShort(0); break; default: throw new HAProxyProtocolException("unexpected addrFamily"); } } private static void encodeTlv(HAProxyTLV haProxyTLV, ByteBuf out) { if (haProxyTLV instanceof HAProxySSLTLV) { HAProxySSLTLV ssltlv = (HAProxySSLTLV) haProxyTLV; out.writeByte(haProxyTLV.typeByteValue()); out.writeShort(ssltlv.contentNumBytes()); out.writeByte(ssltlv.client()); out.writeInt(ssltlv.verify()); encodeTlvs(ssltlv.encapsulatedTLVs(), out); } else { out.writeByte(haProxyTLV.typeByteValue()); ByteBuf value = haProxyTLV.content(); int readableBytes = value.readableBytes(); out.writeShort(readableBytes); out.writeBytes(value.readSlice(readableBytes)); } } private static void encodeTlvs(List<HAProxyTLV> haProxyTLVs, ByteBuf out) { for (int i = 0; i < haProxyTLVs.size(); i++) { encodeTlv(haProxyTLVs.get(i), out); } } }
HAProxyMessageEncoder
java
apache__kafka
clients/src/test/java/org/apache/kafka/clients/admin/KafkaAdminClientTest.java
{ "start": 578138, "end": 578821 }
class ____ extends KafkaAdminClient.TimeoutProcessorFactory { private int numTries = 0; private int failuresInjected = 0; @Override public KafkaAdminClient.TimeoutProcessor create(long now) { return new FailureInjectingTimeoutProcessor(now); } synchronized boolean shouldInjectFailure() { numTries++; if (numTries == 1) { failuresInjected++; return true; } return false; } public synchronized int failuresInjected() { return failuresInjected; } public final
FailureInjectingTimeoutProcessorFactory
java
mapstruct__mapstruct
core/src/main/java/org/mapstruct/TargetType.java
{ "start": 939, "end": 1079 }
interface ____ { * CarEntity carDtoToCar(CarDto dto); * } * </code></pre> * <pre><code class='java'> * // generates * public
CarMapper
java
google__dagger
javatests/dagger/internal/codegen/MultibindingTest.java
{ "start": 13477, "end": 14004 }
class ____ @Inject constructor(map: Map<String, MyInterface>)"); Source parentModule = CompilerTests.kotlinSource( "test.ParentModule.kt", "@file:Suppress(\"INLINE_FROM_HIGHER_PLATFORM\")", // Required to use TODO() "package test", "", "import dagger.Module", "import dagger.Provides", "import dagger.multibindings.IntoMap", "import dagger.multibindings.StringKey", "", "@Module", "
Usage
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/interceptor/IndicesAliasesRequestInterceptor.java
{ "start": 1886, "end": 6678 }
class ____ implements RequestInterceptor { private final ThreadContext threadContext; private final XPackLicenseState licenseState; private final AuditTrailService auditTrailService; private final boolean dlsFlsEnabled; public IndicesAliasesRequestInterceptor( ThreadContext threadContext, XPackLicenseState licenseState, AuditTrailService auditTrailService, boolean dlsFlsEnabled ) { this.threadContext = threadContext; this.licenseState = licenseState; this.auditTrailService = auditTrailService; this.dlsFlsEnabled = dlsFlsEnabled; } @Override public SubscribableListener<Void> intercept( RequestInfo requestInfo, AuthorizationEngine authorizationEngine, AuthorizationInfo authorizationInfo ) { if (requestInfo.getRequest() instanceof IndicesAliasesRequest request) { final AuditTrail auditTrail = auditTrailService.get(); final boolean isDlsLicensed = DOCUMENT_LEVEL_SECURITY_FEATURE.checkWithoutTracking(licenseState); final boolean isFlsLicensed = FIELD_LEVEL_SECURITY_FEATURE.checkWithoutTracking(licenseState); IndicesAccessControl indicesAccessControl = INDICES_PERMISSIONS_VALUE.get(threadContext); if (dlsFlsEnabled && (isDlsLicensed || isFlsLicensed)) { for (IndicesAliasesRequest.AliasActions aliasAction : request.getAliasActions()) { if (aliasAction.actionType() == IndicesAliasesRequest.AliasActions.Type.ADD) { for (String index : aliasAction.indices()) { IndicesAccessControl.IndexAccessControl indexAccessControl = indicesAccessControl.getIndexPermissions(index); if (indexAccessControl != null && (indexAccessControl.getFieldPermissions().hasFieldLevelSecurity() || indexAccessControl.getDocumentPermissions().hasDocumentLevelPermissions())) { return SubscribableListener.newFailed( new ElasticsearchSecurityException( "Alias requests are not allowed for " + "users who have field or document level security enabled on one of the indices", RestStatus.BAD_REQUEST ) ); } } } } } Map<String, List<String>> indexToAliasesMap = request.getAliasActions() .stream() .filter(aliasAction -> aliasAction.actionType() == IndicesAliasesRequest.AliasActions.Type.ADD) .flatMap( aliasActions -> Arrays.stream(aliasActions.indices()) .map(indexName -> new Tuple<>(indexName, Arrays.asList(aliasActions.aliases()))) ) .collect(Collectors.toMap(Tuple::v1, Tuple::v2, (existing, toMerge) -> { List<String> list = new ArrayList<>(existing.size() + toMerge.size()); list.addAll(existing); list.addAll(toMerge); return list; })); final SubscribableListener<Void> listener = new SubscribableListener<>(); authorizationEngine.validateIndexPermissionsAreSubset( requestInfo, authorizationInfo, indexToAliasesMap, wrapPreservingContext(ActionListener.wrap(authzResult -> { if (authzResult.isGranted()) { // do not audit success again listener.onResponse(null); } else { auditTrail.accessDenied( AuditUtil.extractRequestId(threadContext), requestInfo.getAuthentication(), requestInfo.getAction(), request, authorizationInfo ); listener.onFailure( Exceptions.authorizationError( "Adding an alias is not allowed when the alias " + "has more permissions than any of the indices" ) ); } }, listener::onFailure), threadContext) ); return listener; } else { return SubscribableListener.nullSuccess(); } } }
IndicesAliasesRequestInterceptor
java
apache__camel
tooling/camel-tooling-model/src/test/java/org/apache/camel/tooling/model/ComponentOptionModelTest.java
{ "start": 969, "end": 1487 }
class ____ { ComponentModel.ComponentOptionModel componentOptionModelUnderTest; @BeforeEach public void setup() { componentOptionModelUnderTest = new ComponentModel.ComponentOptionModel(); } @Test public void getShortTypeShouldSucceed() { componentOptionModelUnderTest.setJavaType("java.util.concurrent.BlockingQueue<org.apache.camel.Exchange>"); Assertions.assertEquals("BlockingQueue", componentOptionModelUnderTest.getShortJavaType()); } }
ComponentOptionModelTest
java
google__guava
android/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java
{ "start": 6751, "end": 8323 }
class ____ implements Comparable<HashHostileComparable> { final String string; public HashHostileComparable(String string) { this.string = string; } @Override public int hashCode() { throw new UnsupportedOperationException(); } @Override public int compareTo(HashHostileComparable o) { return string.compareTo(o.string); } } public void testSortedBuilderWithExpectedValuesPerKeyPositive() { ImmutableSetMultimap.Builder<String, HashHostileComparable> builder = ImmutableSetMultimap.<String, HashHostileComparable>builder() .expectedValuesPerKey(2) .orderValuesBy(Ordering.natural()); HashHostileComparable v1 = new HashHostileComparable("value1"); HashHostileComparable v2 = new HashHostileComparable("value2"); builder.put("key", v1); builder.put("key", v2); assertThat(builder.build().entries()).hasSize(2); } public void testBuilder_withImmutableEntry() { ImmutableSetMultimap<String, Integer> multimap = new Builder<String, Integer>().put(Maps.immutableEntry("one", 1)).build(); assertEquals(ImmutableSet.of(1), multimap.get("one")); } public void testBuilder_withImmutableEntryAndNullContents() { Builder<String, Integer> builder = new Builder<>(); assertThrows( NullPointerException.class, () -> builder.put(Maps.immutableEntry("one", (Integer) null))); assertThrows( NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); } private static
HashHostileComparable
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestCallQueueManager.java
{ "start": 13187, "end": 18687 }
class ____ { public ExceptionFakeScheduler() { throw new IllegalArgumentException("Exception caused by " + "scheduler constructor.!!"); } } private static final Class<? extends RpcScheduler> exceptionSchedulerClass = CallQueueManager.convertSchedulerClass( ExceptionFakeScheduler.class); private static final Class<? extends BlockingQueue<ExceptionFakeCall>> exceptionQueueClass = CallQueueManager.convertQueueClass( ExceptionFakeCall.class, ExceptionFakeCall.class); @Test public void testCallQueueConstructorException() throws InterruptedException { try { new CallQueueManager<ExceptionFakeCall>(exceptionQueueClass, schedulerClass, false, 10, "", new Configuration()); fail(); } catch (RuntimeException re) { assertTrue(re.getCause() instanceof IllegalArgumentException); assertEquals("Exception caused by call queue constructor.!!", re .getCause() .getMessage()); } } @Test public void testSchedulerConstructorException() throws InterruptedException { try { new CallQueueManager<FakeCall>(queueClass, exceptionSchedulerClass, false, 10, "", new Configuration()); fail(); } catch (RuntimeException re) { assertTrue(re.getCause() instanceof IllegalArgumentException); assertEquals("Exception caused by scheduler constructor.!!", re.getCause() .getMessage()); } } @SuppressWarnings("unchecked") @Test public void testCallQueueOverflowExceptions() throws Exception { RpcScheduler scheduler = mock(RpcScheduler.class); BlockingQueue<Schedulable> queue = mock(BlockingQueue.class); CallQueueManager<Schedulable> cqm = spy(new CallQueueManager<>(queue, scheduler, false, false)); CallQueueManager<Schedulable> cqmTriggerFailover = spy(new CallQueueManager<>(queue, scheduler, false, true)); Schedulable call = new FakeCall(0); // call queue exceptions that trigger failover cqmTriggerFailover.setClientBackoffEnabled(true); doReturn(Boolean.TRUE).when(cqmTriggerFailover).shouldBackOff(call); try { cqmTriggerFailover.put(call); fail("didn't fail"); } catch (Exception ex) { assertEquals(CallQueueOverflowException.FAILOVER.getCause().getMessage(), ex.getCause().getMessage()); } // call queue exceptions passed threw as-is doThrow(CallQueueOverflowException.KEEPALIVE).when(queue).add(call); try { cqm.add(call); fail("didn't throw"); } catch (CallQueueOverflowException cqe) { assertSame(CallQueueOverflowException.KEEPALIVE, cqe); } // standard exception for blocking queue full converted to overflow // exception. doThrow(new IllegalStateException()).when(queue).add(call); try { cqm.add(call); fail("didn't throw"); } catch (Exception ex) { assertTrue(ex instanceof CallQueueOverflowException, ex.toString()); } // backoff disabled, put is put to queue. reset(queue); cqm.setClientBackoffEnabled(false); cqm.put(call); verify(queue, times(1)).put(call); verify(queue, times(0)).add(call); // backoff enabled, put is add to queue. reset(queue); cqm.setClientBackoffEnabled(true); doReturn(Boolean.FALSE).when(cqm).shouldBackOff(call); cqm.put(call); verify(queue, times(0)).put(call); verify(queue, times(1)).add(call); reset(queue); // backoff is enabled, put + scheduler backoff = overflow exception. reset(queue); cqm.setClientBackoffEnabled(true); doReturn(Boolean.TRUE).when(cqm).shouldBackOff(call); try { cqm.put(call); fail("didn't fail"); } catch (Exception ex) { assertTrue(ex instanceof CallQueueOverflowException, ex.toString()); } verify(queue, times(0)).put(call); verify(queue, times(0)).add(call); // backoff is enabled, add + scheduler backoff = overflow exception. reset(queue); cqm.setClientBackoffEnabled(true); doReturn(Boolean.TRUE).when(cqm).shouldBackOff(call); try { cqm.add(call); fail("didn't fail"); } catch (Exception ex) { assertTrue(ex instanceof CallQueueOverflowException, ex.toString()); } verify(queue, times(0)).put(call); verify(queue, times(0)).add(call); } @Test public void testCallQueueOverEnabled() { // default ipc.callqueue.overflow.trigger.failover' configure false. String ns = "ipc.8888"; conf.setBoolean("ipc.callqueue.overflow.trigger.failover", false); manager = new CallQueueManager<>(fcqueueClass, rpcSchedulerClass, false, 10, ns, conf); assertFalse(manager.isServerFailOverEnabled()); assertFalse(manager.isServerFailOverEnabledByQueue()); // set ipc.8888.callqueue.overflow.trigger.failover configure true. conf.setBoolean("ipc.8888.callqueue.overflow.trigger.failover", true); manager = new CallQueueManager<>(fcqueueClass, rpcSchedulerClass, false, 10, ns, conf); assertTrue(manager.isServerFailOverEnabled()); assertTrue(manager.isServerFailOverEnabledByQueue()); // set ipc.callqueue.overflow.trigger.failover' configure true. conf.setBoolean("ipc.callqueue.overflow.trigger.failover", true); manager = new CallQueueManager<>(fcqueueClass, rpcSchedulerClass, false, 10, ns, conf); assertTrue(manager.isServerFailOverEnabled()); assertTrue(manager.isServerFailOverEnabledByQueue()); } }
ExceptionFakeScheduler
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/binding/WrongNamespacesTest.java
{ "start": 811, "end": 1284 }
class ____ { @Test void shouldFailForWrongNamespace() { Configuration configuration = new Configuration(); Assertions.assertThrows(RuntimeException.class, () -> configuration.addMapper(WrongNamespaceMapper.class)); } @Test void shouldFailForMissingNamespace() { Configuration configuration = new Configuration(); Assertions.assertThrows(RuntimeException.class, () -> configuration.addMapper(MissingNamespaceMapper.class)); } }
WrongNamespacesTest
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/domain/contacts/Contact.java
{ "start": 943, "end": 2751 }
class ____ { private Integer id; private Name name; private Gender gender; private LocalDate birthDay; private Contact alternativeContact; private List<Address> addresses; private List<PhoneNumber> phoneNumbers; public Contact() { } public Contact(Integer id, Name name, Gender gender, LocalDate birthDay) { this.id = id; this.name = name; this.gender = gender; this.birthDay = birthDay; } @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } @Temporal( TemporalType.DATE ) @Column( table = "contact_supp" ) public LocalDate getBirthDay() { return birthDay; } public void setBirthDay(LocalDate birthDay) { this.birthDay = birthDay; } @ManyToOne(fetch = FetchType.LAZY) public Contact getAlternativeContact() { return alternativeContact; } public void setAlternativeContact(Contact alternativeContact) { this.alternativeContact = alternativeContact; } @ElementCollection @CollectionTable( name = "contact_addresses" ) // NOTE : because of the @OrderColumn `addresses` is a List, while `phoneNumbers` is // a BAG which is a List with no persisted order @OrderColumn public List<Address> getAddresses() { return addresses; } public void setAddresses(List<Address> addresses) { this.addresses = addresses; } @ElementCollection @CollectionTable( name = "contact_phones" ) public List<PhoneNumber> getPhoneNumbers() { return phoneNumbers; } public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) { this.phoneNumbers = phoneNumbers; } @Embeddable public static
Contact
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/webapp/dao/AppsInfo.java
{ "start": 1265, "end": 1516 }
class ____ { protected ArrayList<AppInfo> app = new ArrayList<>(); public AppsInfo() { // JAXB needs this } public void add(AppInfo appinfo) { app.add(appinfo); } public ArrayList<AppInfo> getApps() { return app; } }
AppsInfo
java
spring-projects__spring-boot
module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/Empty.java
{ "start": 794, "end": 1015 }
class ____ { private static final Consumer<?> EMPTY_CUSTOMIZER = (t) -> { }; private Empty() { } @SuppressWarnings("unchecked") static <T> Consumer<T> consumer() { return (Consumer<T>) EMPTY_CUSTOMIZER; } }
Empty
java
apache__camel
components/camel-pulsar/src/main/java/org/apache/camel/component/pulsar/PulsarMessageReceipt.java
{ "start": 1335, "end": 2695 }
interface ____ { /** * Acknowledge receipt of this message synchronously. * * @see org.apache.pulsar.client.api.Consumer#acknowledge(MessageId) */ void acknowledge() throws PulsarClientException; /** * Acknowledge receipt of all of the messages in the stream up to and including this message synchronously. * * @see org.apache.pulsar.client.api.Consumer#acknowledgeCumulative(MessageId) */ void acknowledgeCumulative() throws PulsarClientException; /** * Acknowledge receipt of this message asynchronously. * * @see org.apache.pulsar.client.api.Consumer#acknowledgeAsync(MessageId) */ CompletableFuture<Void> acknowledgeAsync(); /** * Acknowledge receipt of all of the messages in the stream up to and including this message asynchronously. * * @see org.apache.pulsar.client.api.Consumer#acknowledgeCumulativeAsync(MessageId) */ CompletableFuture<Void> acknowledgeCumulativeAsync(); /** * Acknowledge the failure to process this message. * * @see org.apache.pulsar.client.api.Consumer#negativeAcknowledge(MessageId) Note: Available in Puslar 2.4.0. * Implementations with earlier versions should return an {@link java.lang.UnsupportedOperationException}. */ void negativeAcknowledge(); }
PulsarMessageReceipt
java
apache__flink
flink-end-to-end-tests/flink-stream-state-ttl-test/src/main/java/org/apache/flink/streaming/tests/verify/ValueWithTs.java
{ "start": 4162, "end": 5368 }
class ____ extends CompositeTypeSerializerSnapshot<ValueWithTs<?>, Serializer> { private static final int VERSION = 2; @SuppressWarnings("unused") public ValueWithTsSerializerSnapshot() {} ValueWithTsSerializerSnapshot(Serializer serializerInstance) { super(serializerInstance); } @Override protected int getCurrentOuterSnapshotVersion() { return VERSION; } @Override protected TypeSerializer<?>[] getNestedSerializers(Serializer outerSerializer) { return new TypeSerializer[] { outerSerializer.getValueSerializer(), outerSerializer.getTimestampSerializer() }; } @SuppressWarnings("unchecked") @Override protected Serializer createOuterSerializerWithNestedSerializers( TypeSerializer<?>[] nestedSerializers) { TypeSerializer<?> valueSerializer = nestedSerializers[0]; TypeSerializer<Long> timestampSerializer = (TypeSerializer<Long>) nestedSerializers[1]; return new Serializer(valueSerializer, timestampSerializer); } } }
ValueWithTsSerializerSnapshot
java
alibaba__nacos
api/src/test/java/com/alibaba/nacos/api/naming/listener/FuzzyWatchChangeEventTest.java
{ "start": 863, "end": 2690 }
class ____ { @BeforeEach void setUp() throws Exception { } @Test void testFuzzyWatchChangeEventWithEmptyConstructor() { FuzzyWatchChangeEvent event = new FuzzyWatchChangeEvent(); assertNull(event.getServiceName()); assertNull(event.getGroupName()); assertNull(event.getNamespace()); assertNull(event.getChangeType()); assertNull(event.getSyncType()); } @Test void testFuzzyWatchChangeEventWithFullConstructor() { FuzzyWatchChangeEvent event = new FuzzyWatchChangeEvent("service", "group", "namespace", "ADD_SERVICE", "FUZZY_WATCH_INIT_NOTIFY"); assertEquals("service", event.getServiceName()); assertEquals("group", event.getGroupName()); assertEquals("namespace", event.getNamespace()); assertEquals("ADD_SERVICE", event.getChangeType()); assertEquals("FUZZY_WATCH_INIT_NOTIFY", event.getSyncType()); } @Test void testToString() { FuzzyWatchChangeEvent event = new FuzzyWatchChangeEvent("service", "group", "namespace", "ADD_SERVICE", "FUZZY_WATCH_INIT_NOTIFY"); String expected = "FuzzyWatchChangeEvent{serviceName='service', groupName='group', namespace='namespace'," + " changeType='ADD_SERVICE', syncType='FUZZY_WATCH_INIT_NOTIFY'}"; assertEquals(expected, event.toString()); } @Test void testFuzzyWatchChangeEventWithNullValues() { FuzzyWatchChangeEvent event = new FuzzyWatchChangeEvent(null, null, null, null, null); assertNull(event.getServiceName()); assertNull(event.getGroupName()); assertNull(event.getNamespace()); assertNull(event.getChangeType()); assertNull(event.getSyncType()); } }
FuzzyWatchChangeEventTest
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/Assertions_catchReflectiveOperationException_Test.java
{ "start": 1149, "end": 2745 }
class ____ { @Test void catchReflectiveOperationException_should_fail_with_good_message_if_wrong_type() { // GIVEN ThrowingCallable code = () -> catchReflectiveOperationException(raisingException("boom!!")); // WHEN var assertionError = expectAssertionError(code); // THEN assertThat(assertionError).hasMessageContainingAll(ReflectiveOperationException.class.getName(), Exception.class.getName()); } @Test void catchReflectiveOperationException_should_succeed_and_return_actual_instance_with_correct_class() { // GIVEN final ReflectiveOperationException expected = new ReflectiveOperationException("boom!!"); // WHEN ReflectiveOperationException actual = catchReflectiveOperationException(codeThrowing(expected)); // THEN then(actual).isSameAs(expected); } @Test void catchReflectiveOperationException_should_succeed_and_return_null_if_no_exception_thrown() { // WHEN var error = expectAssertionError(() -> catchReflectiveOperationException(() -> {})); // THEN then(error).hasMessage("Expecting code to raise a ReflectiveOperationException"); } @Test void catchReflectiveOperationException_should_catch_mocked_throwable() { // GIVEN ReflectiveOperationException exception = mock(); // WHEN Throwable actual = catchReflectiveOperationException(codeThrowing(exception)); // THEN then(actual).isSameAs(exception); } static ThrowingCallable raisingException(final String reason) { return codeThrowing(new Exception(reason)); } }
Assertions_catchReflectiveOperationException_Test
java
apache__camel
components/camel-dynamic-router/src/test/java/org/apache/camel/component/dynamicrouter/routing/DynamicRouterComponentTest.java
{ "start": 2537, "end": 7184 }
class ____ { static final String DYNAMIC_ROUTER_CHANNEL = "test"; @RegisterExtension static CamelContextExtension contextExtension = new DefaultCamelContextExtension(); @Mock protected DynamicRouterProducer producer; @Mock DynamicRouterEndpoint endpoint; @Mock DynamicRouterProcessor processor; @Mock PrioritizedFilter prioritizedFilter; @Mock DynamicRouterFilterService filterService; DynamicRouterComponent component; CamelContext context; DynamicRouterEndpointFactory endpointFactory; DynamicRouterProcessorFactory processorFactory; DynamicRouterProducerFactory producerFactory; BiFunction<CamelContext, Expression, RecipientList> recipientListSupplier; PrioritizedFilterFactory prioritizedFilterFactory; DynamicRouterFilterServiceFactory filterServiceFactory; @BeforeEach void setup() { context = contextExtension.getContext(); endpointFactory = new DynamicRouterEndpointFactory() { @Override public DynamicRouterEndpoint getInstance( final String uri, final DynamicRouterComponent component, final DynamicRouterConfiguration configuration, final Supplier<DynamicRouterProcessorFactory> processorFactorySupplier, final Supplier<DynamicRouterProducerFactory> producerFactorySupplier, final BiFunction<CamelContext, Expression, RecipientList> recipientListSupplier, final DynamicRouterFilterService filterService) { return endpoint; } }; processorFactory = new DynamicRouterProcessorFactory() { @Override public DynamicRouterProcessor getInstance( CamelContext camelContext, DynamicRouterConfiguration configuration, DynamicRouterFilterService filterService, final BiFunction<CamelContext, Expression, RecipientList> recipientListSupplier) { return processor; } }; producerFactory = new DynamicRouterProducerFactory() { @Override public DynamicRouterProducer getInstance( DynamicRouterEndpoint endpoint, DynamicRouterComponent component, DynamicRouterConfiguration configuration) { return producer; } }; prioritizedFilterFactory = new PrioritizedFilterFactory() { @Override public PrioritizedFilter getInstance( String id, int priority, Predicate predicate, String endpoint, PrioritizedFilterStatistics statistics) { return prioritizedFilter; } }; filterServiceFactory = new DynamicRouterFilterServiceFactory() { @Override public DynamicRouterFilterService getInstance(Supplier<PrioritizedFilterFactory> filterFactory) { return filterService; } }; component = new DynamicRouterComponent( () -> endpointFactory, () -> processorFactory, () -> producerFactory, recipientListSupplier, () -> prioritizedFilterFactory, () -> filterServiceFactory); } @Test void testCreateEndpoint() throws Exception { component.setCamelContext(context); Endpoint actualEndpoint = component.createEndpoint("dynamic-router:testname", "remaining", Collections.emptyMap()); assertEquals(endpoint, actualEndpoint); } @Test void testCreateEndpointWithEmptyRemainingError() { component.setCamelContext(context); assertThrows(IllegalArgumentException.class, () -> component.createEndpoint("dynamic-router:testname", "", Collections.emptyMap())); } @Test void testAddRoutingProcessor() { component.addRoutingProcessor(DYNAMIC_ROUTER_CHANNEL, processor); assertEquals(processor, component.getRoutingProcessor(DYNAMIC_ROUTER_CHANNEL)); } @Test void testAddRoutingProcessorWithSecondProcessorForChannelError() { component.addRoutingProcessor(DYNAMIC_ROUTER_CHANNEL, processor); assertEquals(processor, component.getRoutingProcessor(DYNAMIC_ROUTER_CHANNEL)); assertThrows(IllegalArgumentException.class, () -> component.addRoutingProcessor(DYNAMIC_ROUTER_CHANNEL, processor)); } @Test void testDefaultConstruction() { DynamicRouterComponent instance = new DynamicRouterComponent(); Assertions.assertNotNull(instance); } }
DynamicRouterComponentTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/filter/subclass/singletable/SingleTableTest.java
{ "start": 415, "end": 885 }
class ____ extends SubClassTest { @Override protected void persistTestData(SessionImplementor session) { createHuman( session, false, 90 ); createHuman( session, false, 100 ); createHuman( session, true, 110 ); } private void createHuman(SessionImplementor session, boolean pregnant, int iq) { Human human = new Human(); human.setName( "Homo Sapiens" ); human.setPregnant( pregnant ); human.setIq( iq ); session.persist( human ); } }
SingleTableTest
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/method/support/UriComponentsContributor.java
{ "start": 1195, "end": 2097 }
interface ____ { /** * Whether this contributor supports the given method parameter. */ boolean supportsParameter(MethodParameter parameter); /** * Process the given method argument and either update the * {@link UriComponentsBuilder} or add to the map with URI variables * to use to expand the URI after all arguments are processed. * @param parameter the controller method parameter (never {@code null}) * @param value the argument value (possibly {@code null}) * @param builder the builder to update (never {@code null}) * @param uriVariables a map to add URI variables to (never {@code null}) * @param conversionService a ConversionService to format values as Strings */ void contributeMethodArgument(MethodParameter parameter, Object value, UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService); }
UriComponentsContributor
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java
{ "start": 79210, "end": 79459 }
class ____ { public static String from(Number no) { return "Number:" + no; } public static String from(Integer no) { return "Integer:" + no; } public static String from(Object no) { return "Object:" + no; } } }
DistanceEnforcer
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/SystemExitOutsideMainTest.java
{ "start": 5394, "end": 5566 }
class ____ { public static void main(String[] args) { System.exit(0); } } """) .doTest(); } }
Test
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/annotation/AnnotationMetadata.java
{ "start": 31721, "end": 32141 }
enum ____ * @return An {@link Optional} class */ default <E extends Enum<E>> Optional<E> enumValue(@NonNull Class<? extends Annotation> annotation, @NonNull String member, Class<E> enumType) { ArgumentUtils.requireNonNull("annotation", annotation); ArgumentUtils.requireNonNull("member", member); return enumValue(annotation.getName(), member, enumType); } /** * The
type
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/enrich/action/GetEnrichPolicyAction.java
{ "start": 1186, "end": 1511 }
class ____ extends ActionType<GetEnrichPolicyAction.Response> { public static final GetEnrichPolicyAction INSTANCE = new GetEnrichPolicyAction(); public static final String NAME = "cluster:admin/xpack/enrich/get"; private GetEnrichPolicyAction() { super(NAME); } public static
GetEnrichPolicyAction
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java
{ "start": 252695, "end": 252846 }
class ____ { Two[] DR = new Two[] {new Two()}; public Two holder = new Two(); public Two[] getDR() { return DR; } } public static
Payload
java
quarkusio__quarkus
test-framework/junit5-component/src/test/java/io/quarkus/test/component/ProgrammaticLookupMockTest.java
{ "start": 855, "end": 1021 }
class ____ { @Inject Instance<Delta> delta; boolean ping() { return delta.get().ping(); } } }
ProgrammaticLookComponent
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/SimpleProcessorIdAwareTest.java
{ "start": 1270, "end": 2954 }
class ____ extends ContextTestSupport { @Test public void testIdAware() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World"); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); List<Processor> matches = context.getRoute("foo").filter("b*"); assertEquals(2, matches.size()); Processor bar = matches.get(0); Processor baz = matches.get(1); assertEquals("bar", ((IdAware) bar).getId()); assertEquals("baz", ((IdAware) baz).getId()); bar = context.getProcessor("bar"); assertNotNull(bar); baz = context.getProcessor("baz"); assertNotNull(baz); Processor unknown = context.getProcessor("unknown"); assertNull(unknown); Processor result = context.getProcessor("result"); assertNotNull(result); ProcessorDefinition def = context.getProcessorDefinition("result"); assertNotNull(def); assertEquals("result", def.getId()); SendDefinition send = assertIsInstanceOf(SendDefinition.class, def); assertNotNull(send); assertEquals("mock:result", send.getEndpointUri()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").routeId("foo").choice().when(header("bar")).to("log:bar").id("bar").otherwise() .to("mock:result").id("result").end().to("log:baz").id("baz"); } }; } }
SimpleProcessorIdAwareTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/StringFieldTest_special_3.java
{ "start": 221, "end": 2121 }
class ____ extends TestCase { public void test_special() throws Exception { Model model = new Model(); StringBuilder buf = new StringBuilder(); for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { buf.append((char) i); } model.name = buf.toString(); StringWriter writer = new StringWriter(); JSON.writeJSONString(writer, model); String json = writer.toString(); Model model2 = JSON.parseObject(json, Model.class); Assert.assertEquals(model.name, model2.name); } public void test_special_browsecue() throws Exception { Model model = new Model(); StringBuilder buf = new StringBuilder(); for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { buf.append((char) i); } model.name = buf.toString(); StringWriter writer = new StringWriter(); JSON.writeJSONString(writer, model, SerializerFeature.BrowserSecure); String text = writer.toString(); text = text.replaceAll("&lt;", "<"); text = text.replaceAll("&gt;", ">"); Model model2 = JSON.parseObject(text, Model.class); assertEquals(model.name, model2.name); } public void test_special_browsecompatible() throws Exception { Model model = new Model(); StringBuilder buf = new StringBuilder(); for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { buf.append((char) i); } model.name = buf.toString(); StringWriter writer = new StringWriter(); JSON.writeJSONString(writer, model, SerializerFeature.BrowserCompatible); Model model2 = JSON.parseObject(writer.toString(), Model.class); Assert.assertEquals(model.name, model2.name); } private static
StringFieldTest_special_3
java
spring-projects__spring-framework
spring-jdbc/src/test/java/org/springframework/jdbc/core/support/SqlBinaryValueTests.java
{ "start": 1199, "end": 3796 }
class ____ { @Test void withByteArray() throws SQLException { byte[] content = new byte[] {0, 1, 2}; SqlBinaryValue value = new SqlBinaryValue(content); PreparedStatement ps = mock(); value.setTypeValue(ps, 1, JdbcUtils.TYPE_UNKNOWN, null); verify(ps).setBytes(1, content); } @Test void withByteArrayForBlob() throws SQLException { byte[] content = new byte[] {0, 1, 2}; SqlBinaryValue value = new SqlBinaryValue(content); PreparedStatement ps = mock(); value.setTypeValue(ps, 1, Types.BLOB, null); verify(ps).setBlob(eq(1), any(ByteArrayInputStream.class), eq(3L)); } @Test void withInputStream() throws SQLException { InputStream content = new ByteArrayInputStream(new byte[] {0, 1, 2}); SqlBinaryValue value = new SqlBinaryValue(content, 3); PreparedStatement ps = mock(); value.setTypeValue(ps, 1, JdbcUtils.TYPE_UNKNOWN, null); verify(ps).setBinaryStream(1, content, 3L); } @Test void withInputStreamForBlob() throws SQLException { InputStream content = new ByteArrayInputStream(new byte[] {0, 1, 2}); SqlBinaryValue value = new SqlBinaryValue(content, 3); PreparedStatement ps = mock(); value.setTypeValue(ps, 1, Types.BLOB, null); verify(ps).setBlob(1, content, 3L); } @Test void withInputStreamSource() throws SQLException { InputStream content = new ByteArrayInputStream(new byte[] {0, 1, 2}); SqlBinaryValue value = new SqlBinaryValue(() -> content, 3); PreparedStatement ps = mock(); value.setTypeValue(ps, 1, JdbcUtils.TYPE_UNKNOWN, null); verify(ps).setBinaryStream(1, content, 3L); } @Test void withInputStreamSourceForBlob() throws SQLException { InputStream content = new ByteArrayInputStream(new byte[] {0, 1, 2}); SqlBinaryValue value = new SqlBinaryValue(() -> content, 3); PreparedStatement ps = mock(); value.setTypeValue(ps, 1, Types.BLOB, null); verify(ps).setBlob(1, content, 3L); } @Test void withResource() throws SQLException { byte[] content = new byte[] {0, 1, 2}; SqlBinaryValue value = new SqlBinaryValue(new ByteArrayResource(content)); PreparedStatement ps = mock(); value.setTypeValue(ps, 1, JdbcUtils.TYPE_UNKNOWN, null); verify(ps).setBinaryStream(eq(1), any(ByteArrayInputStream.class), eq(3L)); } @Test void withResourceForBlob() throws SQLException { InputStream content = new ByteArrayInputStream(new byte[] {0, 1, 2}); SqlBinaryValue value = new SqlBinaryValue(() -> content, 3); PreparedStatement ps = mock(); value.setTypeValue(ps, 1, Types.BLOB, null); verify(ps).setBlob(eq(1), any(ByteArrayInputStream.class), eq(3L)); } }
SqlBinaryValueTests
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/dataframe/DestinationIndex.java
{ "start": 2793, "end": 18426 }
class ____ { private static final Logger logger = LogManager.getLogger(DestinationIndex.class); public static final String INCREMENTAL_ID = "ml__incremental_id"; /** * The field that indicates whether a doc was used for training or not */ public static final String IS_TRAINING = "is_training"; // Metadata fields static final String CREATION_DATE_MILLIS = "creation_date_in_millis"; static final String VERSION = "version"; static final String CREATED = "created"; static final String CREATED_BY = "created_by"; static final String ANALYTICS = "analytics"; private static final String PROPERTIES = "properties"; private static final String META = "_meta"; private static final String RUNTIME = "runtime"; private static final String DFA_CREATOR = "data-frame-analytics"; /** * We only preserve the most important settings. * If the user needs other settings on the destination index they * should create the destination index before starting the analytics. */ private static final String[] PRESERVED_SETTINGS = new String[] { "index.number_of_shards", "index.number_of_replicas", "index.analysis.*", "index.similarity.*", "index.mapping.*" }; /** * This is the minimum compatible version of the destination index we can currently work with. * If the results mappings change in a way existing destination indices will fail to index * the results, this should be bumped accordingly. */ public static final MlConfigVersion MIN_COMPATIBLE_VERSION = StartDataFrameAnalyticsAction.TaskParams.VERSION_DESTINATION_INDEX_MAPPINGS_CHANGED; private DestinationIndex() {} /** * Creates destination index based on source index metadata. */ public static void createDestinationIndex( Client client, Clock clock, DataFrameAnalyticsConfig analyticsConfig, String[] destIndexAllowedSettings, ActionListener<CreateIndexResponse> listener ) { prepareCreateIndexRequest( client, clock, analyticsConfig, destIndexAllowedSettings, listener.delegateFailureAndWrap( (l, createIndexRequest) -> ClientHelper.executeWithHeadersAsync( analyticsConfig.getHeaders(), ClientHelper.ML_ORIGIN, client, TransportCreateIndexAction.TYPE, createIndexRequest, l ) ) ); } private static void prepareCreateIndexRequest( Client client, Clock clock, DataFrameAnalyticsConfig config, String[] destIndexAllowedSettings, ActionListener<CreateIndexRequest> listener ) { GetSettingsRequest getSettingsRequest = new GetSettingsRequest(MachineLearning.HARD_CODED_MACHINE_LEARNING_MASTER_NODE_TIMEOUT) .indices(config.getSource().getIndex()) .indicesOptions(IndicesOptions.lenientExpandOpen()) .names(PRESERVED_SETTINGS); ClientHelper.executeWithHeadersAsync( config.getHeaders(), ML_ORIGIN, client, GetSettingsAction.INSTANCE, getSettingsRequest, listener.delegateFailureAndWrap((delegate, settingsResponse) -> { final Settings settings = settings(settingsResponse, destIndexAllowedSettings); MappingsMerger.mergeMappings( client, MachineLearning.HARD_CODED_MACHINE_LEARNING_MASTER_NODE_TIMEOUT, config.getHeaders(), config.getSource(), delegate.delegateFailureAndWrap( (l, mappings) -> getFieldCapsForRequiredFields( client, config, l.delegateFailureAndWrap( (ll, fieldCapabilitiesResponse) -> ll.onResponse( createIndexRequest(clock, config, settings, mappings, fieldCapabilitiesResponse) ) ) ) ) ); }) ); } private static void getFieldCapsForRequiredFields( Client client, DataFrameAnalyticsConfig config, ActionListener<FieldCapabilitiesResponse> listener ) { List<RequiredField> requiredFields = config.getAnalysis().getRequiredFields(); if (requiredFields.isEmpty()) { listener.onResponse(null); return; } FieldCapabilitiesRequest fieldCapabilitiesRequest = new FieldCapabilitiesRequest().indices(config.getSource().getIndex()) .fields(requiredFields.stream().map(RequiredField::getName).toArray(String[]::new)) .runtimeFields(config.getSource().getRuntimeMappings()); ClientHelper.executeWithHeadersAsync( config.getHeaders(), ML_ORIGIN, client, TransportFieldCapabilitiesAction.TYPE, fieldCapabilitiesRequest, listener ); } private static CreateIndexRequest createIndexRequest( Clock clock, DataFrameAnalyticsConfig config, Settings settings, MappingMetadata mappings, FieldCapabilitiesResponse fieldCapabilitiesResponse ) { String destinationIndex = config.getDest().getIndex(); Map<String, Object> mappingsAsMap = mappings.sourceAsMap(); Map<String, Object> properties = getOrPutDefault(mappingsAsMap, PROPERTIES, HashMap::new); checkResultsFieldIsNotPresentInProperties(config, properties); properties.putAll(createAdditionalMappings(config, fieldCapabilitiesResponse)); Map<String, Object> metadata = getOrPutDefault(mappingsAsMap, META, HashMap::new); metadata.putAll(createMetadata(config.getId(), clock, MlConfigVersion.CURRENT)); if (config.getSource().getRuntimeMappings().isEmpty() == false) { Map<String, Object> runtimeMappings = getOrPutDefault(mappingsAsMap, RUNTIME, HashMap::new); runtimeMappings.putAll(config.getSource().getRuntimeMappings()); } return new CreateIndexRequest(destinationIndex, settings).mapping(mappingsAsMap); } private static Settings settings(GetSettingsResponse settingsResponse, String[] destIndexAllowedSettings) { Settings.Builder settingsBuilder = Settings.builder(); for (String key : destIndexAllowedSettings) { Long value = findMaxSettingValue(settingsResponse, key); if (value != null) { settingsBuilder.put(key, value); } } Map<String, Tuple<String, Settings>> mergedSettings = new HashMap<>(); mergeSimilaritySettings(settingsResponse, mergedSettings); mergeAnalysisSettings(settingsResponse, mergedSettings); for (String settingsKey : Arrays.asList( IndexModule.SIMILARITY_SETTINGS_PREFIX, AnalysisRegistry.INDEX_ANALYSIS_FILTER, AnalysisRegistry.INDEX_ANALYSIS_ANALYZER )) { for (Map.Entry<String, Tuple<String, Settings>> mergedSetting : mergedSettings.entrySet()) { String index = mergedSetting.getValue().v1(); Set<String> settingsKeys = settingsResponse.getIndexToSettings().get(index).getAsSettings(settingsKey).keySet(); for (String key : settingsKeys) { settingsBuilder = settingsBuilder.copy(settingsKey + "." + key, settingsResponse.getIndexToSettings().get(index)); } } } return settingsBuilder.build(); } private static void mergeSimilaritySettings(GetSettingsResponse settingsResponse, Map<String, Tuple<String, Settings>> mergedSettings) { String settingsKey = IndexModule.SIMILARITY_SETTINGS_PREFIX; for (Map.Entry<String, Settings> settingsEntry : settingsResponse.getIndexToSettings().entrySet()) { Settings settings = settingsEntry.getValue().getAsSettings(settingsKey); if (settings.isEmpty()) { continue; } mergeSettings(settingsKey, settingsEntry.getKey(), settings, mergedSettings); } } private static void mergeAnalysisSettings(GetSettingsResponse settingsResponse, Map<String, Tuple<String, Settings>> mergedSettings) { for (String settingsKey : Arrays.asList(AnalysisRegistry.INDEX_ANALYSIS_FILTER, AnalysisRegistry.INDEX_ANALYSIS_ANALYZER)) { for (Map.Entry<String, Settings> settingsEntry : settingsResponse.getIndexToSettings().entrySet()) { Settings settings = settingsEntry.getValue().getAsSettings(settingsKey); if (settings.isEmpty()) { continue; } for (String name : settings.names()) { Settings setting = settings.getAsSettings(name); String fullName = settingsKey + "." + name; mergeSettings(fullName, settingsEntry.getKey(), setting, mergedSettings); } } } } private static void mergeSettings(String key, String index, Settings setting, Map<String, Tuple<String, Settings>> mergedSettings) { if (mergedSettings.containsKey(key) == false) { mergedSettings.put(key, new Tuple<>(index, setting)); } else { Settings mergedSetting = mergedSettings.get(key).v2(); if (mergedSetting.equals(setting) == false) { throw ExceptionsHelper.badRequestException( "cannot merge settings because of differences for " + key + "; specified as [{}] in index [{}]; " + "specified as [{}] in index [{}]", mergedSettings.get(key).v2(), mergedSettings.get(key).v1(), setting.toString(), index ); } } } @Nullable private static Long findMaxSettingValue(GetSettingsResponse settingsResponse, String settingKey) { Long maxValue = null; for (Settings settings : settingsResponse.getIndexToSettings().values()) { Long indexValue = settings.getAsLong(settingKey, null); if (indexValue != null) { maxValue = maxValue == null ? indexValue : Math.max(indexValue, maxValue); } } return maxValue; } private static Map<String, Object> createAdditionalMappings( DataFrameAnalyticsConfig config, FieldCapabilitiesResponse fieldCapabilitiesResponse ) { Map<String, Object> properties = new HashMap<>(); properties.put(INCREMENTAL_ID, Map.of("type", NumberFieldMapper.NumberType.LONG.typeName())); properties.putAll(config.getAnalysis().getResultMappings(config.getDest().getResultsField(), fieldCapabilitiesResponse)); return properties; } // Visible for testing static Map<String, Object> createMetadata(String analyticsId, Clock clock, MlConfigVersion version) { Map<String, Object> metadata = new HashMap<>(); metadata.put(CREATION_DATE_MILLIS, clock.millis()); metadata.put(CREATED_BY, DFA_CREATOR); metadata.put(VERSION, Map.of(CREATED, version.toString())); metadata.put(ANALYTICS, analyticsId); return metadata; } @SuppressWarnings("unchecked") private static <K, V> V getOrPutDefault(Map<K, Object> map, K key, Supplier<V> valueSupplier) { V value = (V) map.get(key); if (value == null) { value = valueSupplier.get(); map.put(key, value); } return value; } @SuppressWarnings("unchecked") public static void updateMappingsToDestIndex( Client client, DataFrameAnalyticsConfig config, GetIndexResponse getIndexResponse, ActionListener<AcknowledgedResponse> listener ) { // We have validated the destination index should match a single index assert getIndexResponse.indices().length == 1; // Fetch mappings from destination index Map<String, Object> destMappingsAsMap = getIndexResponse.mappings().values().iterator().next().sourceAsMap(); Map<String, Object> destPropertiesAsMap = (Map<String, Object>) destMappingsAsMap.getOrDefault(PROPERTIES, Collections.emptyMap()); // Verify that the results field does not exist in the dest index checkResultsFieldIsNotPresentInProperties(config, destPropertiesAsMap); getFieldCapsForRequiredFields(client, config, listener.delegateFailureAndWrap((delegate, fieldCapabilitiesResponse) -> { Map<String, Object> addedMappings = new HashMap<>(); // Determine mappings to be added to the destination index addedMappings.put(PROPERTIES, createAdditionalMappings(config, fieldCapabilitiesResponse)); // Also add runtime mappings if (config.getSource().getRuntimeMappings().isEmpty() == false) { addedMappings.put(RUNTIME, config.getSource().getRuntimeMappings()); } // Add the mappings to the destination index PutMappingRequest putMappingRequest = new PutMappingRequest(getIndexResponse.indices()).source(addedMappings); ClientHelper.executeWithHeadersAsync( config.getHeaders(), ML_ORIGIN, client, TransportPutMappingAction.TYPE, putMappingRequest, delegate ); })); } private static void checkResultsFieldIsNotPresentInProperties(DataFrameAnalyticsConfig config, Map<String, Object> properties) { String resultsField = config.getDest().getResultsField(); if (properties.containsKey(resultsField)) { throw ExceptionsHelper.badRequestException( "A field that matches the {}.{} [{}] already exists; please set a different {}", DataFrameAnalyticsConfig.DEST.getPreferredName(), DataFrameAnalyticsDest.RESULTS_FIELD.getPreferredName(), resultsField, DataFrameAnalyticsDest.RESULTS_FIELD.getPreferredName() ); } } @SuppressWarnings("unchecked") public static Metadata readMetadata(String jobId, MappingMetadata mappingMetadata) { Map<String, Object> mappings = mappingMetadata.getSourceAsMap(); Map<String, Object> meta = (Map<String, Object>) mappings.get(META); if ((meta == null) || (DFA_CREATOR.equals(meta.get(CREATED_BY)) == false)) { return new NoMetadata(); } return new DestMetadata(getVersion(jobId, meta)); } @SuppressWarnings("unchecked") private static MlConfigVersion getVersion(String jobId, Map<String, Object> meta) { try { Map<String, Object> version = (Map<String, Object>) meta.get(VERSION); String createdVersionString = (String) version.get(CREATED); return MlConfigVersion.fromString(createdVersionString); } catch (Exception e) { logger.error(() -> "[" + jobId + "] Could not retrieve destination index version", e); return null; } } public
DestinationIndex
java
netty__netty
common/src/main/java/io/netty/util/AsciiString.java
{ "start": 1737, "end": 2130 }
class ____ designed to provide an immutable array of bytes, and caches some internal state based upon the value * of this array. However underlying access to this byte array is provided via not copying the array on construction or * {@link #array()}. If any changes are made to the underlying byte array it is the user's responsibility to call * {@link #arrayChanged()} so the state of this
was
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/TestDescriptor.java
{ "start": 10951, "end": 11708 }
enum ____ { /** * Denotes that the {@link TestDescriptor} is for a <em>container</em>. */ CONTAINER, /** * Denotes that the {@link TestDescriptor} is for a <em>test</em>. */ TEST, /** * Denotes that the {@link TestDescriptor} is for a <em>test</em> * that may potentially also be a <em>container</em>. */ CONTAINER_AND_TEST; /** * {@return {@code true} if this type represents a descriptor that can * contain other descriptors} */ public boolean isContainer() { return this == CONTAINER || this == CONTAINER_AND_TEST; } /** * {@return {@code true} if this type represents a descriptor for a test} */ public boolean isTest() { return this == TEST || this == CONTAINER_AND_TEST; } } }
Type
java
apache__camel
components/camel-micrometer-prometheus/src/main/java/org/apache/camel/component/micrometer/prometheus/internal/BindersDiscoveryMain.java
{ "start": 1488, "end": 3134 }
class ____ { private static final String JANDEX_INDEX = "META-INF/micrometer-binder-index.dat"; public static void main(String[] args) throws Exception { Set<String> answer = new TreeSet<>(); Index index = BindersHelper.readJandexIndex(new DefaultClassResolver()); if (index == null) { System.out.println("Cannot read " + JANDEX_INDEX + " with list of known MeterBinder classes"); } else { DotName dn = DotName.createSimple(MeterBinder.class); Set<ClassInfo> classes = index.getAllKnownImplementors(dn); for (ClassInfo info : classes) { boolean deprecated = info.hasAnnotation(Deprecated.class); if (deprecated) { // skip deprecated continue; } boolean abs = Modifier.isAbstract(info.flags()); if (abs) { // skip abstract continue; } boolean noArg = info.hasNoArgsConstructor(); if (!noArg) { // skip binders that need extra configuration continue; } String name = info.name().local(); if (name.endsWith("Metrics")) { name = name.substring(0, name.length() - 7); } name = StringHelper.camelCaseToDash(name); answer.add(name); } } StringJoiner sj = new StringJoiner(", "); answer.forEach(sj::add); System.out.println(sj); } }
BindersDiscoveryMain
java
quarkusio__quarkus
independent-projects/tools/devtools-common/src/main/java/io/quarkus/platform/descriptor/loader/json/ResourceInputStreamConsumer.java
{ "start": 117, "end": 213 }
interface ____<T> { T consume(InputStream is) throws IOException; }
ResourceInputStreamConsumer
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/aot/generate/GeneratedFiles.java
{ "start": 2044, "end": 2484 }
class ____ that should be used to determine the path * of the file * @param content the contents of the file */ default void addSourceFile(String className, CharSequence content) { addSourceFile(className, appendable -> appendable.append(content)); } /** * Add a generated {@link Kind#SOURCE source file} with content written to * an {@link Appendable} passed to the given {@link ThrowingConsumer}. * @param className the
name
java
quarkusio__quarkus
extensions/spring-security/deployment/src/main/java/io/quarkus/spring/security/deployment/roles/HasRoleValueProducer.java
{ "start": 178, "end": 261 }
interface ____ extends Function<BytecodeCreator, ResultHandle> { }
HasRoleValueProducer
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/data/RowData.java
{ "start": 2287, "end": 2941 }
interface ____ different implementations which are designed for different * scenarios: * * <ul> * <li>The binary-oriented implementation {@code BinaryRowData} is backed by references to {@link * MemorySegment} instead of using Java objects to reduce the serialization/deserialization * overhead. * <li>The object-oriented implementation {@link GenericRowData} is backed by an array of Java * {@link Object} which is easy to construct and efficient to update. * </ul> * * <p>{@link GenericRowData} is intended for public use and has stable behavior. It is recommended * to construct instances of {@link RowData} with this
has
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/transform/transforms/pivot/TermsGroupSourceTests.java
{ "start": 900, "end": 3996 }
class ____ extends AbstractXContentSerializingTestCase<TermsGroupSource> { public static TermsGroupSource randomTermsGroupSource() { return randomTermsGroupSource(TransformConfigVersion.CURRENT); } public static TermsGroupSource randomTermsGroupSourceNoScript() { return randomTermsGroupSource(TransformConfigVersion.CURRENT, false); } public static TermsGroupSource randomTermsGroupSourceNoScript(String fieldPrefix) { return randomTermsGroupSource(TransformConfigVersion.CURRENT, false, fieldPrefix); } public static TermsGroupSource randomTermsGroupSource(TransformConfigVersion version) { return randomTermsGroupSource(TransformConfigVersion.CURRENT, randomBoolean()); } public static TermsGroupSource randomTermsGroupSource(TransformConfigVersion version, boolean withScript) { return randomTermsGroupSource(TransformConfigVersion.CURRENT, withScript, ""); } public static TermsGroupSource randomTermsGroupSource(TransformConfigVersion version, boolean withScript, String fieldPrefix) { ScriptConfig scriptConfig = null; String field; // either a field or a script must be specified, it's possible to have both, but disallowed to have none if (version.onOrAfter(TransformConfigVersion.V_7_7_0) && withScript) { scriptConfig = ScriptConfigTests.randomScriptConfig(); field = randomBoolean() ? null : fieldPrefix + randomAlphaOfLengthBetween(1, 20); } else { field = fieldPrefix + randomAlphaOfLengthBetween(1, 20); } boolean missingBucket = version.onOrAfter(TransformConfigVersion.V_7_10_0) ? randomBoolean() : false; return new TermsGroupSource(field, scriptConfig, missingBucket); } @Override protected TermsGroupSource doParseInstance(XContentParser parser) throws IOException { return TermsGroupSource.fromXContent(parser, false); } @Override protected TermsGroupSource createTestInstance() { return randomTermsGroupSource(); } @Override protected TermsGroupSource mutateInstance(TermsGroupSource instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected Reader<TermsGroupSource> instanceReader() { return TermsGroupSource::new; } public void testFailOnFieldAndScriptBothBeingNull() throws IOException { String json = "{}"; try (XContentParser parser = createParser(JsonXContent.jsonXContent, json)) { TermsGroupSource group = TermsGroupSource.fromXContent(parser, true); assertThat(group.getField(), is(nullValue())); assertThat(group.getScriptConfig(), is(nullValue())); ValidationException validationException = group.validate(null); assertThat(validationException, is(notNullValue())); assertThat(validationException.getMessage(), containsString("Required one of fields [field, script], but none were specified")); } } }
TermsGroupSourceTests
java
spring-projects__spring-framework
spring-core-test/src/test/java/org/springframework/core/test/io/support/MockSpringFactoriesLoaderTests.java
{ "start": 2486, "end": 2543 }
class ____ implements TestFactoryType { } }
TestFactoryTwo
java
apache__flink
flink-test-utils-parent/flink-test-utils/src/main/java/org/apache/flink/test/util/ShellScript.java
{ "start": 2740, "end": 3134 }
class ____ extends ShellScriptBuilder { WindowsShellScriptBuilder() { line("@setlocal"); line(); } public void command(List<String> command) { line("@call ", String.join(" ", command)); } public void env(String key, String value) { line("@set ", key, "=", value); } } }
WindowsShellScriptBuilder
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/support/rowset/SqlRowSet.java
{ "start": 1887, "end": 19084 }
interface ____ extends Serializable { /** * Retrieve the meta-data, i.e. number, types and properties * for the columns of this row set. * @return a corresponding SqlRowSetMetaData instance * @see java.sql.ResultSet#getMetaData() */ SqlRowSetMetaData getMetaData(); /** * Map the given column label to its column index. * @param columnLabel the name of the column * @return the column index for the given column label * @see java.sql.ResultSet#findColumn(String) */ int findColumn(String columnLabel) throws InvalidResultSetAccessException; // RowSet methods for extracting data values /** * Retrieve the value of the indicated column in the current row as a BigDecimal object. * @param columnIndex the column index * @return an BigDecimal object representing the column value * @see java.sql.ResultSet#getBigDecimal(int) */ @Nullable BigDecimal getBigDecimal(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a BigDecimal object. * @param columnLabel the column label * @return an BigDecimal object representing the column value * @see java.sql.ResultSet#getBigDecimal(String) */ @Nullable BigDecimal getBigDecimal(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a boolean. * @param columnIndex the column index * @return a boolean representing the column value * @see java.sql.ResultSet#getBoolean(int) */ boolean getBoolean(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a boolean. * @param columnLabel the column label * @return a boolean representing the column value * @see java.sql.ResultSet#getBoolean(String) */ boolean getBoolean(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a byte. * @param columnIndex the column index * @return a byte representing the column value * @see java.sql.ResultSet#getByte(int) */ byte getByte(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a byte. * @param columnLabel the column label * @return a byte representing the column value * @see java.sql.ResultSet#getByte(String) */ byte getByte(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Date object. * @param columnIndex the column index * @return a Date object representing the column value * @see java.sql.ResultSet#getDate(int) */ @Nullable Date getDate(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Date object. * @param columnLabel the column label * @return a Date object representing the column value * @see java.sql.ResultSet#getDate(String) */ @Nullable Date getDate(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Date object. * @param columnIndex the column index * @param cal the Calendar to use in constructing the Date * @return a Date object representing the column value * @see java.sql.ResultSet#getDate(int, Calendar) */ @Nullable Date getDate(int columnIndex, Calendar cal) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Date object. * @param columnLabel the column label * @param cal the Calendar to use in constructing the Date * @return a Date object representing the column value * @see java.sql.ResultSet#getDate(String, Calendar) */ @Nullable Date getDate(String columnLabel, Calendar cal) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Double object. * @param columnIndex the column index * @return a Double object representing the column value * @see java.sql.ResultSet#getDouble(int) */ double getDouble(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Double object. * @param columnLabel the column label * @return a Double object representing the column value * @see java.sql.ResultSet#getDouble(String) */ double getDouble(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a float. * @param columnIndex the column index * @return a float representing the column value * @see java.sql.ResultSet#getFloat(int) */ float getFloat(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a float. * @param columnLabel the column label * @return a float representing the column value * @see java.sql.ResultSet#getFloat(String) */ float getFloat(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as an int. * @param columnIndex the column index * @return an int representing the column value * @see java.sql.ResultSet#getInt(int) */ int getInt(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as an int. * @param columnLabel the column label * @return an int representing the column value * @see java.sql.ResultSet#getInt(String) */ int getInt(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a long. * @param columnIndex the column index * @return a long representing the column value * @see java.sql.ResultSet#getLong(int) */ long getLong(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a long. * @param columnLabel the column label * @return a long representing the column value * @see java.sql.ResultSet#getLong(String) */ long getLong(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a String * (for NCHAR, NVARCHAR, LONGNVARCHAR columns). * @param columnIndex the column index * @return a String representing the column value * @since 4.1.3 * @see java.sql.ResultSet#getNString(int) */ @Nullable String getNString(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a String * (for NCHAR, NVARCHAR, LONGNVARCHAR columns). * @param columnLabel the column label * @return a String representing the column value * @since 4.1.3 * @see java.sql.ResultSet#getNString(String) */ @Nullable String getNString(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as an Object. * @param columnIndex the column index * @return an Object representing the column value * @see java.sql.ResultSet#getObject(int) */ @Nullable Object getObject(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as an Object. * @param columnLabel the column label * @return an Object representing the column value * @see java.sql.ResultSet#getObject(String) */ @Nullable Object getObject(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as an Object. * @param columnIndex the column index * @param map a Map object containing the mapping from SQL types to Java types * @return an Object representing the column value * @see java.sql.ResultSet#getObject(int, Map) */ @Nullable Object getObject(int columnIndex, Map<String, Class<?>> map) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as an Object. * @param columnLabel the column label * @param map a Map object containing the mapping from SQL types to Java types * @return an Object representing the column value * @see java.sql.ResultSet#getObject(String, Map) */ @Nullable Object getObject(String columnLabel, Map<String, Class<?>> map) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as an Object. * @param columnIndex the column index * @param type the Java type to convert the designated column to * @return an Object representing the column value * @since 4.1.3 * @see java.sql.ResultSet#getObject(int, Class) */ <T> @Nullable T getObject(int columnIndex, Class<T> type) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as an Object. * @param columnLabel the column label * @param type the Java type to convert the designated column to * @return an Object representing the column value * @since 4.1.3 * @see java.sql.ResultSet#getObject(String, Class) */ <T> @Nullable T getObject(String columnLabel, Class<T> type) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a short. * @param columnIndex the column index * @return a short representing the column value * @see java.sql.ResultSet#getShort(int) */ short getShort(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a short. * @param columnLabel the column label * @return a short representing the column value * @see java.sql.ResultSet#getShort(String) */ short getShort(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a String. * @param columnIndex the column index * @return a String representing the column value * @see java.sql.ResultSet#getString(int) */ @Nullable String getString(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a String. * @param columnLabel the column label * @return a String representing the column value * @see java.sql.ResultSet#getString(String) */ @Nullable String getString(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Time object. * @param columnIndex the column index * @return a Time object representing the column value * @see java.sql.ResultSet#getTime(int) */ @Nullable Time getTime(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Time object. * @param columnLabel the column label * @return a Time object representing the column value * @see java.sql.ResultSet#getTime(String) */ @Nullable Time getTime(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Time object. * @param columnIndex the column index * @param cal the Calendar to use in constructing the Date * @return a Time object representing the column value * @see java.sql.ResultSet#getTime(int, Calendar) */ @Nullable Time getTime(int columnIndex, Calendar cal) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Time object. * @param columnLabel the column label * @param cal the Calendar to use in constructing the Date * @return a Time object representing the column value * @see java.sql.ResultSet#getTime(String, Calendar) */ @Nullable Time getTime(String columnLabel, Calendar cal) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Timestamp object. * @param columnIndex the column index * @return a Timestamp object representing the column value * @see java.sql.ResultSet#getTimestamp(int) */ @Nullable Timestamp getTimestamp(int columnIndex) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Timestamp object. * @param columnLabel the column label * @return a Timestamp object representing the column value * @see java.sql.ResultSet#getTimestamp(String) */ @Nullable Timestamp getTimestamp(String columnLabel) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Timestamp object. * @param columnIndex the column index * @param cal the Calendar to use in constructing the Date * @return a Timestamp object representing the column value * @see java.sql.ResultSet#getTimestamp(int, Calendar) */ @Nullable Timestamp getTimestamp(int columnIndex, Calendar cal) throws InvalidResultSetAccessException; /** * Retrieve the value of the indicated column in the current row as a Timestamp object. * @param columnLabel the column label * @param cal the Calendar to use in constructing the Date * @return a Timestamp object representing the column value * @see java.sql.ResultSet#getTimestamp(String, Calendar) */ @Nullable Timestamp getTimestamp(String columnLabel, Calendar cal) throws InvalidResultSetAccessException; // RowSet navigation methods /** * Move the cursor to the given row number in the row set, just after the last row. * @param row the number of the row where the cursor should move * @return {@code true} if the cursor is on the row set, {@code false} otherwise * @see java.sql.ResultSet#absolute(int) */ boolean absolute(int row) throws InvalidResultSetAccessException; /** * Move the cursor to the end of this row set. * @see java.sql.ResultSet#afterLast() */ void afterLast() throws InvalidResultSetAccessException; /** * Move the cursor to the front of this row set, just before the first row. * @see java.sql.ResultSet#beforeFirst() */ void beforeFirst() throws InvalidResultSetAccessException; /** * Move the cursor to the first row of this row set. * @return {@code true} if the cursor is on a valid row, {@code false} otherwise * @see java.sql.ResultSet#first() */ boolean first() throws InvalidResultSetAccessException; /** * Retrieve the current row number. * @return the current row number * @see java.sql.ResultSet#getRow() */ int getRow() throws InvalidResultSetAccessException; /** * Retrieve whether the cursor is after the last row of this row set. * @return {@code true} if the cursor is after the last row, {@code false} otherwise * @see java.sql.ResultSet#isAfterLast() */ boolean isAfterLast() throws InvalidResultSetAccessException; /** * Retrieve whether the cursor is before the first row of this row set. * @return {@code true} if the cursor is before the first row, {@code false} otherwise * @see java.sql.ResultSet#isBeforeFirst() */ boolean isBeforeFirst() throws InvalidResultSetAccessException; /** * Retrieve whether the cursor is on the first row of this row set. * @return {@code true} if the cursor is after the first row, {@code false} otherwise * @see java.sql.ResultSet#isFirst() */ boolean isFirst() throws InvalidResultSetAccessException; /** * Retrieve whether the cursor is on the last row of this row set. * @return {@code true} if the cursor is after the last row, {@code false} otherwise * @see java.sql.ResultSet#isLast() */ boolean isLast() throws InvalidResultSetAccessException; /** * Move the cursor to the last row of this row set. * @return {@code true} if the cursor is on a valid row, {@code false} otherwise * @see java.sql.ResultSet#last() */ boolean last() throws InvalidResultSetAccessException; /** * Move the cursor to the next row. * @return {@code true} if the new row is valid, {@code false} if there are no more rows * @see java.sql.ResultSet#next() */ boolean next() throws InvalidResultSetAccessException; /** * Move the cursor to the previous row. * @return {@code true} if the new row is valid, {@code false} if it is off the row set * @see java.sql.ResultSet#previous() */ boolean previous() throws InvalidResultSetAccessException; /** * Move the cursor a relative number of rows, either positive or negative. * @return {@code true} if the cursor is on a row, {@code false} otherwise * @see java.sql.ResultSet#relative(int) */ boolean relative(int rows) throws InvalidResultSetAccessException; /** * Report whether the last column read had a value of SQL {@code NULL}. * <p>Note that you must first call one of the getter methods and then * call the {@code wasNull()} method. * @return {@code true} if the most recent column retrieved was * SQL {@code NULL}, {@code false} otherwise * @see java.sql.ResultSet#wasNull() */ boolean wasNull() throws InvalidResultSetAccessException; }
SqlRowSet
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/dto/generated/QueryRecordsLine_Item__c.java
{ "start": 952, "end": 1034 }
class ____ extends AbstractQueryRecordsBase<Line_Item__c> { }
QueryRecordsLine_Item__c
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/extension/ExtensionContext.java
{ "start": 20595, "end": 35597 }
interface ____ { /** * Close underlying resources. * * @throws Throwable any throwable will be caught and rethrown */ void close() throws Throwable; } /** * Get the value that is stored under the supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. * * <p>For greater type safety, consider using {@link #get(Object, Class)} * instead. * * @param key the key; never {@code null} * @return the value; potentially {@code null} * @see #get(Object, Class) * @see #getOrDefault(Object, Class, Object) */ @Nullable Object get(Object key); /** * Get the value of the specified required type that is stored under * the supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. * * @param key the key; never {@code null} * @param requiredType the required type of the value; never {@code null} * @param <V> the value type * @return the value; potentially {@code null} * @see #get(Object) * @see #getOrDefault(Object, Class, Object) */ <V> @Nullable V get(Object key, Class<V> requiredType); /** * Get the value of the specified required type that is stored under * the supplied {@code key}, or the supplied {@code defaultValue} if no * value is found for the supplied {@code key} in this store or in an * ancestor. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. * * @param key the key; never {@code null} * @param requiredType the required type of the value; never {@code null} * @param defaultValue the default value; never {@code null} * @param <V> the value type * @return the value; never {@code null} * @since 5.5 * @see #get(Object, Class) */ @API(status = STABLE, since = "5.5") default <V> V getOrDefault(Object key, Class<V> requiredType, V defaultValue) { V value = get(key, requiredType); return (value != null ? value : defaultValue); } /** * Get the object of type {@code type} that is present in this * {@code Store} (<em>keyed</em> by {@code type}); and otherwise invoke * the default constructor for {@code type} to generate the object, * store it, and return it. * * <p>This method is a shortcut for the following, where {@code X} is * the type of object we wish to retrieve from the store. * * <pre style="code"> * X x = store.computeIfAbsent(X.class, key -&gt; new X(), X.class); * // Equivalent to: * // X x = store.computeIfAbsent(X.class); * </pre> * * <p>See {@link #computeIfAbsent(Object, Function, Class)} for further * details. * * <p>If {@code type} implements {@link CloseableResource} or * {@link AutoCloseable} (unless the * {@code junit.jupiter.extensions.store.close.autocloseable.enabled} * configuration parameter is set to {@code false}), then the {@code close()} * method will be invoked on the stored object when the store is closed. * * @param type the type of object to retrieve; never {@code null} * @param <V> the key and value type * @return the object; never {@code null} * @since 5.1 * @see #computeIfAbsent(Class) * @see #computeIfAbsent(Object, Function) * @see #computeIfAbsent(Object, Function, Class) * @see CloseableResource * @see AutoCloseable * @deprecated Please use {@link #computeIfAbsent(Class)} instead. */ @Deprecated(since = "6.0") @API(status = DEPRECATED, since = "6.0") default <V> V getOrComputeIfAbsent(Class<V> type) { return computeIfAbsent(type); } /** * Return the object of type {@code type} if it is present and not * {@code null} in this {@code Store} (<em>keyed</em> by {@code type}); * otherwise, invoke the default constructor for {@code type} to * generate the object, store it, and return it. * * <p>This method is a shortcut for the following, where {@code X} is * the type of object we wish to retrieve from the store. * * <pre style="code"> * X x = store.computeIfAbsent(X.class, key -&gt; new X(), X.class); * // Equivalent to: * // X x = store.computeIfAbsent(X.class); * </pre> * * <p>See {@link #computeIfAbsent(Object, Function, Class)} for further * details. * * <p>If {@code type} implements {@link CloseableResource} or * {@link AutoCloseable} (unless the * {@code junit.jupiter.extensions.store.close.autocloseable.enabled} * configuration parameter is set to {@code false}), then the {@code close()} * method will be invoked on the stored object when the store is closed. * * @param type the type of object to retrieve; never {@code null} * @param <V> the key and value type * @return the object; never {@code null} * @since 6.0 * @see #computeIfAbsent(Object, Function) * @see #computeIfAbsent(Object, Function, Class) * @see CloseableResource * @see AutoCloseable */ @API(status = MAINTAINED, since = "6.0") default <V> V computeIfAbsent(Class<V> type) { return computeIfAbsent(type, ReflectionSupport::newInstance, type); } /** * Get the value that is stored under the supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. If no value is found for the supplied {@code key}, * a new value will be computed by the {@code defaultCreator} (given * the {@code key} as input), stored, and returned. * * <p>For greater type safety, consider using * {@link #computeIfAbsent(Object, Function, Class)} instead. * * <p>If the created value is an instance of {@link CloseableResource} or * {@link AutoCloseable} (unless the * {@code junit.jupiter.extensions.store.close.autocloseable.enabled} * configuration parameter is set to {@code false}), then the {@code close()} * method will be invoked on the stored object when the store is closed. * * @param key the key; never {@code null} * @param defaultCreator the function called with the supplied {@code key} * to create a new value; never {@code null} but may return {@code null} * @param <K> the key type * @param <V> the value type * @return the value; potentially {@code null} * @see #computeIfAbsent(Class) * @see #computeIfAbsent(Object, Function) * @see #computeIfAbsent(Object, Function, Class) * @see CloseableResource * @see AutoCloseable * @deprecated Please use {@link #computeIfAbsent(Object, Function)} instead. */ @Deprecated(since = "6.0") @API(status = DEPRECATED, since = "6.0") <K, V extends @Nullable Object> @Nullable Object getOrComputeIfAbsent(K key, Function<? super K, ? extends V> defaultCreator); /** * Return the value of the specified required type that is stored under * the supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. If no value is found for the supplied {@code key} * or the value is {@code null}, a new value will be computed by the * {@code defaultCreator} (given the {@code key} as input), stored, and * returned. * * <p>For greater type safety, consider using * {@link #computeIfAbsent(Object, Function, Class)} instead. * * <p>If the created value is an instance of {@link CloseableResource} or * {@link AutoCloseable} (unless the * {@code junit.jupiter.extensions.store.close.autocloseable.enabled} * configuration parameter is set to {@code false}), then the {@code close()} * method will be invoked on the stored object when the store is closed. * * @param key the key; never {@code null} * @param defaultCreator the function called with the supplied {@code key} * to create a new value; never {@code null} and must not return * {@code null} * @param <K> the key type * @param <V> the value type * @return the value; never {@code null} * @since 6.0 * @see #computeIfAbsent(Class) * @see #computeIfAbsent(Object, Function, Class) * @see CloseableResource * @see AutoCloseable */ @API(status = MAINTAINED, since = "6.0") <K, V> Object computeIfAbsent(K key, Function<? super K, ? extends V> defaultCreator); /** * Get the value of the specified required type that is stored under the * supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. If no value is found for the supplied {@code key}, * a new value will be computed by the {@code defaultCreator} (given * the {@code key} as input), stored, and returned. * * <p>If the created value implements {@link CloseableResource} or * {@link AutoCloseable} (unless the * {@code junit.jupiter.extensions.store.close.autocloseable.enabled} * configuration parameter is set to {@code false}), then the {@code close()} * method will be invoked on the stored object when the store is closed. * * @param key the key; never {@code null} * @param defaultCreator the function called with the supplied {@code key} * to create a new value; never {@code null} but may return {@code null} * @param requiredType the required type of the value; never {@code null} * @param <K> the key type * @param <V> the value type * @return the value; potentially {@code null} * @see #computeIfAbsent(Class) * @see #computeIfAbsent(Object, Function) * @see #computeIfAbsent(Object, Function, Class) * @see CloseableResource * @see AutoCloseable * @deprecated Please use {@link #computeIfAbsent(Object, Function, Class)} instead. */ @Deprecated(since = "6.0") @API(status = DEPRECATED, since = "6.0") <K, V extends @Nullable Object> @Nullable V getOrComputeIfAbsent(K key, Function<? super K, ? extends V> defaultCreator, Class<V> requiredType); /** * Get the value of the specified required type that is stored under the * supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. If no value is found for the supplied {@code key} * or the value is {@code null}, a new value will be computed by the * {@code defaultCreator} (given the {@code key} as input), stored, and * returned. * * <p>If the created value is an instance of {@link CloseableResource} or * {@link AutoCloseable} (unless the * {@code junit.jupiter.extensions.store.close.autocloseable.enabled} * configuration parameter is set to {@code false}), then the {@code close()} * method will be invoked on the stored object when the store is closed. * * @param key the key; never {@code null} * @param defaultCreator the function called with the supplied {@code key} * to create a new value; never {@code null} and must not return * {@code null} * @param requiredType the required type of the value; never {@code null} * @param <K> the key type * @param <V> the value type * @return the value; never {@code null} * @since 6.0 * @see #computeIfAbsent(Class) * @see #computeIfAbsent(Object, Function) * @see CloseableResource * @see AutoCloseable */ @API(status = MAINTAINED, since = "6.0") <K, V> V computeIfAbsent(K key, Function<? super K, ? extends V> defaultCreator, Class<V> requiredType); /** * Store a {@code value} for later retrieval under the supplied {@code key}. * * <p>A stored {@code value} is visible in child {@link ExtensionContext * ExtensionContexts} for the store's {@code Namespace} unless they * overwrite it. * * <p>If the {@code value} is an instance of {@link CloseableResource} or * {@link AutoCloseable} (unless the * {@code junit.jupiter.extensions.store.close.autocloseable.enabled} * configuration parameter is set to {@code false}), then the {@code close()} * method will be invoked on the stored object when the store is closed. * * @param key the key under which the value should be stored; never * {@code null} * @param value the value to store; may be {@code null} * @see CloseableResource * @see AutoCloseable */ void put(Object key, @Nullable Object value); /** * Remove the value that was previously stored under the supplied {@code key}. * * <p>The value will only be removed in the current {@link ExtensionContext}, * not in ancestors. In addition, the {@link CloseableResource} and {@link AutoCloseable} * API will not be honored for values that are manually removed via this method. * * <p>For greater type safety, consider using {@link #remove(Object, Class)} * instead. * * @param key the key; never {@code null} * @return the previous value or {@code null} if no value was present * for the specified key * @see #remove(Object, Class) */ @Nullable Object remove(Object key); /** * Remove the value of the specified required type that was previously stored * under the supplied {@code key}. * * <p>The value will only be removed in the current {@link ExtensionContext}, * not in ancestors. In addition, the {@link CloseableResource} and {@link AutoCloseable} * API will not be honored for values that are manually removed via this method. * * @param key the key; never {@code null} * @param requiredType the required type of the value; never {@code null} * @param <V> the value type * @return the previous value or {@code null} if no value was present * for the specified key * @see #remove(Object) */ <V> @Nullable V remove(Object key, Class<V> requiredType); } /** * A {@code Namespace} is used to provide a <em>scope</em> for data saved by * extensions within a {@link Store}. * * <p>Storing data in custom namespaces allows extensions to avoid accidentally * mixing data between extensions or across different invocations within the * lifecycle of a single extension. */ final
CloseableResource
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/PropertyMetadata.java
{ "start": 164, "end": 426 }
class ____ for storing "additional" metadata about * properties. Carved out to reduce number of distinct properties that * actual property implementations and place holders need to store; * since instances are immutable, they can be freely shared. */ public
used
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/typebasedtypehandlerresolution/GloballyRegisteredHandlerMapper.java
{ "start": 976, "end": 2696 }
interface ____ { @Result(column = "id", property = "id", id = true) @Result(column = "strvalue", property = "strvalue") @Result(column = "intvalue", property = "intvalue") @Result(column = "strings", property = "strings") @Result(column = "integers", property = "integers") @Select("select id, strvalue, intvalue, strings, integers from users where id = #{id}") User getUser(Integer id); @Insert({ "insert into users (id, strvalue, intvalue, strings, integers)", "values (#{id}, #{strvalue}, #{intvalue}, #{strings}, #{integers})" }) void insertUser(User user); @Insert({ "insert into users (id, strvalue, intvalue, strings, integers)", "values (#{user.id}, #{user.strvalue}, #{user.intvalue}, #{user.strings}, #{user.integers})" }) void insertUserMultiParam(User user, String foo); @Select("select strvalue from users where id = #{id}") FuzzyBean<String> selectFuzzyString(Integer id); @Select("select id, strvalue, intvalue, strings, integers from users where strvalue = #{v}") User getUserByFuzzyBean(FuzzyBean<String> str); @Select("select id, strvalue, intvalue, strings, integers from users where strvalue = #{p1} and intvalue = #{p2}") User getUserByFuzzyBeans(FuzzyBean<String> p1, FuzzyBean<Integer> p2); ParentBean selectNestedUser_SingleParam(Integer id); ParentBean selectNestedUser_MultiParam(Integer id); @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id") @Insert("insert into product (name) values (#{name})") int insertProduct(Product product); int insertProducts(List<Product> products); int insertProducts2(@Param("dummy") String dummy, @Param("products") List<Product> products); }
GloballyRegisteredHandlerMapper
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaTransactionCoordinatorImpl.java
{ "start": 2116, "end": 12828 }
class ____ implements TransactionCoordinator, SynchronizationCallbackTarget { private final TransactionCoordinatorBuilder transactionCoordinatorBuilder; private final TransactionCoordinatorOwner transactionCoordinatorOwner; private final JtaPlatform jtaPlatform; private final boolean autoJoinTransactions; private final boolean preferUserTransactions; private final boolean performJtaThreadTracking; private boolean synchronizationRegistered; private SynchronizationCallbackCoordinator callbackCoordinator; private TransactionDriverControlImpl physicalTransactionDelegate; private final SynchronizationRegistryStandardImpl synchronizationRegistry = new SynchronizationRegistryStandardImpl(); private int timeOut = -1; private transient List<TransactionObserver> observers = null; /** * Construct a JtaTransactionCoordinatorImpl instance. package-protected to ensure access goes through * builder. * * @param owner The transactionCoordinatorOwner * @param autoJoinTransactions Should JTA transactions be auto-joined? Or should we wait for explicit join calls? */ JtaTransactionCoordinatorImpl( TransactionCoordinatorBuilder transactionCoordinatorBuilder, TransactionCoordinatorOwner owner, boolean autoJoinTransactions, JtaPlatform jtaPlatform) { this.transactionCoordinatorBuilder = transactionCoordinatorBuilder; this.transactionCoordinatorOwner = owner; this.autoJoinTransactions = autoJoinTransactions; this.jtaPlatform = jtaPlatform; final var jdbcSessionContext = owner.getJdbcSessionOwner().getJdbcSessionContext(); preferUserTransactions = jdbcSessionContext.isPreferUserTransaction(); performJtaThreadTracking = jdbcSessionContext.isJtaTrackByThread(); synchronizationRegistered = false; pulse(); } public JtaTransactionCoordinatorImpl( TransactionCoordinatorBuilder transactionCoordinatorBuilder, TransactionCoordinatorOwner owner, boolean autoJoinTransactions, JtaPlatform jtaPlatform, boolean preferUserTransactions, boolean performJtaThreadTracking, TransactionObserver... observers) { this.transactionCoordinatorBuilder = transactionCoordinatorBuilder; this.transactionCoordinatorOwner = owner; this.autoJoinTransactions = autoJoinTransactions; this.jtaPlatform = jtaPlatform; this.preferUserTransactions = preferUserTransactions; this.performJtaThreadTracking = performJtaThreadTracking; if ( observers != null ) { this.observers = new ArrayList<>( observers.length ); addAll( this.observers, observers ); } synchronizationRegistered = false; pulse(); } /** * Needed because while iterating the observers list and executing the before/update callbacks, * some observers might get removed from the list. * Yet try to not allocate anything for when the list is empty, as this is a common case. * * @return TransactionObserver */ private Iterable<TransactionObserver> observers() { return observers == null ? emptyList() : new ArrayList<>( observers ); } public SynchronizationCallbackCoordinator getSynchronizationCallbackCoordinator() { if ( callbackCoordinator == null ) { callbackCoordinator = performJtaThreadTracking ? new SynchronizationCallbackCoordinatorTrackingImpl( this ) : new SynchronizationCallbackCoordinatorNonTrackingImpl( this ); } return callbackCoordinator; } @Override public void pulse() { if ( autoJoinTransactions && !synchronizationRegistered ) { // Can we register a synchronization according to the JtaPlatform? if ( !jtaPlatform.canRegisterSynchronization() ) { JTA_LOGGER.cannotRegisterSynchronization(); } else { joinJtaTransaction(); } } } /** * Join to the JTA transaction. Note that the underlying meaning of joining in JTA environments is to register the * RegisteredSynchronization with the JTA system */ private void joinJtaTransaction() { if ( !synchronizationRegistered ) { jtaPlatform.registerSynchronization( new RegisteredSynchronization( getSynchronizationCallbackCoordinator() ) ); getSynchronizationCallbackCoordinator().synchronizationRegistered(); synchronizationRegistered = true; JTA_LOGGER.registeredSynchronization(); // report entering into a "transactional context" getTransactionCoordinatorOwner().startTransactionBoundary(); } } @Override public void explicitJoin() { if ( synchronizationRegistered ) { JTA_LOGGER.alreadyJoinedJtaTransaction(); } else { if ( getTransactionDriverControl().getStatus() != ACTIVE ) { throw new TransactionRequiredForJoinException( "Explicitly joining a JTA transaction requires a JTA transaction be currently active" ); } joinJtaTransaction(); } } @Override public boolean isJoined() { return synchronizationRegistered; } /** * Is the RegisteredSynchronization used by Hibernate for unified JTA Synchronization callbacks registered for this * coordinator? * * @return {@code true} indicates that a RegisteredSynchronization is currently registered for this coordinator; * {@code false} indicates it is not (yet) registered. */ public boolean isSynchronizationRegistered() { return synchronizationRegistered; } public TransactionCoordinatorOwner getTransactionCoordinatorOwner(){ return transactionCoordinatorOwner; } @Override public JpaCompliance getJpaCompliance() { return transactionCoordinatorOwner.getJdbcSessionOwner().getJdbcSessionContext().getJpaCompliance(); } @Override public TransactionDriver getTransactionDriverControl() { if ( physicalTransactionDelegate == null ) { physicalTransactionDelegate = makePhysicalTransactionDelegate(); } return physicalTransactionDelegate; } private TransactionDriverControlImpl makePhysicalTransactionDelegate() { final var adapter = preferUserTransactions ? getTransactionAdapterPreferringUserTransaction() : getTransactionAdapterPreferringTransactionManager(); if ( adapter == null ) { throw new JtaPlatformInaccessibleException( "Unable to access TransactionManager or UserTransaction to make physical transaction delegate" ); } else { return new TransactionDriverControlImpl( adapter ); } } private JtaTransactionAdapter getTransactionAdapterPreferringTransactionManager() { final var adapter = makeTransactionManagerAdapter(); if ( adapter == null ) { JTA_LOGGER.unableToAccessTransactionManagerTryingUserTransaction(); return makeUserTransactionAdapter(); } return adapter; } private JtaTransactionAdapter getTransactionAdapterPreferringUserTransaction() { final var adapter = makeUserTransactionAdapter(); if ( adapter == null ) { JTA_LOGGER.unableToAccessUserTransactionTryingTransactionManager(); return makeTransactionManagerAdapter(); } return adapter; } private JtaTransactionAdapter makeUserTransactionAdapter() { try { final var userTransaction = jtaPlatform.retrieveUserTransaction(); if ( userTransaction == null ) { JTA_LOGGER.userTransactionReturnedNull(); return null; } else { return new JtaTransactionAdapterUserTransactionImpl( userTransaction ); } } catch ( Exception exception ) { JTA_LOGGER.exceptionRetrievingUserTransaction( exception.getMessage(), exception ); return null; } } private JtaTransactionAdapter makeTransactionManagerAdapter() { try { final var transactionManager = jtaPlatform.retrieveTransactionManager(); if ( transactionManager == null ) { JTA_LOGGER.transactionManagerReturnedNull(); return null; } else { return new JtaTransactionAdapterTransactionManagerImpl( transactionManager ); } } catch ( Exception exception ) { JTA_LOGGER.exceptionRetrievingTransactionManager( exception.getMessage(), exception ); return null; } } @Override public SynchronizationRegistry getLocalSynchronizations() { return synchronizationRegistry; } @Override public boolean isActive() { return transactionCoordinatorOwner.isActive(); } public boolean isJtaTransactionCurrentlyActive() { return getTransactionDriverControl().getStatus() == ACTIVE; } @Override public IsolationDelegate createIsolationDelegate() { return new JtaIsolationDelegate( transactionCoordinatorOwner, jtaPlatform.retrieveTransactionManager() ); } @Override public TransactionCoordinatorBuilder getTransactionCoordinatorBuilder() { return transactionCoordinatorBuilder; } @Override public void setTimeOut(int seconds) { this.timeOut = seconds; physicalTransactionDelegate.jtaTransactionAdapter.setTimeOut( seconds ); } @Override public int getTimeOut() { return timeOut; } @Override public void invalidate() { if ( physicalTransactionDelegate != null ) { physicalTransactionDelegate.invalidate(); } physicalTransactionDelegate = null; } // SynchronizationCallbackTarget ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Override public void beforeCompletion() { JTA_LOGGER.notifyingJtaObserversBeforeCompletion(); try { transactionCoordinatorOwner.beforeTransactionCompletion(); } catch ( Exception e ) { physicalTransactionDelegate.markRollbackOnly(); throw e; } finally { synchronizationRegistry.notifySynchronizationsBeforeTransactionCompletion(); for ( var transactionObserver : observers() ) { transactionObserver.beforeCompletion(); } } } @Override public void afterCompletion(boolean successful, boolean delayed) { if ( transactionCoordinatorOwner.isActive() ) { JTA_LOGGER.notifyingJtaObserversAfterCompletion(); final int statusToSend = successful ? Status.STATUS_COMMITTED : Status.STATUS_UNKNOWN; synchronizationRegistry.notifySynchronizationsAfterTransactionCompletion( statusToSend ); // afterCompletionAction.doAction( this, statusToSend ); transactionCoordinatorOwner.afterTransactionCompletion( successful, delayed ); for ( var transactionObserver : observers() ) { transactionObserver.afterCompletion( successful, delayed ); } synchronizationRegistered = false; } } public void addObserver(TransactionObserver observer) { if ( observers == null ) { observers = new ArrayList<>( 3 ); //These lists are typically very small. } observers.add( observer ); } @Override public void removeObserver(TransactionObserver observer) { if ( observers != null ) { observers.remove( observer ); } } /** * Implementation of the LocalInflow for this TransactionCoordinator. Allows the * local transaction ({@link org.hibernate.Transaction}) to callback into this * TransactionCoordinator for the purpose of driving the underlying JTA transaction. */ public
JtaTransactionCoordinatorImpl
java
apache__camel
components/camel-flowable/src/main/java/org/apache/camel/component/flowable/CamelOperationsOutboundEventChannelAdapter.java
{ "start": 1038, "end": 1734 }
class ____ implements OutboundEventChannelAdapter<String> { protected FlowableEndpoint endpoint; public CamelOperationsOutboundEventChannelAdapter(FlowableEndpoint endpoint) { this.endpoint = endpoint; } @Override public void sendEvent(String rawEvent, Map<String, Object> headerMap) { Exchange exchange = endpoint.createExchange(); exchange.getIn().setBody(rawEvent); exchange.getIn().setHeaders(headerMap); try { endpoint.process(exchange); } catch (Exception e) { throw new FlowableException("Exception while processing Camel exchange", e); } } }
CamelOperationsOutboundEventChannelAdapter
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/util/datetime/FastDatePrinter.java
{ "start": 1963, "end": 3610 }
class ____ especially useful in multi-threaded server environments. * {@code SimpleDateFormat} is not thread-safe in any JDK version, * nor will it be as Sun have closed the bug/RFE. * </p> * * <p>Only formatting is supported by this class, but all patterns are compatible with * SimpleDateFormat (except time zones and some year patterns - see below).</p> * * <p>Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}). * This pattern letter can be used here (on all JDK versions).</p> * * <p>In addition, the pattern {@code 'ZZ'} has been made to represent * ISO 8601 extended format time zones (eg. {@code +08:00} or {@code -11:00}). * This introduces a minor incompatibility with Java 1.4, but at a gain of * useful functionality.</p> * * <p>Starting with JDK7, ISO 8601 support was added using the pattern {@code 'X'}. * To maintain compatibility, {@code 'ZZ'} will continue to be supported, but using * one of the {@code 'X'} formats is recommended. * * <p>Javadoc cites for the year pattern: <i>For formatting, if the number of * pattern letters is 2, the year is truncated to 2 digits; otherwise it is * interpreted as a number.</i> Starting with Java 1.7 a pattern of 'Y' or * 'YYY' will be formatted as '2003', while it was '03' in former Java * versions. FastDatePrinter implements the behavior of Java 7.</p> * * <p> * Copied and modified from <a href="https://commons.apache.org/proper/commons-lang/">Apache Commons Lang</a>. * </p> * * @since Apache Commons Lang 3.2 * @deprecated Starting with version {@code 2.25.0}, this
is
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/HasCamelContext.java
{ "start": 896, "end": 967 }
interface ____ an object which holds a {@link CamelContext}. */ public
for
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java
{ "start": 67902, "end": 68243 }
class ____ { @Bean(name = EnableConfigurationProperties.VALIDATOR_BEAN_NAME) CustomPropertiesValidator validator() { return new CustomPropertiesValidator(); } } @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(WithSetterThatThrowsValidationExceptionProperties.class) static
WithCustomValidatorConfiguration
java
apache__camel
components/camel-platform-http/src/test/java/org/apache/camel/component/platform/http/PlatformHttpCamelHeadersTest.java
{ "start": 1067, "end": 2351 }
class ____ extends AbstractPlatformHttpTest { @Test void testFilterCamelHeaders() { given() .header("Accept", "application/json") .header("User-Agent", "User-Agent-Camel") .header("caMElHttpResponseCode", "503") .port(port) .expect() .statusCode(200) .header("Accept", (String) null) .header("User-Agent", (String) null) .header("CamelHttpResponseCode", (String) null) .when() .get("/get"); } @Override protected RouteBuilder routes() { return new RouteBuilder() { @Override public void configure() { from("platform-http:/get") .process(e -> { Assertions.assertEquals("application/json", e.getMessage().getHeader("Accept")); Assertions.assertEquals("User-Agent-Camel", e.getMessage().getHeader("User-Agent")); Assertions.assertNull(e.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); }) .setBody().constant(""); } }; } }
PlatformHttpCamelHeadersTest
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/datasource/pooled/PoolState.java
{ "start": 837, "end": 6037 }
class ____ { // This lock does not guarantee consistency. // Field values can be modified in PooledDataSource // after the instance is returned from // PooledDataSource#getPoolState(). // A possible fix is to create and return a 'snapshot'. private final ReentrantLock lock = new ReentrantLock(); protected PooledDataSource dataSource; protected final List<PooledConnection> idleConnections = new ArrayList<>(); protected final List<PooledConnection> activeConnections = new ArrayList<>(); protected long requestCount; protected long accumulatedRequestTime; protected long accumulatedCheckoutTime; protected long claimedOverdueConnectionCount; protected long accumulatedCheckoutTimeOfOverdueConnections; protected long accumulatedWaitTime; protected long hadToWaitCount; protected long badConnectionCount; public PoolState(PooledDataSource dataSource) { this.dataSource = dataSource; } public long getRequestCount() { lock.lock(); try { return requestCount; } finally { lock.unlock(); } } public long getAverageRequestTime() { lock.lock(); try { return requestCount == 0 ? 0 : accumulatedRequestTime / requestCount; } finally { lock.unlock(); } } public long getAverageWaitTime() { lock.lock(); try { return hadToWaitCount == 0 ? 0 : accumulatedWaitTime / hadToWaitCount; } finally { lock.unlock(); } } public long getHadToWaitCount() { lock.lock(); try { return hadToWaitCount; } finally { lock.unlock(); } } public long getBadConnectionCount() { lock.lock(); try { return badConnectionCount; } finally { lock.unlock(); } } public long getClaimedOverdueConnectionCount() { lock.lock(); try { return claimedOverdueConnectionCount; } finally { lock.unlock(); } } public long getAverageOverdueCheckoutTime() { lock.lock(); try { return claimedOverdueConnectionCount == 0 ? 0 : accumulatedCheckoutTimeOfOverdueConnections / claimedOverdueConnectionCount; } finally { lock.unlock(); } } public long getAverageCheckoutTime() { lock.lock(); try { return requestCount == 0 ? 0 : accumulatedCheckoutTime / requestCount; } finally { lock.unlock(); } } public int getIdleConnectionCount() { lock.lock(); try { return idleConnections.size(); } finally { lock.unlock(); } } public int getActiveConnectionCount() { lock.lock(); try { return activeConnections.size(); } finally { lock.unlock(); } } @Override public String toString() { lock.lock(); try { StringBuilder builder = new StringBuilder(); builder.append("\n===CONFIGURATION=============================================="); builder.append("\n jdbcDriver ").append(dataSource.getDriver()); builder.append("\n jdbcUrl ").append(dataSource.getUrl()); builder.append("\n jdbcUsername ").append(dataSource.getUsername()); builder.append("\n jdbcPassword ") .append(dataSource.getPassword() == null ? "NULL" : "************"); builder.append("\n poolMaxActiveConnections ").append(dataSource.poolMaximumActiveConnections); builder.append("\n poolMaxIdleConnections ").append(dataSource.poolMaximumIdleConnections); builder.append("\n poolMaxCheckoutTime ").append(dataSource.poolMaximumCheckoutTime); builder.append("\n poolTimeToWait ").append(dataSource.poolTimeToWait); builder.append("\n poolPingEnabled ").append(dataSource.poolPingEnabled); builder.append("\n poolPingQuery ").append(dataSource.poolPingQuery); builder.append("\n poolPingConnectionsNotUsedFor ").append(dataSource.poolPingConnectionsNotUsedFor); builder.append("\n ---STATUS-----------------------------------------------------"); builder.append("\n activeConnections ").append(getActiveConnectionCount()); builder.append("\n idleConnections ").append(getIdleConnectionCount()); builder.append("\n requestCount ").append(getRequestCount()); builder.append("\n averageRequestTime ").append(getAverageRequestTime()); builder.append("\n averageCheckoutTime ").append(getAverageCheckoutTime()); builder.append("\n claimedOverdue ").append(getClaimedOverdueConnectionCount()); builder.append("\n averageOverdueCheckoutTime ").append(getAverageOverdueCheckoutTime()); builder.append("\n hadToWait ").append(getHadToWaitCount()); builder.append("\n averageWaitTime ").append(getAverageWaitTime()); builder.append("\n badConnectionCount ").append(getBadConnectionCount()); builder.append("\n==============================================================="); return builder.toString(); } finally { lock.unlock(); } } }
PoolState
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/PipelineStepWithEventTest.java
{ "start": 4381, "end": 4534 }
interface ____ { void beforeStep(BeforeStepEvent event); void afterStep(AfterStepEvent event); } private static
StepEventListener
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/utils/FieldUtils.java
{ "start": 1899, "end": 2762 }
class ____ its inherited types * * @param declaredClass the declared class * @param fieldName the name of {@link Field} * @return if can't be found, return <code>null</code> */ static Field findField(Class<?> declaredClass, String fieldName) { Field field = getDeclaredField(declaredClass, fieldName); if (field != null) { return field; } for (Class superType : getAllInheritedTypes(declaredClass)) { field = getDeclaredField(superType, fieldName); if (field != null) { break; } } if (field == null) { throw new IllegalStateException(String.format("cannot find field %s,field is null", fieldName)); } return field; } /** * Find the {@link Field} by the name in the specified
and
java
elastic__elasticsearch
x-pack/plugin/slm/src/main/java/org/elasticsearch/xpack/slm/ReservedLifecycleStateHandlerProvider.java
{ "start": 569, "end": 1118 }
class ____ implements ReservedStateHandlerProvider { private final SnapshotLifecycle plugin; public ReservedLifecycleStateHandlerProvider() { throw new IllegalStateException("Provider must be constructed using PluginsService"); } public ReservedLifecycleStateHandlerProvider(SnapshotLifecycle plugin) { this.plugin = plugin; } @Override public Collection<ReservedClusterStateHandler<?>> clusterHandlers() { return plugin.reservedClusterStateHandlers(); } }
ReservedLifecycleStateHandlerProvider
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/inference/chunking/SentenceBoundaryChunkerTests.java
{ "start": 1017, "end": 15480 }
class ____ extends ESTestCase { /** * Utility method for testing. * Use the chunk functions that return offsets where possible */ private List<String> textChunks( SentenceBoundaryChunker chunker, String input, int maxNumberWordsPerChunk, boolean includePrecedingSentence ) { var chunkPositions = chunker.chunk(input, maxNumberWordsPerChunk, includePrecedingSentence); return chunkPositions.stream().map(offset -> input.substring(offset.start(), offset.end())).collect(Collectors.toList()); } public void testEmptyString() { var chunks = textChunks(new SentenceBoundaryChunker(), "", 100, randomBoolean()); assertThat(chunks, hasSize(1)); assertThat(chunks.get(0), Matchers.is("")); } public void testBlankString() { var chunks = textChunks(new SentenceBoundaryChunker(), " ", 100, randomBoolean()); assertThat(chunks, hasSize(1)); assertThat(chunks.get(0), Matchers.is(" ")); } public void testSingleChar() { var chunks = textChunks(new SentenceBoundaryChunker(), " b", 100, randomBoolean()); assertThat(chunks, Matchers.contains(" b")); chunks = textChunks(new SentenceBoundaryChunker(), "b", 100, randomBoolean()); assertThat(chunks, Matchers.contains("b")); chunks = textChunks(new SentenceBoundaryChunker(), ". ", 100, randomBoolean()); assertThat(chunks, Matchers.contains(". ")); chunks = textChunks(new SentenceBoundaryChunker(), " , ", 100, randomBoolean()); assertThat(chunks, Matchers.contains(" , ")); chunks = textChunks(new SentenceBoundaryChunker(), " ,", 100, randomBoolean()); assertThat(chunks, Matchers.contains(" ,")); } public void testSingleCharRepeated() { var input = "a".repeat(32_000); var chunks = textChunks(new SentenceBoundaryChunker(), input, 100, randomBoolean()); assertThat(chunks, Matchers.contains(input)); } public void testChunkSplitLargeChunkSizes() { for (int maxWordsPerChunk : new int[] { 100, 200 }) { var chunker = new SentenceBoundaryChunker(); var chunks = textChunks(chunker, TEST_TEXT, maxWordsPerChunk, false); int numChunks = expectedNumberOfChunks(sentenceSizes(TEST_TEXT), maxWordsPerChunk); assertThat("words per chunk " + maxWordsPerChunk, chunks, hasSize(numChunks)); for (var chunk : chunks) { assertTrue(Character.isUpperCase(chunk.charAt(0))); var trailingWhiteSpaceRemoved = chunk.strip(); var lastChar = trailingWhiteSpaceRemoved.charAt(trailingWhiteSpaceRemoved.length() - 1); assertThat(lastChar, Matchers.is('.')); } } } public void testChunkSplitLargeChunkSizes_withOverlap() { boolean overlap = true; for (int maxWordsPerChunk : new int[] { 70, 80, 100, 120, 150, 200 }) { var chunker = new SentenceBoundaryChunker(); var chunks = textChunks(chunker, TEST_TEXT, maxWordsPerChunk, overlap); int[] overlaps = chunkOverlaps(sentenceSizes(TEST_TEXT), maxWordsPerChunk, overlap); assertThat("words per chunk " + maxWordsPerChunk, chunks, hasSize(overlaps.length)); assertTrue(Character.isUpperCase(chunks.get(0).charAt(0))); for (int i = 0; i < overlaps.length; i++) { if (overlaps[i] == 0) { // start of a sentence assertTrue(Character.isUpperCase(chunks.get(i).charAt(0))); } else { // The start of this chunk should contain some text from the end of the previous var previousChunk = chunks.get(i - 1); assertThat(chunks.get(i), containsString(previousChunk.substring(previousChunk.length() - 20))); } } var trailingWhiteSpaceRemoved = chunks.get(0).strip(); var lastChar = trailingWhiteSpaceRemoved.charAt(trailingWhiteSpaceRemoved.length() - 1); assertThat(lastChar, Matchers.is('.')); trailingWhiteSpaceRemoved = chunks.get(chunks.size() - 1).strip(); lastChar = trailingWhiteSpaceRemoved.charAt(trailingWhiteSpaceRemoved.length() - 1); assertThat(lastChar, Matchers.is('.')); } } public void testWithOverlap_SentencesFitInChunks() { int numChunks = 4; int chunkSize = 100; var sb = new StringBuilder(); int[] sentenceStartIndexes = new int[numChunks]; sentenceStartIndexes[0] = 0; int numSentences = randomIntBetween(2, 5); int sentenceIndex = 0; int lastSentenceSize = 0; int roughSentenceSize = (chunkSize / numSentences) - 1; for (int j = 0; j < numSentences; j++) { sb.append(makeSentence(roughSentenceSize, sentenceIndex++)); lastSentenceSize = roughSentenceSize; } for (int i = 1; i < numChunks; i++) { sentenceStartIndexes[i] = sentenceIndex - 1; roughSentenceSize = (chunkSize / numSentences) - 1; int wordCount = lastSentenceSize; while (wordCount + roughSentenceSize < chunkSize) { sb.append(makeSentence(roughSentenceSize, sentenceIndex++)); lastSentenceSize = roughSentenceSize; wordCount += roughSentenceSize; } } var chunker = new SentenceBoundaryChunker(); var chunks = textChunks(chunker, sb.toString(), chunkSize, true); assertThat(chunks, hasSize(numChunks)); for (int i = 0; i < numChunks; i++) { assertThat("num sentences " + numSentences, chunks.get(i), startsWith("SStart" + sentenceStartIndexes[i])); assertThat("num sentences " + numSentences, chunks.get(i).trim(), endsWith(".")); } } private String makeSentence(int numWords, int sentenceIndex) { StringBuilder sb = new StringBuilder(); sb.append("SStart").append(sentenceIndex).append(' '); for (int i = 1; i < numWords - 1; i++) { sb.append(i).append(' '); } sb.append(numWords - 1).append(". "); return sb.toString(); } public void testChunk_ChunkSizeLargerThanText() { int maxWordsPerChunk = 500; var chunker = new SentenceBoundaryChunker(); var chunks = textChunks(chunker, TEST_TEXT, maxWordsPerChunk, false); assertEquals(chunks.get(0), TEST_TEXT); chunks = textChunks(chunker, TEST_TEXT, maxWordsPerChunk, true); assertEquals(chunks.get(0), TEST_TEXT); } public void testChunkSplit_SentencesLongerThanChunkSize() { var chunkSizes = new int[] { 10, 30, 50 }; var expectedNumberOFChunks = new int[] { 21, 7, 4 }; for (int i = 0; i < chunkSizes.length; i++) { int maxWordsPerChunk = chunkSizes[i]; var chunker = new SentenceBoundaryChunker(); var chunks = textChunks(chunker, TEST_TEXT, maxWordsPerChunk, false); assertThat("words per chunk " + maxWordsPerChunk, chunks, hasSize(expectedNumberOFChunks[i])); for (var chunk : chunks) { // count whitespaced words // strip out the '=' signs as they are not counted as words by ICU var trimmed = chunk.trim().replace("=", ""); // split by hyphen or whitespace to match the way // the ICU break iterator counts words var split = trimmed.split("[\\s\\-]+"); int numWhiteSpacedWords = (int) Arrays.stream(split).filter(s -> s.isEmpty() == false).count(); if (chunk.trim().endsWith(".")) { // End of sentence, may be less than maxWordsPerChunk assertThat(Arrays.toString(split), numWhiteSpacedWords, lessThanOrEqualTo(maxWordsPerChunk)); } else { // splitting inside a sentence so should have max words assertEquals(Arrays.toString(split), maxWordsPerChunk, numWhiteSpacedWords); } } } } public void testChunkSplit_SentencesLongerThanChunkSize_WithOverlap() { var chunkSizes = new int[] { 10, 30, 50 }; // Chunk sizes are shorter the sentences most of the sentences will be split. for (int i = 0; i < chunkSizes.length; i++) { int maxWordsPerChunk = chunkSizes[i]; var chunker = new SentenceBoundaryChunker(); var chunks = textChunks(chunker, TEST_TEXT, maxWordsPerChunk, true); assertThat(chunks.get(0), containsString("Word segmentation is the problem of dividing")); assertThat(chunks.get(chunks.size() - 1), containsString(", with solidification being a stronger norm.")); } } public void testShortLongShortSentences_WithOverlap() { int maxWordsPerChunk = 40; var sb = new StringBuilder(); int[] sentenceLengths = new int[] { 15, 30, 20, 5 }; for (int l = 0; l < sentenceLengths.length; l++) { sb.append("SStart").append(l).append(" "); for (int i = 1; i < sentenceLengths[l] - 1; i++) { sb.append(i).append(' '); } sb.append(sentenceLengths[l] - 1).append(". "); } var chunker = new SentenceBoundaryChunker(); var chunks = textChunks(chunker, sb.toString(), maxWordsPerChunk, true); assertThat(chunks, hasSize(5)); assertTrue(chunks.get(0).trim().startsWith("SStart0")); // Entire sentence assertTrue(chunks.get(0).trim().endsWith(".")); // Entire sentence assertTrue(chunks.get(1).trim().startsWith("SStart0")); // contains previous sentence assertFalse(chunks.get(1).trim().endsWith(".")); // not a full sentence(s) assertTrue(chunks.get(2).trim().endsWith(".")); assertTrue(chunks.get(3).trim().endsWith(".")); assertTrue(chunks.get(4).trim().startsWith("SStart2")); // contains previous sentence assertThat(chunks.get(4), containsString("SStart3")); // last chunk contains 2 sentences assertTrue(chunks.get(4).trim().endsWith(".")); // full sentence(s) } public void testSkipWords() { int numWords = 50; StringBuilder sb = new StringBuilder(); for (int i = 0; i < numWords; i++) { sb.append("word").append(i).append(" "); } var text = sb.toString(); var wordIterator = BreakIterator.getWordInstance(Locale.ROOT); wordIterator.setText(text); int start = 0; int pos = SentenceBoundaryChunker.skipWords(start, 3, wordIterator); assertThat(text.substring(pos), startsWith("word3 ")); pos = SentenceBoundaryChunker.skipWords(pos + 1, 1, wordIterator); assertThat(text.substring(pos), startsWith("word4 ")); pos = SentenceBoundaryChunker.skipWords(pos + 1, 5, wordIterator); assertThat(text.substring(pos), startsWith("word9 ")); // past the end of the input pos = SentenceBoundaryChunker.skipWords(0, numWords + 10, wordIterator); assertThat(pos, greaterThan(0)); } public void testChunkSplitLargeChunkSizesWithChunkingSettings() { for (int maxWordsPerChunk : new int[] { 100, 200 }) { var chunker = new SentenceBoundaryChunker(); SentenceBoundaryChunkingSettings chunkingSettings = new SentenceBoundaryChunkingSettings(maxWordsPerChunk, 0); var chunks = textChunks(chunker, TEST_TEXT, maxWordsPerChunk, false); int numChunks = expectedNumberOfChunks(sentenceSizes(TEST_TEXT), maxWordsPerChunk); assertThat("words per chunk " + maxWordsPerChunk, chunks, hasSize(numChunks)); for (var chunk : chunks) { assertTrue(Character.isUpperCase(chunk.charAt(0))); var trailingWhiteSpaceRemoved = chunk.strip(); var lastChar = trailingWhiteSpaceRemoved.charAt(trailingWhiteSpaceRemoved.length() - 1); assertThat(lastChar, Matchers.is('.')); } } } public void testInvalidChunkingSettingsProvided() { var maxChunkSize = randomIntBetween(10, 300); ChunkingSettings chunkingSettings = new WordBoundaryChunkingSettings(maxChunkSize, randomIntBetween(1, maxChunkSize / 2)); assertThrows(IllegalArgumentException.class, () -> { new SentenceBoundaryChunker().chunk(TEST_TEXT, chunkingSettings); }); } private int[] sentenceSizes(String text) { var sentences = text.split("\\.\\s+"); var lengths = new int[sentences.length]; for (int i = 0; i < sentences.length; i++) { // strip out the '=' signs as they are not counted as words by ICU sentences[i] = sentences[i].replace("=", ""); // split by hyphen or whitespace to match the way // the ICU break iterator counts words lengths[i] = sentences[i].split("[ \\-]+").length; } return lengths; } private int expectedNumberOfChunks(int[] sentenceLengths, int maxWordsPerChunk) { return chunkOverlaps(sentenceLengths, maxWordsPerChunk, false).length; } private int[] chunkOverlaps(int[] sentenceLengths, int maxWordsPerChunk, boolean includeSingleSentenceOverlap) { int maxOverlap = SentenceBoundaryChunker.maxWordsInOverlap(maxWordsPerChunk); var overlaps = new ArrayList<Integer>(); overlaps.add(0); int runningWordCount = 0; for (int i = 0; i < sentenceLengths.length; i++) { if (runningWordCount + sentenceLengths[i] > maxWordsPerChunk) { runningWordCount = sentenceLengths[i]; if (includeSingleSentenceOverlap && i > 0) { // include what is carried over from the previous int overlap = Math.min(maxOverlap, sentenceLengths[i - 1]); overlaps.add(overlap); runningWordCount += overlap; } else { overlaps.add(0); } } else { runningWordCount += sentenceLengths[i]; } } return overlaps.stream().mapToInt(Integer::intValue).toArray(); } }
SentenceBoundaryChunkerTests
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/transport/TransportKeepAliveTests.java
{ "start": 8606, "end": 9191 }
class ____ extends TestThreadPool { private final Deque<Tuple<TimeValue, Runnable>> scheduledTasks = new ArrayDeque<>(); private CapturingThreadPool() { super(getTestName()); } @Override public ScheduledCancellable schedule(Runnable task, TimeValue delay, Executor executor) { return doSchedule(task, delay); } private ScheduledCancellable doSchedule(Runnable task, TimeValue delay) { scheduledTasks.add(new Tuple<>(delay, task)); return null; } } }
CapturingThreadPool
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/introspect/TestPropertyConflicts.java
{ "start": 661, "end": 828 }
class ____ { public int getX() { return 3; } public boolean getx() { return false; } } // [databind#238] protected static
BeanWithConflict
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/MultipleErrorHandlerOnExceptionIssueTest.java
{ "start": 1048, "end": 3080 }
class ____ extends ContextTestSupport { @Test public void testMultipleErrorHandlerOnExceptionA() throws Exception { getMockEndpoint("mock:handled").expectedMessageCount(1); getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:b").expectedMessageCount(0); getMockEndpoint("mock:dead.a").expectedMessageCount(0); getMockEndpoint("mock:dead.b").expectedMessageCount(0); template.sendBody("seda:a", "Hello World"); assertMockEndpointsSatisfied(); } @Test public void testMultipleErrorHandlerOnExceptionB() throws Exception { getMockEndpoint("mock:handled").expectedMessageCount(0); getMockEndpoint("mock:a").expectedMessageCount(0); getMockEndpoint("mock:b").expectedMessageCount(1); getMockEndpoint("mock:dead.a").expectedMessageCount(0); getMockEndpoint("mock:dead.b").expectedMessageCount(1); template.sendBody("seda:b", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { onException(IllegalArgumentException.class).handled(true).to("mock:handled"); from("seda:a") .errorHandler(deadLetterChannel("mock:dead.a").maximumRedeliveries(3).redeliveryDelay(0) .retryAttemptedLogLevel(LoggingLevel.WARN).asyncDelayedRedelivery()) .to("mock:a").throwException(new IllegalArgumentException("Forced A")); from("seda:b") .errorHandler(deadLetterChannel("mock:dead.b").maximumRedeliveries(2).redeliveryDelay(0) .retryAttemptedLogLevel(LoggingLevel.WARN)) .to("mock:b") .throwException(new IOException("Some IO error")); } }; } }
MultipleErrorHandlerOnExceptionIssueTest
java
quarkusio__quarkus
extensions/oidc-client/runtime/src/test/java/io/quarkus/oidc/client/OidcClientConfigTest.java
{ "start": 704, "end": 805 }
interface ____ class" .formatted(configMappingMethod)); } } }
to
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1395/spring/Issue1395Test.java
{ "start": 562, "end": 657 }
class ____ { @ProcessorTest public void shouldGenerateValidCode() { } }
Issue1395Test
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/results/internal/implicit/ImplicitModelPartResultBuilderEntity.java
{ "start": 837, "end": 3197 }
class ____ implements ImplicitModelPartResultBuilder, ResultBuilderEntityValued { private final NavigablePath navigablePath; private final EntityValuedModelPart modelPart; public ImplicitModelPartResultBuilderEntity( NavigablePath navigablePath, EntityValuedModelPart modelPart) { this.navigablePath = navigablePath; this.modelPart = modelPart; } public ImplicitModelPartResultBuilderEntity(EntityMappingType entityMappingType) { this( new NavigablePath( entityMappingType.getEntityName() ), entityMappingType ); } @Override public Class<?> getJavaType() { return modelPart.getJavaType().getJavaTypeClass(); } @Override public ResultBuilder cacheKeyInstance() { return this; } @Override public EntityResult buildResult( JdbcValuesMetadata jdbcResultsMetadata, int resultPosition, DomainResultCreationState domainResultCreationState) { final DomainResultCreationStateImpl creationStateImpl = ResultsHelper.impl( domainResultCreationState ); creationStateImpl.disallowPositionalSelections(); return (EntityResult) modelPart.createDomainResult( navigablePath, tableGroup( creationStateImpl ), null, domainResultCreationState ); } private TableGroup tableGroup(DomainResultCreationStateImpl creationStateImpl) { return creationStateImpl.getFromClauseAccess().resolveTableGroup( navigablePath, np -> navigablePath.getParent() != null ? creationStateImpl.getFromClauseAccess().getTableGroup( navigablePath.getParent() ) : modelPart.getEntityMappingType().createRootTableGroup( // since this is only used for result set mappings, // the canUseInnerJoins value is irrelevant. true, navigablePath, null, null, null, creationStateImpl ) ); } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } final ImplicitModelPartResultBuilderEntity that = (ImplicitModelPartResultBuilderEntity) o; return navigablePath.equals( that.navigablePath ) && modelPart.equals( that.modelPart ); } @Override public int hashCode() { int result = navigablePath.hashCode(); result = 31 * result + modelPart.hashCode(); return result; } }
ImplicitModelPartResultBuilderEntity
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/core/authority/mapping/MapBasedAttributes2GrantedAuthoritiesMapperTests.java
{ "start": 1201, "end": 7450 }
class ____ { @Test public void testAfterPropertiesSetEmptyMap() throws Exception { MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); assertThatIllegalArgumentException() .isThrownBy(() -> mapper.setAttributes2grantedAuthoritiesMap(new HashMap())); } @Test public void testAfterPropertiesSetInvalidKeyTypeMap() throws Exception { MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); HashMap m = new HashMap(); m.put(new Object(), "ga1"); assertThatIllegalArgumentException().isThrownBy(() -> mapper.setAttributes2grantedAuthoritiesMap(m)); } @Test public void testAfterPropertiesSetInvalidValueTypeMap1() throws Exception { MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); HashMap m = new HashMap(); m.put("role1", new Object()); assertThatIllegalArgumentException().isThrownBy(() -> mapper.setAttributes2grantedAuthoritiesMap(m)); } @Test public void testAfterPropertiesSetInvalidValueTypeMap2() throws Exception { MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); HashMap m = new HashMap(); m.put("role1", new Object[] { new String[] { "ga1", "ga2" }, new Object() }); assertThatIllegalArgumentException().isThrownBy(() -> mapper.setAttributes2grantedAuthoritiesMap(m)); } @Test public void testAfterPropertiesSetValidMap() throws Exception { MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); HashMap m = getValidAttributes2GrantedAuthoritiesMap(); mapper.setAttributes2grantedAuthoritiesMap(m); mapper.afterPropertiesSet(); } @Test public void testMapping1() throws Exception { String[] roles = { "role1" }; String[] expectedGas = { "ga1" }; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } @Test public void testMapping2() throws Exception { String[] roles = { "role2" }; String[] expectedGas = { "ga2" }; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } @Test public void testMapping3() throws Exception { String[] roles = { "role3" }; String[] expectedGas = { "ga3", "ga4" }; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } @Test public void testMapping4() throws Exception { String[] roles = { "role4" }; String[] expectedGas = { "ga5", "ga6" }; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } @Test public void testMapping5() throws Exception { String[] roles = { "role5" }; String[] expectedGas = { "ga7", "ga8", "ga9" }; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } @Test public void testMapping6() throws Exception { String[] roles = { "role6" }; String[] expectedGas = { "ga10", "ga11", "ga12" }; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } @Test public void testMapping7() throws Exception { String[] roles = { "role7" }; String[] expectedGas = { "ga13", "ga14" }; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } @Test public void testMapping8() throws Exception { String[] roles = { "role8" }; String[] expectedGas = { "ga13", "ga14" }; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } @Test public void testMapping9() throws Exception { String[] roles = { "role9" }; String[] expectedGas = {}; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } @Test public void testMapping10() throws Exception { String[] roles = { "role10" }; String[] expectedGas = {}; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } @Test public void testMapping11() throws Exception { String[] roles = { "role11" }; String[] expectedGas = {}; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } @Test public void testNonExistingMapping() throws Exception { String[] roles = { "nonExisting" }; String[] expectedGas = {}; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } @Test public void testMappingCombination() throws Exception { String[] roles = { "role1", "role2", "role3", "role4", "role5", "role6", "role7", "role8", "role9", "role10", "role11" }; String[] expectedGas = { "ga1", "ga2", "ga3", "ga4", "ga5", "ga6", "ga7", "ga8", "ga9", "ga10", "ga11", "ga12", "ga13", "ga14" }; testGetGrantedAuthorities(getDefaultMapper(), roles, expectedGas); } private HashMap getValidAttributes2GrantedAuthoritiesMap() { HashMap m = new HashMap(); m.put("role1", "ga1"); m.put("role2", new SimpleGrantedAuthority("ga2")); m.put("role3", Arrays.asList("ga3", new SimpleGrantedAuthority("ga4"))); m.put("role4", "ga5,ga6"); m.put("role5", Arrays.asList("ga7", "ga8", new Object[] { new SimpleGrantedAuthority("ga9") })); m.put("role6", new Object[] { "ga10", "ga11", new Object[] { new SimpleGrantedAuthority("ga12") } }); m.put("role7", new String[] { "ga13", "ga14" }); m.put("role8", new String[] { "ga13", "ga14", null }); m.put("role9", null); m.put("role10", new Object[] {}); m.put("role11", Arrays.asList(new Object[] { null })); return m; } private MapBasedAttributes2GrantedAuthoritiesMapper getDefaultMapper() throws Exception { MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); mapper.setAttributes2grantedAuthoritiesMap(getValidAttributes2GrantedAuthoritiesMap()); mapper.afterPropertiesSet(); return mapper; } private void testGetGrantedAuthorities(MapBasedAttributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) { List<GrantedAuthority> result = mapper.getGrantedAuthorities(Arrays.asList(roles)); Collection resultColl = new ArrayList(result.size()); for (GrantedAuthority auth : result) { resultColl.add(auth.getAuthority()); } Collection expectedColl = Arrays.asList(expectedGas); assertThat(resultColl.containsAll(expectedColl)) .withFailMessage("Role collections should match; result: " + resultColl + ", expected: " + expectedColl) .isTrue(); } }
MapBasedAttributes2GrantedAuthoritiesMapperTests
java
apache__kafka
server/src/main/java/org/apache/kafka/network/SocketServerConfigs.java
{ "start": 5628, "end": 16976 }
interface ____ which the broker binds." + " If this is not set, the value for <code>%1$1s</code> will be used." + " Unlike <code>%1$1s</code>, it is not valid to advertise the 0.0.0.0 meta-address.%n" + " Also unlike <code>%1$1s</code>, there can be duplicated ports in this property," + " so that one listener can be configured to advertise another listener's address." + " This can be useful in some cases where external load balancers are used.", LISTENERS_CONFIG); public static final String SOCKET_SEND_BUFFER_BYTES_CONFIG = "socket.send.buffer.bytes"; public static final int SOCKET_SEND_BUFFER_BYTES_DEFAULT = 100 * 1024; public static final String SOCKET_SEND_BUFFER_BYTES_DOC = "The SO_SNDBUF buffer of the socket server sockets. If the value is -1, the OS default will be used."; public static final String SOCKET_RECEIVE_BUFFER_BYTES_CONFIG = "socket.receive.buffer.bytes"; public static final int SOCKET_RECEIVE_BUFFER_BYTES_DEFAULT = 100 * 1024; public static final String SOCKET_RECEIVE_BUFFER_BYTES_DOC = "The SO_RCVBUF buffer of the socket server sockets. If the value is -1, the OS default will be used."; public static final String SOCKET_REQUEST_MAX_BYTES_CONFIG = "socket.request.max.bytes"; public static final int SOCKET_REQUEST_MAX_BYTES_DEFAULT = 100 * 1024 * 1024; public static final String SOCKET_REQUEST_MAX_BYTES_DOC = "The maximum number of bytes in a socket request"; public static final String SOCKET_LISTEN_BACKLOG_SIZE_CONFIG = "socket.listen.backlog.size"; public static final int SOCKET_LISTEN_BACKLOG_SIZE_DEFAULT = 50; public static final String SOCKET_LISTEN_BACKLOG_SIZE_DOC = "The maximum number of pending connections on the socket. " + "In Linux, you may also need to configure <code>somaxconn</code> and <code>tcp_max_syn_backlog</code> kernel parameters " + "accordingly to make the configuration takes effect."; public static final String MAX_CONNECTIONS_PER_IP_OVERRIDES_CONFIG = "max.connections.per.ip.overrides"; public static final String MAX_CONNECTIONS_PER_IP_OVERRIDES_DEFAULT = ""; public static final String MAX_CONNECTIONS_PER_IP_OVERRIDES_DOC = "A comma-separated list of per-ip or hostname overrides to the default maximum number of connections. " + "An example value is \"hostName:100,127.0.0.1:200\""; public static final String MAX_CONNECTIONS_PER_IP_CONFIG = "max.connections.per.ip"; public static final int MAX_CONNECTIONS_PER_IP_DEFAULT = Integer.MAX_VALUE; public static final String MAX_CONNECTIONS_PER_IP_DOC = "The maximum number of connections we allow from each ip address. This can be set to 0 if there are overrides " + String.format("configured using %s property. New connections from the ip address are dropped if the limit is reached.", MAX_CONNECTIONS_PER_IP_OVERRIDES_CONFIG); public static final String MAX_CONNECTIONS_CONFIG = "max.connections"; public static final int MAX_CONNECTIONS_DEFAULT = Integer.MAX_VALUE; public static final String MAX_CONNECTIONS_DOC = String.format( "The maximum number of connections we allow in the broker at any time. This limit is applied in addition " + "to any per-ip limits configured using %s. Listener-level limits may also be configured by prefixing the " + "config name with the listener prefix, for example, <code>listener.name.internal.%1$1s</code>. Broker-wide limit " + "should be configured based on broker capacity while listener limits should be configured based on application requirements. " + "New connections are blocked if either the listener or broker limit is reached. Connections on the inter-broker listener are " + "permitted even if broker-wide limit is reached. The least recently used connection on another listener will be closed in this case.", MAX_CONNECTIONS_PER_IP_CONFIG); public static final String MAX_CONNECTION_CREATION_RATE_CONFIG = "max.connection.creation.rate"; public static final int MAX_CONNECTION_CREATION_RATE_DEFAULT = Integer.MAX_VALUE; public static final String MAX_CONNECTION_CREATION_RATE_DOC = "The maximum connection creation rate we allow in the broker at any time. Listener-level limits " + String.format("may also be configured by prefixing the config name with the listener prefix, for example, <code>listener.name.internal.%s</code>.", MAX_CONNECTION_CREATION_RATE_CONFIG) + "Broker-wide connection rate limit should be configured based on broker capacity while listener limits should be configured based on " + "application requirements. New connections will be throttled if either the listener or the broker limit is reached, with the exception " + "of inter-broker listener. Connections on the inter-broker listener will be throttled only when the listener-level rate limit is reached."; public static final String CONNECTIONS_MAX_IDLE_MS_CONFIG = "connections.max.idle.ms"; public static final long CONNECTIONS_MAX_IDLE_MS_DEFAULT = 10 * 60 * 1000L; public static final String CONNECTIONS_MAX_IDLE_MS_DOC = "Idle connections timeout: the server socket processor threads close the connections that idle more than this"; public static final String FAILED_AUTHENTICATION_DELAY_MS_CONFIG = "connection.failed.authentication.delay.ms"; public static final int FAILED_AUTHENTICATION_DELAY_MS_DEFAULT = 100; public static final String FAILED_AUTHENTICATION_DELAY_MS_DOC = "Connection close delay on failed authentication: this is the time (in milliseconds) by which connection close will be delayed on authentication failure. " + String.format("This must be configured to be less than %s to prevent connection timeout.", CONNECTIONS_MAX_IDLE_MS_CONFIG); public static final String QUEUED_MAX_REQUESTS_CONFIG = "queued.max.requests"; public static final int QUEUED_MAX_REQUESTS_DEFAULT = 500; public static final String QUEUED_MAX_REQUESTS_DOC = "The number of queued requests allowed for data-plane, before blocking the network threads"; public static final String QUEUED_MAX_BYTES_CONFIG = "queued.max.request.bytes"; public static final int QUEUED_MAX_REQUEST_BYTES_DEFAULT = -1; public static final String QUEUED_MAX_REQUEST_BYTES_DOC = "The number of queued bytes allowed before no more requests are read"; public static final String NUM_NETWORK_THREADS_CONFIG = "num.network.threads"; public static final int NUM_NETWORK_THREADS_DEFAULT = 3; public static final String NUM_NETWORK_THREADS_DOC = "The number of threads that the server uses for receiving requests from the network and sending responses to the network. Noted: each listener (except for controller listener) creates its own thread pool."; public static final ConfigDef CONFIG_DEF = new ConfigDef() .define(LISTENERS_CONFIG, LIST, LISTENERS_DEFAULT, ConfigDef.ValidList.anyNonDuplicateValues(false, false), HIGH, LISTENERS_DOC) .define(ADVERTISED_LISTENERS_CONFIG, LIST, null, ConfigDef.ValidList.anyNonDuplicateValues(false, true), HIGH, ADVERTISED_LISTENERS_DOC) .define(LISTENER_SECURITY_PROTOCOL_MAP_CONFIG, STRING, LISTENER_SECURITY_PROTOCOL_MAP_DEFAULT, LOW, LISTENER_SECURITY_PROTOCOL_MAP_DOC) .define(SOCKET_SEND_BUFFER_BYTES_CONFIG, INT, SOCKET_SEND_BUFFER_BYTES_DEFAULT, HIGH, SOCKET_SEND_BUFFER_BYTES_DOC) .define(SOCKET_RECEIVE_BUFFER_BYTES_CONFIG, INT, SOCKET_RECEIVE_BUFFER_BYTES_DEFAULT, HIGH, SOCKET_RECEIVE_BUFFER_BYTES_DOC) .define(SOCKET_REQUEST_MAX_BYTES_CONFIG, INT, SOCKET_REQUEST_MAX_BYTES_DEFAULT, atLeast(1), HIGH, SOCKET_REQUEST_MAX_BYTES_DOC) .define(SOCKET_LISTEN_BACKLOG_SIZE_CONFIG, INT, SOCKET_LISTEN_BACKLOG_SIZE_DEFAULT, atLeast(1), MEDIUM, SOCKET_LISTEN_BACKLOG_SIZE_DOC) .define(MAX_CONNECTIONS_PER_IP_CONFIG, INT, MAX_CONNECTIONS_PER_IP_DEFAULT, atLeast(0), MEDIUM, MAX_CONNECTIONS_PER_IP_DOC) .define(MAX_CONNECTIONS_PER_IP_OVERRIDES_CONFIG, STRING, MAX_CONNECTIONS_PER_IP_OVERRIDES_DEFAULT, MEDIUM, MAX_CONNECTIONS_PER_IP_OVERRIDES_DOC) .define(MAX_CONNECTIONS_CONFIG, INT, MAX_CONNECTIONS_DEFAULT, atLeast(0), MEDIUM, MAX_CONNECTIONS_DOC) .define(MAX_CONNECTION_CREATION_RATE_CONFIG, INT, MAX_CONNECTION_CREATION_RATE_DEFAULT, atLeast(0), MEDIUM, MAX_CONNECTION_CREATION_RATE_DOC) .define(CONNECTIONS_MAX_IDLE_MS_CONFIG, LONG, CONNECTIONS_MAX_IDLE_MS_DEFAULT, MEDIUM, CONNECTIONS_MAX_IDLE_MS_DOC) .define(FAILED_AUTHENTICATION_DELAY_MS_CONFIG, INT, FAILED_AUTHENTICATION_DELAY_MS_DEFAULT, atLeast(0), LOW, FAILED_AUTHENTICATION_DELAY_MS_DOC) .define(QUEUED_MAX_REQUESTS_CONFIG, INT, QUEUED_MAX_REQUESTS_DEFAULT, atLeast(1), HIGH, QUEUED_MAX_REQUESTS_DOC) .define(QUEUED_MAX_BYTES_CONFIG, LONG, QUEUED_MAX_REQUEST_BYTES_DEFAULT, MEDIUM, QUEUED_MAX_REQUEST_BYTES_DOC) .define(NUM_NETWORK_THREADS_CONFIG, INT, NUM_NETWORK_THREADS_DEFAULT, atLeast(1), HIGH, NUM_NETWORK_THREADS_DOC); private static final Pattern URI_PARSE_REGEXP = Pattern.compile( "^(.*)://\\[?([0-9a-zA-Z\\-%._:]*)\\]?:(-?[0-9]+)"); public static final Map<ListenerName, SecurityProtocol> DEFAULT_NAME_TO_SECURITY_PROTO = Arrays.stream(SecurityProtocol.values()) .collect(Collectors.toUnmodifiableMap( ListenerName::forSecurityProtocol, Function.identity() )); public static List<Endpoint> listenerListToEndPoints( List<String> input, Map<ListenerName, SecurityProtocol> nameToSecurityProto ) { return listenerListToEndPoints(input, n -> { SecurityProtocol result = nameToSecurityProto.get(n); if (result == null) { throw new IllegalArgumentException("No security protocol defined for listener " + n.value()); } return result; }); } public static List<Endpoint> listenerListToEndPoints( List<String> input, Function<ListenerName, SecurityProtocol> nameToSecurityProto ) { List<Endpoint> results = new ArrayList<>(); for (String entry : input) { Matcher matcher = URI_PARSE_REGEXP.matcher(entry); if (!matcher.matches()) { throw new KafkaException("Unable to parse " + entry + " to a broker endpoint"); } ListenerName listenerName = ListenerName.normalised(matcher.group(1)); String host = matcher.group(2); if (host.isEmpty()) { // By Kafka convention, an empty host string indicates binding to the wildcard // address, and is stored as null. host = null; } String portString = matcher.group(3); int port = Integer.parseInt(portString); SecurityProtocol securityProtocol = nameToSecurityProto.apply(listenerName); results.add(new Endpoint(listenerName.value(), securityProtocol, host, port)); } return results; } }
to
java
qos-ch__slf4j
slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java
{ "start": 1522, "end": 1597 }
class ____ * compile time. * * @author Ceki G&uuml;lc&uuml; */ public
at
java
apache__flink
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/util/ClientWrapperClassLoader.java
{ "start": 2314, "end": 2462 }
class ____ resource, any classes or * resources in the removed jar that are already loaded, are still accessible. */ @Experimental @Internal public
or
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/utils/Duration.java
{ "start": 1036, "end": 2805 }
class ____ implements Closeable { public long start, finish; public final long limit; /** * Create a duration instance with a limit of 0 */ public Duration() { this(0); } /** * Create a duration with a limit specified in millis * @param limit duration in milliseconds */ public Duration(long limit) { this.limit = limit; } /** * Start * @return self */ public Duration start() { start = now(); return this; } /** * The close operation relays to {@link #finish()}. * Implementing it allows Duration instances to be automatically * finish()'d in Java7 try blocks for when used in measuring durations. */ @Override public final void close() { finish(); } public void finish() { finish = now(); } protected long now() { return System.nanoTime()/1000000; } public long getInterval() { return finish - start; } /** * return true if the limit has been exceeded * @return true if a limit was set and the current time * exceeds it. */ public boolean getLimitExceeded() { return limit >= 0 && ((now() - start) > limit); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Duration"); if (finish >= start) { builder.append(" finished at ").append(getInterval()).append(" millis;"); } else { if (start > 0) { builder.append(" started but not yet finished;"); } else { builder.append(" unstarted;"); } } if (limit > 0) { builder.append(" limit: ").append(limit).append(" millis"); if (getLimitExceeded()) { builder.append(" - exceeded"); } } return builder.toString(); } }
Duration