language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/seq/PolyMapWriter827Test.java
{ "start": 624, "end": 767 }
class ____ { String a; int b; @Override public String toString() { return "BAD-KEY"; } } public
CustomKey
java
spring-projects__spring-boot
module/spring-boot-r2dbc/src/main/java/org/springframework/boot/r2dbc/autoconfigure/ConnectionFactoryConfigurations.java
{ "start": 3845, "end": 3968 }
class ____ { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ConnectionPool.class) static
PoolConfiguration
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/JobExceptionsInfoWithHistory.java
{ "start": 3302, "end": 5283 }
class ____ { public static final String FIELD_NAME_ENTRIES = "entries"; public static final String FIELD_NAME_TRUNCATED = "truncated"; @JsonProperty(FIELD_NAME_ENTRIES) private final List<RootExceptionInfo> entries; @JsonProperty(FIELD_NAME_TRUNCATED) private final boolean truncated; @JsonCreator public JobExceptionHistory( @JsonProperty(FIELD_NAME_ENTRIES) List<RootExceptionInfo> entries, @JsonProperty(FIELD_NAME_TRUNCATED) boolean truncated) { this.entries = entries; this.truncated = truncated; } @JsonIgnore public List<RootExceptionInfo> getEntries() { return entries; } @JsonIgnore public boolean isTruncated() { return truncated; } // hashCode and equals are necessary for the test classes deriving from // RestResponseMarshallingTestBase @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JobExceptionHistory that = (JobExceptionHistory) o; return this.isTruncated() == that.isTruncated() && Objects.equals(entries, that.entries); } @Override public int hashCode() { return Objects.hash(entries, truncated); } @Override public String toString() { return new StringJoiner(", ", JobExceptionHistory.class.getSimpleName() + "[", "]") .add("entries=" + entries) .add("truncated=" + truncated) .toString(); } } /** * Json equivalent of {@link * org.apache.flink.runtime.scheduler.exceptionhistory.ExceptionHistoryEntry}. */ public static
JobExceptionHistory
java
apache__flink
flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/eventtime/function/TwoOutputEventTimeStreamProcessFunction.java
{ "start": 1397, "end": 2404 }
interface ____<IN, OUT1, OUT2> extends EventTimeProcessFunction, TwoOutputStreamProcessFunction<IN, OUT1, OUT2> { /** * The {@code #onEventTimeWatermark} method signifies that the EventTimeProcessFunction has * received an EventTimeWatermark. Other types of watermarks will be processed by the {@code * ProcessFunction#onWatermark} method. */ default void onEventTimeWatermark( long watermarkTimestamp, Collector<OUT1> output1, Collector<OUT2> output2, TwoOutputNonPartitionedContext<OUT1, OUT2> ctx) throws Exception {} /** * Invoked when an event-time timer fires. Note that it is only used in {@link * KeyedPartitionStream}. */ default void onEventTimer( long timestamp, Collector<OUT1> output1, Collector<OUT2> output2, TwoOutputPartitionedContext<OUT1, OUT2> ctx) throws Exception {} }
TwoOutputEventTimeStreamProcessFunction
java
quarkusio__quarkus
integration-tests/main/src/main/java/io/quarkus/it/rest/TestResourceWithVariable.java
{ "start": 229, "end": 406 }
class ____ { @GET @Produces(MediaType.TEXT_PLAIN) public String hello(@PathParam("name") String name) { return "hello " + name; } }
TestResourceWithVariable
java
resilience4j__resilience4j
resilience4j-rxjava2/src/test/java/io/github/resilience4j/bulkhead/operator/CompletableBulkheadTest.java
{ "start": 490, "end": 1819 }
class ____ { private Bulkhead bulkhead; @Before public void setUp() { bulkhead = mock(Bulkhead.class, RETURNS_DEEP_STUBS); } @Test public void shouldComplete() { given(bulkhead.tryAcquirePermission()).willReturn(true); Completable.complete() .compose(BulkheadOperator.of(bulkhead)) .test() .assertSubscribed() .assertComplete(); then(bulkhead).should().onComplete(); } @Test public void shouldPropagateError() { given(bulkhead.tryAcquirePermission()).willReturn(true); Completable.error(new IOException("BAM!")) .compose(BulkheadOperator.of(bulkhead)) .test() .assertSubscribed() .assertError(IOException.class) .assertNotComplete(); then(bulkhead).should().onComplete(); } @Test public void shouldEmitErrorWithBulkheadFullException() { given(bulkhead.tryAcquirePermission()).willReturn(false); Completable.complete() .compose(BulkheadOperator.of(bulkhead)) .test() .assertSubscribed() .assertError(BulkheadFullException.class) .assertNotComplete(); then(bulkhead).should(never()).onComplete(); } }
CompletableBulkheadTest
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/BeanDescription.java
{ "start": 2348, "end": 2590 }
class ____ described has any * annotations recognized by registered annotation introspector. */ public abstract boolean hasKnownClassAnnotations(); /** * Method for accessing collection of annotations the bean *
being
java
apache__flink
flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/operator/WindowReaderOperator.java
{ "start": 3129, "end": 8120 }
class ____<S extends State, KEY, IN, W extends Window, OUT> extends StateReaderOperator<WindowReaderFunction<IN, OUT, KEY, W>, KEY, W, OUT> { private static final String WINDOW_STATE_NAME = "window-contents"; private static final String WINDOW_TIMER_NAME = "window-timers"; private final WindowContents<S, IN> contents; private final StateDescriptor<S, ?> descriptor; private transient Context ctx; public static <KEY, T, W extends Window, OUT> WindowReaderOperator<?, KEY, T, W, OUT> reduce( ReduceFunction<T> function, WindowReaderFunction<T, OUT, KEY, W> reader, TypeInformation<KEY> keyType, TypeSerializer<W> windowSerializer, TypeInformation<T> inputType) { StateDescriptor<ReducingState<T>, T> descriptor = new ReducingStateDescriptor<>(WINDOW_STATE_NAME, function, inputType); return new WindowReaderOperator<>( reader, keyType, windowSerializer, WindowContents.reducingState(), descriptor); } public static <KEY, T, ACC, R, OUT, W extends Window> WindowReaderOperator<?, KEY, R, W, OUT> aggregate( AggregateFunction<T, ACC, R> function, WindowReaderFunction<R, OUT, KEY, W> readerFunction, TypeInformation<KEY> keyType, TypeSerializer<W> windowSerializer, TypeInformation<ACC> accumulatorType) { StateDescriptor<AggregatingState<T, R>, ACC> descriptor = new AggregatingStateDescriptor<>(WINDOW_STATE_NAME, function, accumulatorType); return new WindowReaderOperator<>( readerFunction, keyType, windowSerializer, WindowContents.aggregatingState(), descriptor); } public static <KEY, T, W extends Window, OUT> WindowReaderOperator<?, KEY, T, W, OUT> process( WindowReaderFunction<T, OUT, KEY, W> readerFunction, TypeInformation<KEY> keyType, TypeSerializer<W> windowSerializer, TypeInformation<T> stateType) { StateDescriptor<ListState<T>, List<T>> descriptor = new ListStateDescriptor<>(WINDOW_STATE_NAME, stateType); return new WindowReaderOperator<>( readerFunction, keyType, windowSerializer, WindowContents.listState(), descriptor); } public static <KEY, T, W extends Window, OUT> WindowReaderOperator<?, KEY, StreamRecord<T>, W, OUT> evictingWindow( WindowReaderFunction<StreamRecord<T>, OUT, KEY, W> readerFunction, TypeInformation<KEY> keyType, TypeSerializer<W> windowSerializer, TypeInformation<T> stateType, ExecutionConfig config) { @SuppressWarnings({"unchecked", "rawtypes"}) TypeSerializer<StreamRecord<T>> streamRecordSerializer = (TypeSerializer<StreamRecord<T>>) new StreamElementSerializer( stateType.createSerializer(config.getSerializerConfig())); StateDescriptor<ListState<StreamRecord<T>>, List<StreamRecord<T>>> descriptor = new ListStateDescriptor<>(WINDOW_STATE_NAME, streamRecordSerializer); return new WindowReaderOperator<>( readerFunction, keyType, windowSerializer, WindowContents.listState(), descriptor); } private WindowReaderOperator( WindowReaderFunction<IN, OUT, KEY, W> function, TypeInformation<KEY> keyType, TypeSerializer<W> namespaceSerializer, WindowContents<S, IN> contents, StateDescriptor<S, ?> descriptor) { super(function, keyType, namespaceSerializer); Preconditions.checkNotNull(contents, "WindowContents must not be null"); Preconditions.checkNotNull(descriptor, "The state descriptor must not be null"); this.contents = contents; this.descriptor = descriptor; } @Override public void open() throws Exception { super.open(); ctx = new Context(getKeyedStateBackend(), getInternalTimerService(WINDOW_TIMER_NAME)); } @Override public void processElement(KEY key, W namespace, Collector<OUT> out) throws Exception { ctx.window = namespace; S state = getKeyedStateBackend() .getPartitionedState(namespace, namespaceSerializer, descriptor); function.readWindow(key, ctx, contents.contents(state), out); } @Override public CloseableIterator<Tuple2<KEY, W>> getKeysAndNamespaces(SavepointRuntimeContext ctx) throws Exception { Stream<Tuple2<KEY, W>> keysAndWindows = getKeyedStateBackend().getKeysAndNamespaces(descriptor.getName()); return new IteratorWithRemove<>(keysAndWindows); } private
WindowReaderOperator
java
apache__camel
components/camel-docker/src/test/java/org/apache/camel/component/docker/it/FakeDockerCmdExecFactory.java
{ "start": 5571, "end": 14340 }
class ____ implements DockerCmdExecFactory { public static final String FAKE_VERSION = "Fake Camel Version 1.0"; public FakeDockerCmdExecFactory() { } @Override public VersionCmd.Exec createVersionCmdExec() { return new VersionCmd.Exec() { @Override public Version exec(VersionCmd versionCmd) { return new Version() { @Override public String getVersion() { return FAKE_VERSION; } }; } }; } @Override public AuthCmd.Exec createAuthCmdExec() { return null; } @Override public InfoCmd.Exec createInfoCmdExec() { return null; } @Override public PingCmd.Exec createPingCmdExec() { return null; } @Override public ExecCreateCmd.Exec createExecCmdExec() { return null; } @Override public PullImageCmd.Exec createPullImageCmdExec() { return null; } @Override public PushImageCmd.Exec createPushImageCmdExec() { return null; } @Override public SaveImageCmd.Exec createSaveImageCmdExec() { return null; } @Override public CreateImageCmd.Exec createCreateImageCmdExec() { return null; } @Override public LoadImageCmd.Exec createLoadImageCmdExec() { return null; } @Override public LoadImageAsyncCmd.Exec createLoadImageAsyncCmdExec() { return null; } @Override public SearchImagesCmd.Exec createSearchImagesCmdExec() { return null; } @Override public RemoveImageCmd.Exec createRemoveImageCmdExec() { return null; } @Override public ListImagesCmd.Exec createListImagesCmdExec() { return null; } @Override public InspectImageCmd.Exec createInspectImageCmdExec() { return null; } @Override public ListContainersCmd.Exec createListContainersCmdExec() { return null; } @Override public CreateContainerCmd.Exec createCreateContainerCmdExec() { return null; } @Override public StartContainerCmd.Exec createStartContainerCmdExec() { return null; } @Override public InspectContainerCmd.Exec createInspectContainerCmdExec() { return null; } @Override public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { return null; } @Override public WaitContainerCmd.Exec createWaitContainerCmdExec() { return null; } @Override public AttachContainerCmd.Exec createAttachContainerCmdExec() { return null; } @Override public ExecStartCmd.Exec createExecStartCmdExec() { return null; } @Override public InspectExecCmd.Exec createInspectExecCmdExec() { return null; } @Override public LogContainerCmd.Exec createLogContainerCmdExec() { return null; } @Override public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() { return null; } @Override public CopyArchiveFromContainerCmd.Exec createCopyArchiveFromContainerCmdExec() { return null; } @Override public CopyArchiveToContainerCmd.Exec createCopyArchiveToContainerCmdExec() { return null; } @Override public StopContainerCmd.Exec createStopContainerCmdExec() { return null; } @Override public ContainerDiffCmd.Exec createContainerDiffCmdExec() { return null; } @Override public KillContainerCmd.Exec createKillContainerCmdExec() { return null; } @Override public UpdateContainerCmd.Exec createUpdateContainerCmdExec() { return null; } @Override public RenameContainerCmd.Exec createRenameContainerCmdExec() { return null; } @Override public RestartContainerCmd.Exec createRestartContainerCmdExec() { return null; } @Override public CommitCmd.Exec createCommitCmdExec() { return null; } @Override public BuildImageCmd.Exec createBuildImageCmdExec() { return null; } @Override public TopContainerCmd.Exec createTopContainerCmdExec() { return null; } @Override public TagImageCmd.Exec createTagImageCmdExec() { return null; } @Override public PauseContainerCmd.Exec createPauseContainerCmdExec() { return null; } @Override public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { return null; } @Override public EventsCmd.Exec createEventsCmdExec() { return null; } @Override public StatsCmd.Exec createStatsCmdExec() { return null; } @Override public CreateVolumeCmd.Exec createCreateVolumeCmdExec() { return null; } @Override public InspectVolumeCmd.Exec createInspectVolumeCmdExec() { return null; } @Override public RemoveVolumeCmd.Exec createRemoveVolumeCmdExec() { return null; } @Override public ListVolumesCmd.Exec createListVolumesCmdExec() { return null; } @Override public ListNetworksCmd.Exec createListNetworksCmdExec() { return null; } @Override public InspectNetworkCmd.Exec createInspectNetworkCmdExec() { return null; } @Override public CreateNetworkCmd.Exec createCreateNetworkCmdExec() { return null; } @Override public RemoveNetworkCmd.Exec createRemoveNetworkCmdExec() { return null; } @Override public ConnectToNetworkCmd.Exec createConnectToNetworkCmdExec() { return null; } @Override public DisconnectFromNetworkCmd.Exec createDisconnectFromNetworkCmdExec() { return null; } @Override public InitializeSwarmCmd.Exec createInitializeSwarmCmdExec() { return null; } @Override public InspectSwarmCmd.Exec createInspectSwarmCmdExec() { return null; } @Override public JoinSwarmCmd.Exec createJoinSwarmCmdExec() { return null; } @Override public LeaveSwarmCmd.Exec createLeaveSwarmCmdExec() { return null; } @Override public UpdateSwarmCmd.Exec createUpdateSwarmCmdExec() { return null; } @Override public ListServicesCmd.Exec createListServicesCmdExec() { return null; } @Override public CreateServiceCmd.Exec createCreateServiceCmdExec() { return null; } @Override public InspectServiceCmd.Exec createInspectServiceCmdExec() { return null; } @Override public UpdateServiceCmd.Exec createUpdateServiceCmdExec() { return null; } @Override public RemoveServiceCmd.Exec createRemoveServiceCmdExec() { return null; } @Override public LogSwarmObjectCmd.Exec logSwarmObjectExec(String s) { return null; } @Override public ListSwarmNodesCmd.Exec listSwarmNodeCmdExec() { return null; } @Override public InspectSwarmNodeCmd.Exec inspectSwarmNodeCmdExec() { return null; } @Override public RemoveSwarmNodeCmd.Exec removeSwarmNodeCmdExec() { return null; } @Override public UpdateSwarmNodeCmd.Exec updateSwarmNodeCmdExec() { return null; } @Override public ListTasksCmd.Exec listTasksCmdExec() { return null; } @Override public void close() { // Noop } @Override public Exec pruneCmdExec() { return null; } @Override public SaveImagesCmd.Exec createSaveImagesCmdExec() { return null; } @Override public ListSecretsCmd.Exec createListSecretsCmdExec() { return null; } @Override public CreateSecretCmd.Exec createCreateSecretCmdExec() { return null; } @Override public RemoveSecretCmd.Exec createRemoveSecretCmdExec() { return null; } @Override public ListConfigsCmd.Exec createListConfigsCmdExec() { return null; } @Override public InspectConfigCmd.Exec createInspectConfigCmdExec() { return null; } @Override public CreateConfigCmd.Exec createCreateConfigCmdExec() { return null; } @Override public RemoveConfigCmd.Exec createRemoveConfigCmdExec() { return null; } @Override public ResizeContainerCmd.Exec createResizeContainerCmdExec() { return null; } @Override public ResizeExecCmd.Exec createResizeExecCmdExec() { return null; } }
FakeDockerCmdExecFactory
java
apache__kafka
metadata/src/test/java/org/apache/kafka/metadata/storage/ScramParserTest.java
{ "start": 1610, "end": 11331 }
class ____ { static final byte[] TEST_SALT = new byte[] { 49, 108, 118, 52, 112, 100, 110, 119, 52, 102, 119, 113, 55, 110, 111, 116, 99, 120, 109, 48, 121, 121, 49, 107, 55, 113 }; static final byte[] TEST_SALTED_PASSWORD = new byte[] { -103, 61, 50, -55, 69, 49, -98, 82, 90, 11, -33, 71, 94, 4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt.empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt.empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt.empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt.of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt.empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt.of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), OptionalInt.empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt.of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), OptionalInt.empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), OptionalInt.empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } }
ScramParserTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/yearmonth/YearMonthAssert_isBetween_with_String_parameters_Test.java
{ "start": 1029, "end": 2173 }
class ____ extends YearMonthAssertBaseTest { private YearMonth before = now.minusMonths(1); private YearMonth after = now.plusMonths(1); @Override protected YearMonthAssert invoke_api_method() { return assertions.isBetween(before.toString(), after.toString()); } @Override protected void verify_internal_effects() { verify(comparables).assertIsBetween(getInfo(assertions), getActual(assertions), before, after, true, true); } @Test void should_throw_a_DateTimeParseException_if_start_String_parameter_cannot_be_converted() { // GIVEN String abc = "abc"; // WHEN Throwable thrown = catchThrowable(() -> assertions.isBetween(abc, after.toString())); // THEN then(thrown).isInstanceOf(DateTimeParseException.class); } @Test void should_throw_a_DateTimeParseException_if_end_String_parameter_cannot_be_converted() { // GIVEN String abc = "abc"; // WHEN Throwable thrown = catchThrowable(() -> assertions.isBetween(before.toString(), abc)); // THEN then(thrown).isInstanceOf(DateTimeParseException.class); } }
YearMonthAssert_isBetween_with_String_parameters_Test
java
elastic__elasticsearch
plugins/discovery-gce/src/main/java/org/elasticsearch/plugin/discovery/gce/GceDiscoveryPlugin.java
{ "start": 1596, "end": 4108 }
class ____ extends Plugin implements DiscoveryPlugin, Closeable { /** Determines whether settings those reroutes GCE call should be allowed (for testing purposes only). */ private static final boolean ALLOW_REROUTE_GCE_SETTINGS = Booleans.parseBoolean( System.getProperty("es.allow_reroute_gce_settings", "false") ); public static final String GCE = "gce"; protected final Settings settings; private static final Logger logger = LogManager.getLogger(GceDiscoveryPlugin.class); // stashed when created in order to properly close private final SetOnce<GceInstancesService> gceInstancesService = new SetOnce<>(); public GceDiscoveryPlugin(Settings settings) { this.settings = settings; logger.trace("starting gce discovery plugin..."); } // overrideable for tests protected GceInstancesService createGceInstancesService() { return new GceInstancesServiceImpl(settings); } @Override public Map<String, Supplier<SeedHostsProvider>> getSeedHostProviders(TransportService transportService, NetworkService networkService) { return Collections.singletonMap(GCE, () -> { gceInstancesService.set(createGceInstancesService()); return new GceSeedHostsProvider(settings, gceInstancesService.get(), transportService, networkService); }); } @Override public NetworkService.CustomNameResolver getCustomNameResolver(Settings settingsToUse) { logger.debug("Register _gce_, _gce:xxx network names"); return new GceNameResolver(new GceMetadataService(settingsToUse)); } @Override public List<Setting<?>> getSettings() { List<Setting<?>> settingList = new ArrayList<>( Arrays.asList( // Register GCE settings GceInstancesService.PROJECT_SETTING, GceInstancesService.ZONE_SETTING, GceSeedHostsProvider.TAGS_SETTING, GceInstancesService.REFRESH_SETTING, GceInstancesService.RETRY_SETTING, GceInstancesService.MAX_WAIT_SETTING ) ); if (ALLOW_REROUTE_GCE_SETTINGS) { settingList.add(GceMetadataService.GCE_HOST); settingList.add(GceInstancesServiceImpl.GCE_ROOT_URL); } return Collections.unmodifiableList(settingList); } @Override public void close() throws IOException { IOUtils.close(gceInstancesService.get()); } }
GceDiscoveryPlugin
java
alibaba__nacos
naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandlerTest.java
{ "start": 1969, "end": 3745 }
class ____ { @InjectMocks private ServiceQueryRequestHandler serviceQueryRequestHandler; @Mock private ServiceStorage serviceStorage; @Mock private NamingMetadataManager metadataManager; @Mock private ConfigurableApplicationContext applicationContext; @Mock private SelectorManager selectorManager; @BeforeEach void setUp() { ApplicationUtils.injectContext(applicationContext); Mockito.when(applicationContext.getBean(SelectorManager.class)).thenReturn(selectorManager); } @Test void testHandle() throws NacosException { Instance instance = new Instance(); instance.setIp("1.1.1.1"); List<Instance> instances = Arrays.asList(instance); ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setGroupName("A"); serviceInfo.setGroupName("B"); serviceInfo.setName("C"); serviceInfo.setHosts(instances); Mockito.when(serviceStorage.getData(Mockito.any())).thenReturn(serviceInfo); ServiceMetadata serviceMetadata = new ServiceMetadata(); Mockito.when(metadataManager.getServiceMetadata(Mockito.any())).thenReturn(Optional.of(serviceMetadata)); ServiceQueryRequest serviceQueryRequest = new ServiceQueryRequest(); serviceQueryRequest.setNamespace("A"); serviceQueryRequest.setGroupName("B"); serviceQueryRequest.setServiceName("C"); serviceQueryRequest.setHealthyOnly(false); QueryServiceResponse queryServiceResponse = serviceQueryRequestHandler.handle(serviceQueryRequest, new RequestMeta()); assertEquals("C", queryServiceResponse.getServiceInfo().getName()); } }
ServiceQueryRequestHandlerTest
java
elastic__elasticsearch
modules/repository-azure/src/main/java/org/elasticsearch/repositories/azure/AzureStorageService.java
{ "start": 1918, "end": 9727 }
class ____ { private static final Logger logger = LogManager.getLogger(AzureStorageService.class); public static final ByteSizeValue MIN_CHUNK_SIZE = ByteSizeValue.ofBytes(1); /** * The maximum size of a BlockBlob block. * See https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-block-blobs--append-blobs--and-page-blobs */ public static final ByteSizeValue MAX_BLOCK_SIZE = ByteSizeValue.of(100, ByteSizeUnit.MB); /** * The maximum number of blocks. * See https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-block-blobs--append-blobs--and-page-blobs */ public static final long MAX_BLOCK_NUMBER = 50000; /** * Default block size for multi-block uploads. The Azure repository will use the Put block and Put block list APIs to split the * stream into several part, each of block_size length, and will upload each part in its own request. */ private static final ByteSizeValue DEFAULT_BLOCK_SIZE = ByteSizeValue.ofBytes( Math.max( ByteSizeUnit.MB.toBytes(5), // minimum value Math.min(MAX_BLOCK_SIZE.getBytes(), JvmInfo.jvmInfo().getMem().getHeapMax().getBytes() / 20) ) ); /** * The maximum size of a Block Blob. * See https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-block-blobs--append-blobs--and-page-blobs */ public static final long MAX_BLOB_SIZE = MAX_BLOCK_NUMBER * DEFAULT_BLOCK_SIZE.getBytes(); /** * Maximum allowed blob size in Azure blob store. */ public static final ByteSizeValue MAX_CHUNK_SIZE = ByteSizeValue.ofBytes(MAX_BLOB_SIZE); private static final long DEFAULT_UPLOAD_BLOCK_SIZE = DEFAULT_BLOCK_SIZE.getBytes(); private final int multipartUploadMaxConcurrency; private final AzureClientProvider azureClientProvider; private final ClientLogger clientLogger = new ClientLogger(AzureStorageService.class); private final AzureStorageClientsManager clientsManager; private final boolean stateless; public AzureStorageService( Settings settings, AzureClientProvider azureClientProvider, ClusterService clusterService, ProjectResolver projectResolver ) { this.clientsManager = new AzureStorageClientsManager(settings, projectResolver.supportsMultipleProjects()); this.azureClientProvider = azureClientProvider; this.stateless = DiscoveryNode.isStateless(settings); this.multipartUploadMaxConcurrency = azureClientProvider.getMultipartUploadMaxConcurrency(); if (projectResolver.supportsMultipleProjects()) { clusterService.addHighPriorityApplier(this.clientsManager); } } public AzureBlobServiceClient client( @Nullable ProjectId projectId, String clientName, LocationMode locationMode, OperationPurpose purpose ) { return client(projectId, clientName, locationMode, purpose, null); } public AzureBlobServiceClient client( @Nullable ProjectId projectId, String clientName, LocationMode locationMode, OperationPurpose purpose, AzureClientProvider.RequestMetricsHandler requestMetricsHandler ) { return clientsManager.client(projectId, clientName, locationMode, purpose, requestMetricsHandler); } private AzureBlobServiceClient buildClient( LocationMode locationMode, OperationPurpose purpose, AzureClientProvider.RequestMetricsHandler requestMetricsHandler, AzureStorageSettings azureStorageSettings ) { RequestRetryOptions retryOptions = getRetryOptions(locationMode, azureStorageSettings); ProxyOptions proxyOptions = getProxyOptions(azureStorageSettings); return azureClientProvider.createClient( azureStorageSettings, locationMode, retryOptions, proxyOptions, requestMetricsHandler, purpose ); } private static ProxyOptions getProxyOptions(AzureStorageSettings settings) { Proxy proxy = settings.getProxy(); if (proxy == null) { return null; } return switch (proxy.type()) { case HTTP -> new ProxyOptions(ProxyOptions.Type.HTTP, (InetSocketAddress) proxy.address()); case SOCKS -> new ProxyOptions(ProxyOptions.Type.SOCKS5, (InetSocketAddress) proxy.address()); default -> null; }; } // non-static, package private for testing long getUploadBlockSize() { return DEFAULT_UPLOAD_BLOCK_SIZE; } int getMaxReadRetries(@Nullable ProjectId projectId, String clientName) { AzureStorageSettings azureStorageSettings = clientsManager.getClientSettings(projectId, clientName); return azureStorageSettings.getMaxRetries(); } boolean isStateless() { return stateless; } // non-static, package private for testing RequestRetryOptions getRetryOptions(LocationMode locationMode, AzureStorageSettings azureStorageSettings) { AzureStorageSettings.StorageEndpoint endpoint = azureStorageSettings.getStorageEndpoint(); String primaryUri = endpoint.primaryURI(); String secondaryUri = endpoint.secondaryURI(); if (locationMode == LocationMode.PRIMARY_THEN_SECONDARY && secondaryUri == null) { throw new IllegalArgumentException("Unable to use " + locationMode + " location mode without a secondary location URI"); } final String secondaryHost = switch (locationMode) { case PRIMARY_ONLY, SECONDARY_ONLY -> null; case PRIMARY_THEN_SECONDARY -> secondaryUri; case SECONDARY_THEN_PRIMARY -> primaryUri; }; // The request retry policy uses seconds as the default time unit, since // it's possible to configure a timeout < 1s we should ceil that value // as RequestRetryOptions expects a value >= 1. // See https://github.com/Azure/azure-sdk-for-java/issues/17590 for a proposal // to fix this issue. TimeValue configuredTimeout = azureStorageSettings.getTimeout(); int timeout = configuredTimeout.duration() == -1 ? Integer.MAX_VALUE : Math.max(1, Math.toIntExact(configuredTimeout.getSeconds())); return new RequestRetryOptions( RetryPolicyType.EXPONENTIAL, azureStorageSettings.getMaxRetries(), timeout, null, null, secondaryHost ); } /** * Updates settings for building cluster level clients. Any client cache is cleared. Future * client requests will use the new refreshed settings. * * @param clientsSettings the settings for new clients */ public void refreshClusterClientSettings(Map<String, AzureStorageSettings> clientsSettings) { clientsManager.refreshClusterClientSettings(clientsSettings); } /** * For Azure repositories, we report the different kinds of credentials in use in the telemetry. */ public Set<String> getExtraUsageFeatures(@Nullable ProjectId projectId, String clientName) { try { return clientsManager.getClientSettings(projectId, clientName).credentialsUsageFeatures(); } catch (Exception e) { return Set.of(); } } public int getMultipartUploadMaxConcurrency() { return multipartUploadMaxConcurrency; } // Package private for testing Map<String, AzureStorageSettings> getStorageSettings() { return clientsManager.clusterStorageSettings; } // Package private for testing AzureStorageClientsManager getClientsManager() { return clientsManager; }
AzureStorageService
java
quarkusio__quarkus
integration-tests/elytron-resteasy/src/test/java/io/quarkus/it/resteasy/elytron/HttpPolicyAuthFailedExMapperTest.java
{ "start": 498, "end": 921 }
class ____ { @Test public void testAuthFailedExceptionMapper() { RestAssured .given() .auth().basic("unknown-user", "unknown-pwd") .contentType(ContentType.TEXT) .get("/") .then() .statusCode(401) .body(Matchers.equalTo(EXPECTED_RESPONSE)); } public static
HttpPolicyAuthFailedExMapperTest
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/completable/CompletableTimer.java
{ "start": 1587, "end": 2344 }
class ____ extends AtomicReference<Disposable> implements Disposable, Runnable { private static final long serialVersionUID = 3167244060586201109L; final CompletableObserver downstream; TimerDisposable(final CompletableObserver downstream) { this.downstream = downstream; } @Override public void run() { downstream.onComplete(); } @Override public void dispose() { DisposableHelper.dispose(this); } @Override public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } void setFuture(Disposable d) { DisposableHelper.replace(this, d); } } }
TimerDisposable
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/execution/librarycache/LibraryCacheManager.java
{ "start": 2979, "end": 3069 }
class ____. * * @param requiredJarFiles requiredJarFiles the user code
paths
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/EmbeddableWithJavaTypeTest.java
{ "start": 4632, "end": 4758 }
class ____ { @Id @Column(name = "id") long id; @Embedded EmbedNative embedNative; } public static
EntityEmbedNative
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/engine/Engine.java
{ "start": 32612, "end": 36540 }
class ____ { private final Operation.TYPE operationType; private final Result.Type resultType; private final long version; private final long term; private final long seqNo; private final Exception failure; private final SetOnce<Boolean> freeze = new SetOnce<>(); private final Mapping requiredMappingUpdate; private final String id; private Translog.Location translogLocation; private long took; protected Result(Operation.TYPE operationType, Exception failure, long version, long term, long seqNo, String id) { this.operationType = operationType; this.failure = Objects.requireNonNull(failure); this.version = version; this.term = term; this.seqNo = seqNo; this.requiredMappingUpdate = null; this.resultType = Type.FAILURE; this.id = id; } protected Result(Operation.TYPE operationType, long version, long term, long seqNo, String id) { this.operationType = operationType; this.version = version; this.seqNo = seqNo; this.term = term; this.failure = null; this.requiredMappingUpdate = null; this.resultType = Type.SUCCESS; this.id = id; } protected Result(Operation.TYPE operationType, Mapping requiredMappingUpdate, String id) { this.operationType = operationType; this.version = Versions.NOT_FOUND; this.seqNo = UNASSIGNED_SEQ_NO; this.term = UNASSIGNED_PRIMARY_TERM; this.failure = null; this.requiredMappingUpdate = requiredMappingUpdate; this.resultType = Type.MAPPING_UPDATE_REQUIRED; this.id = id; } /** whether the operation was successful, has failed or was aborted due to a mapping update */ public Type getResultType() { return resultType; } /** get the updated document version */ public long getVersion() { return version; } /** * Get the sequence number on the primary. * * @return the sequence number */ public long getSeqNo() { return seqNo; } public long getTerm() { return term; } /** * If the operation was aborted due to missing mappings, this method will return the mappings * that are required to complete the operation. */ public Mapping getRequiredMappingUpdate() { return requiredMappingUpdate; } /** get the translog location after executing the operation */ public Translog.Location getTranslogLocation() { return translogLocation; } /** get document failure while executing the operation {@code null} in case of no failure */ public Exception getFailure() { return failure; } /** get total time in nanoseconds */ public long getTook() { return took; } public Operation.TYPE getOperationType() { return operationType; } public String getId() { return id; } void setTranslogLocation(Translog.Location translogLocation) { if (freeze.get() == null) { this.translogLocation = translogLocation; } else { throw new IllegalStateException("result is already frozen"); } } void setTook(long took) { if (freeze.get() == null) { this.took = took; } else { throw new IllegalStateException("result is already frozen"); } } void freeze() { freeze.set(true); } public
Result
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/SequenceFile.java
{ "start": 33468, "end": 33621 }
class ____ extends Options.LongOption implements Option { BlockSizeOption(long value) { super(value); } } static
BlockSizeOption
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/StateEntry.java
{ "start": 1044, "end": 1601 }
interface ____<K, N, S> { /** Returns the key of this entry. */ K getKey(); /** Returns the namespace of this entry. */ N getNamespace(); /** Returns the state of this entry. */ S getState(); default StateEntry<K, N, S> filterOrTransform(StateSnapshotTransformer<S> transformer) { S newState = transformer.filterOrTransform(getState()); if (newState != null) { return new SimpleStateEntry<>(getKey(), getNamespace(), newState); } else { return null; } }
StateEntry
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/annotation/CaptorAnnotationTest.java
{ "start": 1039, "end": 1948 }
interface ____ { void testMe(String simple, List<List<String>> genericList); } @Test public void testNormalUsage() { MockitoAnnotations.openMocks(this); // check if assigned correctly assertNotNull(finalCaptor); assertNotNull(genericsCaptor); assertNotNull(nonGenericCaptorIsAllowed); assertNull(notAMock); // use captors in the field to be sure they are cool String argForFinalCaptor = "Hello"; ArrayList<List<String>> argForGenericsCaptor = new ArrayList<List<String>>(); mockInterface.testMe(argForFinalCaptor, argForGenericsCaptor); Mockito.verify(mockInterface).testMe(finalCaptor.capture(), genericsCaptor.capture()); assertEquals(argForFinalCaptor, finalCaptor.getValue()); assertEquals(argForGenericsCaptor, genericsCaptor.getValue()); } public static
MockInterface
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/MonoSingle.java
{ "start": 2097, "end": 4438 }
class ____<T> extends Operators.MonoInnerProducerBase<T> implements InnerConsumer<T> { final @Nullable T defaultValue; final boolean completeOnEmpty; @SuppressWarnings("NotNullFieldNotInitialized") // s is initialized in onSubscribe Subscription s; int count; boolean done; @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.TERMINATED) return done; if (key == Attr.PARENT) return s; if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } @Override public Context currentContext() { return actual().currentContext(); } SingleSubscriber(CoreSubscriber<? super T> actual, @Nullable T defaultValue, boolean completeOnEmpty) { super(actual); this.defaultValue = defaultValue; this.completeOnEmpty = completeOnEmpty; } @Override public void doOnRequest(long n) { s.request(Long.MAX_VALUE); } @Override public void doOnCancel() { s.cancel(); } @Override public void onSubscribe(Subscription s) { if (Operators.validate(this.s, s)) { this.s = s; actual().onSubscribe(this); } } @Override public void onNext(T t) { if (isCancelled()) { //this helps differentiating a duplicate malformed signal "done" from a count > 1 "done" discard(t); return; } if (done) { Operators.onNextDropped(t, actual().currentContext()); return; } if (++count > 1) { discard(t); //mark as both cancelled and done cancel(); onError(new IndexOutOfBoundsException("Source emitted more than one item")); } else { setValue(t); } } @Override public void onError(Throwable t) { if (done) { Operators.onErrorDropped(t, actual().currentContext()); return; } done = true; discardTheValue(); actual().onError(t); } @Override public void onComplete() { if (done) { return; } done = true; int c = count; if (c == 0) { if (completeOnEmpty) { actual().onComplete(); return; } T t = defaultValue; if (t != null) { complete(t); } else { actual().onError(Operators.onOperatorError(this, new NoSuchElementException("Source was empty"), actual().currentContext())); } } else if (c == 1) { complete(); } } } }
SingleSubscriber
java
apache__camel
components/camel-opentelemetry/src/test/java/org/apache/camel/opentelemetry/SpanProcessorsTest.java
{ "start": 1105, "end": 4406 }
class ____ extends CamelOpenTelemetryTestSupport { private static final SpanTestData[] TEST_DATA = { new SpanTestData().setLabel("seda:b server").setUri("seda://b").setOperation("b") .setParentId(1).addLogMessage("routing at b") .addTag("b-tag", "request-header-value"), new SpanTestData().setLabel("seda:b server").setUri("seda://b").setOperation("b") .setKind(SpanKind.CLIENT) .setParentId(4), new SpanTestData().setLabel("seda:c server").setUri("seda://c").setOperation("c") .setParentId(3).addLogMessage("Exchange[ExchangePattern: InOut, BodyType: String, Body: Hello]"), new SpanTestData().setLabel("seda:c server").setUri("seda://c").setOperation("c") .setKind(SpanKind.CLIENT) .setParentId(4), new SpanTestData().setLabel("seda:a server").setUri("seda://a").setOperation("a") .setParentId(5).addLogMessage("routing at a").addLogMessage("End of routing"), new SpanTestData().setLabel("seda:a server").setUri("seda://a").setOperation("a") .setKind(SpanKind.CLIENT) .setParentId(6), new SpanTestData().setLabel("direct:start server").setUri("direct://start").setOperation("start") .setParentId(7), new SpanTestData().setLabel("direct:start server").setUri("direct://start").setOperation("start") .setKind(SpanKind.CLIENT) }; SpanProcessorsTest() { super(TEST_DATA); } @Test void testRoute() { Exchange result = template.request("direct:start", exchange -> { exchange.getIn().setBody("Hello"); exchange.getIn().setHeader("request-header", context.resolveLanguage("simple").createExpression("request-header-value")); }); verify(); assertEquals("request-header-value", result.getMessage().getHeader("baggage-header", String.class)); } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").to("seda:a").routeId("start"); from("seda:a").routeId("a") .log("routing at ${routeId}") .process(new SetCorrelationContextProcessor("a-baggage", simple("${header.request-header}"))) .to("seda:b") .delay(2000) .to("seda:c") .log("End of routing"); from("seda:b").routeId("b") .log("routing at ${routeId}") .process(new AttributeProcessor("b-tag", simple("${header.request-header}"))) .delay(simple("${random(1000,2000)}")); from("seda:c").routeId("c") .to("log:test") .process(new GetCorrelationContextProcessor("a-baggage", "baggage-header")) .delay(simple("${random(0,100)}")); } }; } }
SpanProcessorsTest
java
apache__camel
components/camel-platform-http-vertx/src/main/java/org/apache/camel/component/platform/http/vertx/VertxPlatformHttpConsumer.java
{ "start": 3145, "end": 16647 }
class ____ extends DefaultConsumer implements PlatformHttpConsumer, Suspendable, SuspendableService { private static final Logger LOGGER = LoggerFactory.getLogger(VertxPlatformHttpConsumer.class); private static final Pattern PATH_PARAMETER_PATTERN = Pattern.compile("\\{([^/}]+)\\}"); private final List<Handler<RoutingContext>> handlers; private final String fileNameExtWhitelist; private final boolean muteExceptions; private final boolean handleWriteResponseError; private Set<Method> methods; private String path; private Route route; private VertxPlatformHttpRouter router; private HttpRequestBodyHandler httpRequestBodyHandler; private CookieConfiguration cookieConfiguration; private final String routerName; public VertxPlatformHttpConsumer(PlatformHttpEndpoint endpoint, Processor processor, List<Handler<RoutingContext>> handlers, String routerName) { super(endpoint, processor); this.handlers = handlers; this.fileNameExtWhitelist = endpoint.getFileNameExtWhitelist() == null ? null : endpoint.getFileNameExtWhitelist().toLowerCase(Locale.US); this.muteExceptions = endpoint.isMuteException(); this.handleWriteResponseError = endpoint.isHandleWriteResponseError(); this.routerName = routerName; } @Override public PlatformHttpEndpoint getEndpoint() { return (PlatformHttpEndpoint) super.getEndpoint(); } @Override protected void doInit() throws Exception { super.doInit(); methods = Method.parseList(getEndpoint().getHttpMethodRestrict()); path = configureEndpointPath(getEndpoint()); router = VertxPlatformHttpRouter.lookup(getEndpoint().getCamelContext(), routerName); if (!getEndpoint().isHttpProxy() && getEndpoint().isUseStreaming()) { httpRequestBodyHandler = new StreamingHttpRequestBodyHandler(router.bodyHandler()); } else if (!getEndpoint().isHttpProxy() && !getEndpoint().isUseBodyHandler()) { httpRequestBodyHandler = new NoOpHttpRequestBodyHandler(router.bodyHandler()); } else { httpRequestBodyHandler = new DefaultHttpRequestBodyHandler(router.bodyHandler()); } if (getEndpoint().isUseCookieHandler()) { cookieConfiguration = getEndpoint().getCookieConfiguration(); } } @Override protected void doStart() throws Exception { super.doStart(); final Route newRoute = router.route(path); if (getEndpoint().getRequestTimeout() > 0) { newRoute.handler(TimeoutHandler.create(getEndpoint().getRequestTimeout())); } if (getEndpoint().getCamelContext().getRestConfiguration().isEnableCORS() && getEndpoint().getConsumes() != null) { ((RouteImpl) newRoute).setEmptyBodyPermittedWithConsumes(true); } if (!methods.equals(Method.getAll())) { methods.forEach(m -> newRoute.method(HttpMethod.valueOf(m.name()))); } if (getEndpoint().getConsumes() != null) { //comma separated contentTypes has to be registered one by one for (String c : getEndpoint().getConsumes().split(",")) { newRoute.consumes(c); } } if (getEndpoint().getProduces() != null) { //comma separated contentTypes has to be registered one by one for (String p : getEndpoint().getProduces().split(",")) { newRoute.produces(p); } } httpRequestBodyHandler.configureRoute(newRoute); for (Handler<RoutingContext> handler : handlers) { newRoute.handler(handler); } newRoute.handler(this::handleRequest); this.route = newRoute; } @Override protected void doStop() throws Exception { if (route != null) { route.remove(); route = null; } super.doStop(); } private String configureEndpointPath(PlatformHttpEndpoint endpoint) { String path = endpoint.getPath(); if (endpoint.isMatchOnUriPrefix() && !path.endsWith("*")) { path += "*"; } // Transform from the Camel path param syntax /path/{key} to vert.x web's /path/:key return PATH_PARAMETER_PATTERN.matcher(path).replaceAll(":$1"); } protected void handleRequest(RoutingContext ctx) { if (isSuspended()) { handleSuspend(ctx); return; } final Vertx vertx = ctx.vertx(); final Exchange exchange = createExchange(false); exchange.setPattern(ExchangePattern.InOut); // // We do not know if any of the processing logic of the route is synchronous or not so we // need to process the request on a thread on the Vert.x worker pool. // // As example, assuming the platform-http component is configured as the transport provider // for the rest dsl, then the following code may result in a blocking operation that could // block Vert.x event-loop for too long if the target service takes long to respond, as // example in case the service is a knative service scaled to zero that could take some time // to become available: // // rest("/results") // .get("/{id}") // .route() // .removeHeaders("*", "CamelHttpPath") // .to("rest:get:?bridgeEndpoint=true"); // // Note: any logic that needs to interrogate HTTP headers not provided by RoutingContext.parsedHeaders, should // be done inside of the following onComplete block, to ensure that the HTTP request is fully processed. processHttpRequest(exchange, ctx).onComplete(result -> { if (result.failed()) { handleFailure(exchange, ctx, result.cause()); return; } if (getEndpoint().isHttpProxy()) { handleProxy(ctx, exchange); } if (getEndpoint().isUseBodyHandler()) { populateMultiFormData(ctx, exchange.getIn(), getEndpoint().getHeaderFilterStrategy()); } vertx.executeBlocking(() -> processExchange(exchange), false).onComplete(processExchangeResult -> { if (processExchangeResult.succeeded()) { writeResponse(ctx, exchange, getEndpoint().getHeaderFilterStrategy(), muteExceptions) .onComplete(writeResponseResult -> { if (writeResponseResult.succeeded()) { handleExchangeComplete(exchange); } else { handleFailure(exchange, ctx, writeResponseResult.cause()); } }); } else { handleFailure(exchange, ctx, processExchangeResult.cause()); } }); }); } private void handleExchangeComplete(Exchange exchange) { doneUoW(exchange); releaseExchange(exchange, false); } private void handleFailure(Exchange exchange, RoutingContext ctx, Throwable failure) { getExceptionHandler().handleException( "Failed handling platform-http endpoint " + getEndpoint().getPath(), failure); ctx.fail(failure); if (handleWriteResponseError && failure != null) { Exception existing = exchange.getException(); if (existing != null) { failure.addSuppressed(existing); } exchange.setProperty(Exchange.EXCEPTION_CAUGHT, failure); exchange.setException(failure); } handleExchangeComplete(exchange); } private Object processExchange(Exchange exchange) throws Exception { createUoW(exchange); getProcessor().process(exchange); return null; } private static void handleSuspend(RoutingContext ctx) { ctx.response().setStatusCode(503); ctx.end(); } private static void handleProxy(RoutingContext ctx, Exchange exchange) { exchange.getExchangeExtension().setStreamCacheDisabled(true); final MultiMap httpHeaders = ctx.request().headers(); exchange.getMessage().setHeader(Exchange.HTTP_HOST, httpHeaders.get("Host")); exchange.getMessage().removeHeader("Proxy-Connection"); } protected Future<Void> processHttpRequest(Exchange exchange, RoutingContext ctx) { // reuse existing http message if pooled Message in = exchange.getIn(); if (in instanceof HttpMessage hm) { hm.init(exchange, ctx.request(), ctx.response()); } else { in = new HttpMessage(exchange, ctx.request(), ctx.response()); exchange.setMessage(in); } final String charset = ctx.parsedHeaders().contentType().parameter("charset"); if (charset != null) { exchange.setProperty(ExchangePropertyKey.CHARSET_NAME, charset); in.setHeader(Exchange.HTTP_CHARACTER_ENCODING, charset); } User user = ctx.user(); if (user != null) { in.setHeader(VertxPlatformHttpConstants.AUTHENTICATED_USER, user); } if (getEndpoint().isUseCookieHandler()) { exchange.setProperty(Exchange.COOKIE_HANDLER, new VertxCookieHandler(ctx)); } return populateCamelMessage(ctx, exchange, in); } protected Future<Void> populateCamelMessage(RoutingContext ctx, Exchange exchange, Message message) { final HeaderFilterStrategy headerFilterStrategy = getEndpoint().getHeaderFilterStrategy(); populateCamelHeaders(ctx, message.getHeaders(), exchange, headerFilterStrategy); return httpRequestBodyHandler.handle(ctx, message); } private void populateMultiFormData( RoutingContext ctx, Message message, HeaderFilterStrategy headerFilterStrategy) { final boolean isMultipartFormData = isMultiPartFormData(ctx); if (isFormUrlEncoded(ctx) || isMultipartFormData) { final MultiMap formData = ctx.request().formAttributes(); final Map<String, Object> body = new HashMap<>(); for (String key : formData.names()) { for (String value : formData.getAll(key)) { if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(key, value, message.getExchange())) { appendEntry(message.getHeaders(), key, value); if (getEndpoint().isPopulateBodyWithForm()) { appendEntry(body, key, value); } } } } if (!body.isEmpty()) { message.setBody(body); } if (isMultipartFormData) { populateAttachments(ctx.fileUploads(), message); } } } protected void populateAttachments(List<FileUpload> uploads, Message message) { message.setHeader(Exchange.ATTACHMENTS_SIZE, uploads.size()); for (FileUpload upload : uploads) { final String name = upload.name(); final String fileName = upload.fileName(); LOGGER.trace("HTTP attachment {} = {}", name, fileName); // is the file name accepted boolean accepted = true; if (fileNameExtWhitelist != null) { String ext = FileUtil.onlyExt(fileName); if (ext != null) { ext = ext.toLowerCase(Locale.US); if (!fileNameExtWhitelist.equals("*") && !fileNameExtWhitelist.contains(ext)) { accepted = false; } } } if (accepted) { final File localFile = new File(upload.uploadedFileName()); final AttachmentMessage attachmentMessage = message.getExchange().getMessage(AttachmentMessage.class); attachmentMessage.addAttachment(name, new DataHandler(new CamelFileDataSource(localFile, fileName))); // populate body in case there is only one attachment if (uploads.size() == 1) { message.setHeader(Exchange.FILE_PATH, localFile.getAbsolutePath()); message.setHeader(Exchange.FILE_LENGTH, upload.size()); message.setHeader(Exchange.FILE_NAME, upload.fileName()); String ct = MimeTypeHelper.probeMimeType(upload.fileName()); if (ct == null) { ct = upload.contentType(); } if (ct != null) { message.setHeader(Exchange.FILE_CONTENT_TYPE, ct); } message.setBody(localFile); } } else { LOGGER.debug( "Cannot add file as attachment: {} because the file is not accepted according to fileNameExtWhitelist: {}", fileName, fileNameExtWhitelist); } } }
VertxPlatformHttpConsumer
java
resilience4j__resilience4j
resilience4j-spring-boot2/src/test/java/io/github/resilience4j/ratelimiter/autoconfigure/RateLimiterConfigurationOnMissingBeanTest.java
{ "start": 1813, "end": 3006 }
class ____ { @Autowired public ConfigWithOverrides configWithOverrides; @Autowired private RateLimiterRegistry rateLimiterRegistry; @Autowired private RateLimiterAspect rateLimiterAspect; @Autowired private EventConsumerRegistry<RateLimiterEvent> rateLimiterEventsConsumerRegistry; @Test public void testAllBeansFromCircuitBreakerConfigurationHasOnMissingBean() throws NoSuchMethodException { final Class<RateLimiterConfiguration> originalClass = RateLimiterConfiguration.class; final Class<RateLimiterConfigurationOnMissingBean> onMissingBeanClass = RateLimiterConfigurationOnMissingBean.class; TestUtils.assertAnnotations(originalClass, onMissingBeanClass); } @Test public void testAllCircuitBreakerConfigurationBeansOverridden() { assertEquals(rateLimiterRegistry, configWithOverrides.rateLimiterRegistry); assertEquals(rateLimiterAspect, configWithOverrides.rateLimiterAspect); assertEquals(rateLimiterEventsConsumerRegistry, configWithOverrides.rateLimiterEventsConsumerRegistry); } @Configuration public static
RateLimiterConfigurationOnMissingBeanTest
java
elastic__elasticsearch
test/fixtures/gcs-fixture/src/test/java/fixture/gcs/MultipartUploadTests.java
{ "start": 963, "end": 4338 }
class ____ extends ESTestCase { // produces content that does not contain boundary static String randomPartContent(int len, String boundary) { assert len > 0 && boundary.isEmpty() == false; var content = randomAlphanumericOfLength(len); var replacement = boundary.getBytes(UTF_8); replacement[0]++; // change single char to make it different from original return content.replace(boundary, Arrays.toString(replacement)); } public void testGenericMultipart() throws IOException { var boundary = randomAlphanumericOfLength(between(1, 70)); var part1 = "plain text\nwith line break"; var part2 = ""; var part3 = randomPartContent(between(1, 1024), boundary); var strInput = """ --$boundary\r \r \r $part1\r --$boundary\r X-Header: x-man\r \r $part2\r --$boundary\r Content-Type: application/octet-stream\r \r $part3\r --$boundary--""".replace("$boundary", boundary).replace("$part1", part1).replace("$part2", part2).replace("$part3", part3); var reader = new MultipartUpload.MultipartContentReader(boundary, new ByteArrayStreamInput(strInput.getBytes())); assertEquals(part1, reader.next().utf8ToString()); assertEquals(part2, reader.next().utf8ToString()); assertEquals(part3, reader.next().utf8ToString()); assertFalse(reader.hasNext()); } public void testReadUntilDelimiter() throws IOException { for (int run = 0; run < 100; run++) { var delimitedContent = DelimitedContent.randomContent(); var inputStream = delimitedContent.toBytesReference().streamInput(); var readBytes = MultipartUpload.readUntilDelimiter(inputStream, delimitedContent.delimiter); assertThat(readBytes, equalBytes(new BytesArray(delimitedContent.before))); var readRemaining = inputStream.readAllBytes(); assertArrayEquals(delimitedContent.after, readRemaining); } } public void testSkipUntilDelimiter() throws IOException { for (int run = 0; run < 100; run++) { var delimitedContent = DelimitedContent.randomContent(); var inputStream = delimitedContent.toBytesReference().streamInput(); MultipartUpload.skipUntilDelimiter(inputStream, delimitedContent.delimiter); var readRemaining = inputStream.readAllBytes(); assertArrayEquals(delimitedContent.after, readRemaining); } } record DelimitedContent(byte[] before, byte[] delimiter, byte[] after) { static DelimitedContent randomContent() { var before = randomAlphanumericOfLength(between(0, 1024 * 1024)).getBytes(UTF_8); var delimiter = randomByteArrayOfLength(between(1, 70)); delimiter[0] = '\r'; // make it distinguishable from the initial bytes var after = randomAlphanumericOfLength(between(0, 1024 * 1024)).getBytes(UTF_8); return new DelimitedContent(before, delimiter, after); } BytesReference toBytesReference() { return CompositeBytesReference.of(new BytesArray(before), new BytesArray(delimiter), new BytesArray(after)); } } }
MultipartUploadTests
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/heartbeat/TestingHeartbeatServices.java
{ "start": 6861, "end": 7824 }
class ____<O> implements HeartbeatMonitor.Factory<O> { @Override public HeartbeatMonitor<O> createHeartbeatMonitor( ResourceID resourceID, HeartbeatTarget<O> heartbeatTarget, ScheduledExecutor mainThreadExecutor, HeartbeatListener<?, O> heartbeatListener, long heartbeatTimeoutIntervalMs, int failedRpcRequestsUntilUnreachable) { return new TestingHeartbeatMonitor<>( resourceID, heartbeatTarget, mainThreadExecutor, heartbeatListener, heartbeatTimeoutIntervalMs, failedRpcRequestsUntilUnreachable); } } /** * A heartbeat monitor for testing which supports triggering timeout manually. * * @param <O> Type of the outgoing heartbeat payload */ static
TestingHeartbeatMonitorFactory
java
google__dagger
javatests/artifacts/dagger-ksp/java-app/src/main/java/app/AssistedInjectClasses.java
{ "start": 993, "end": 1135 }
interface ____ { FooFactory fooFactory(); ParameterizedFooFactory<Bar, String> parameterizedFooFactory(); } static final
MyComponent
java
apache__camel
core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/ManagedFailoverLoadBalancerMBean.java
{ "start": 1021, "end": 1725 }
interface ____ extends ManagedProcessorMBean, ManagedExtendedInformation { @ManagedAttribute(description = "Number of processors in the load balancer") Integer getSize(); @ManagedAttribute(description = "Whether or not the failover load balancer should operate in round robin mode or not.") Boolean isRoundRobin(); @ManagedAttribute(description = "Whether or not the failover load balancer should operate in sticky mode or not.") Boolean isSticky(); @ManagedAttribute(description = "A value to indicate after X failover attempts we should exhaust (give up).") Integer getMaximumFailoverAttempts(); @ManagedAttribute(description = "The
ManagedFailoverLoadBalancerMBean
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/streaming/api/datastream/extension/join/JoinITCase.java
{ "start": 2970, "end": 16974 }
class ____ extends AbstractTestBase implements Serializable { private transient ExecutionEnvironment env; private static List<String> sinkResults; @BeforeEach void before() throws Exception { env = ExecutionEnvironment.getInstance(); sinkResults = new ArrayList<>(); } @AfterEach void after() throws Exception { sinkResults.clear(); } @Test void testInnerJoinWithSameKey() throws Exception { NonKeyedPartitionStream<KeyAndValue> source1 = getSourceStream( Arrays.asList( KeyAndValue.of("key", 0), KeyAndValue.of("key", 1), KeyAndValue.of("key", 2)), "source1"); NonKeyedPartitionStream<KeyAndValue> source2 = getSourceStream( Arrays.asList( KeyAndValue.of("key", 0), KeyAndValue.of("key", 1), KeyAndValue.of("key", 2)), "source2"); NonKeyedPartitionStream<String> joinedStream = BuiltinFuncs.join( source1, (KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key, source2, (KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key, new TestJoinFunction(), JoinType.INNER); joinedStream.toSink(new WrappedSink<>(new TestSink())); env.execute("testInnerJoinWithSameKey"); expectInAnyOrder( "key:0:0", "key:0:1", "key:0:2", "key:1:0", "key:1:1", "key:1:2", "key:2:0", "key:2:1", "key:2:2"); } @Test void testInnerJoinWithMultipleKeys() throws Exception { NonKeyedPartitionStream<KeyAndValue> source1 = getSourceStream( Arrays.asList( KeyAndValue.of("key0", 0), KeyAndValue.of("key1", 1), KeyAndValue.of("key2", 2), KeyAndValue.of("key2", 3)), "source1"); NonKeyedPartitionStream<KeyAndValue> source2 = getSourceStream( Arrays.asList( KeyAndValue.of("key2", 4), KeyAndValue.of("key2", 5), KeyAndValue.of("key0", 6), KeyAndValue.of("key1", 7)), "source2"); NonKeyedPartitionStream<String> joinedStream = BuiltinFuncs.join( source1, (KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key, source2, (KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key, new TestJoinFunction(), JoinType.INNER); joinedStream.toSink(new WrappedSink<>(new TestSink())); env.execute("testInnerJoinWithMultipleKeys"); expectInAnyOrder("key0:0:6", "key1:1:7", "key2:2:4", "key2:2:5", "key2:3:4", "key2:3:5"); } @Test void testInnerJoinWhenLeftInputNoData() throws Exception { NonKeyedPartitionStream<KeyAndValue> source1 = getSourceStream( Arrays.asList( KeyAndValue.of("key0", 0), KeyAndValue.of("key1", 1), KeyAndValue.of("key2", 2), KeyAndValue.of("key2", 3)), "source1"); NonKeyedPartitionStream<KeyAndValue> source2 = getSourceStream(new ArrayList<>(), "source2"); NonKeyedPartitionStream<String> joinedStream = BuiltinFuncs.join( source1, (KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key, source2, (KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key, new TestJoinFunction(), JoinType.INNER); joinedStream.toSink(new WrappedSink<>(new TestSink())); env.execute("testInnerJoinWhenLeftInputNoData"); expectInAnyOrder(); } @Test void testInnerJoinWhenRightInputNoData() throws Exception { NonKeyedPartitionStream<KeyAndValue> source1 = getSourceStream(new ArrayList<>(), "source1"); NonKeyedPartitionStream<KeyAndValue> source2 = getSourceStream( Arrays.asList( KeyAndValue.of("key0", 0), KeyAndValue.of("key1", 1), KeyAndValue.of("key2", 2), KeyAndValue.of("key2", 3)), "source2"); NonKeyedPartitionStream<String> joinedStream = BuiltinFuncs.join( source1, (KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key, source2, (KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key, new TestJoinFunction(), JoinType.INNER); joinedStream.toSink(new WrappedSink<>(new TestSink())); env.execute("testInnerJoinWhenRightInputNoData"); expectInAnyOrder(); } /** Test Join using {@link BuiltinFuncs#join(JoinFunction)}. */ @Test void testJoinWithWrappedJoinProcessFunction() throws Exception { NonKeyedPartitionStream<KeyAndValue> source1 = getSourceStream( Arrays.asList( KeyAndValue.of("key", 0), KeyAndValue.of("key", 1), KeyAndValue.of("key", 2)), "source1"); NonKeyedPartitionStream<KeyAndValue> source2 = getSourceStream( Arrays.asList( KeyAndValue.of("key", 0), KeyAndValue.of("key", 1), KeyAndValue.of("key", 2)), "source2"); KeyedPartitionStream<String, KeyAndValue> keyedStream1 = source1.keyBy((KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key); KeyedPartitionStream<String, KeyAndValue> keyedStream2 = source2.keyBy((KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key); TwoInputNonBroadcastStreamProcessFunction<KeyAndValue, KeyAndValue, String> wrappedJoinProcessFunction = BuiltinFuncs.join(new TestJoinFunction()); NonKeyedPartitionStream<String> joinedStream = keyedStream1.connectAndProcess(keyedStream2, wrappedJoinProcessFunction); joinedStream.toSink(new WrappedSink<>(new TestSink())); env.execute("testInnerJoinWithSameKey"); expectInAnyOrder( "key:0:0", "key:0:1", "key:0:2", "key:1:0", "key:1:1", "key:1:2", "key:2:0", "key:2:1", "key:2:2"); } /** * Test Join using {@link BuiltinFuncs#join(KeyedPartitionStream, KeyedPartitionStream, * JoinFunction)}. */ @Test void testJoinWithKeyedStream() throws Exception { NonKeyedPartitionStream<KeyAndValue> source1 = getSourceStream( Arrays.asList( KeyAndValue.of("key", 0), KeyAndValue.of("key", 1), KeyAndValue.of("key", 2)), "source1"); NonKeyedPartitionStream<KeyAndValue> source2 = getSourceStream( Arrays.asList( KeyAndValue.of("key", 0), KeyAndValue.of("key", 1), KeyAndValue.of("key", 2)), "source2"); KeyedPartitionStream<String, KeyAndValue> keyedStream1 = source1.keyBy((KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key); KeyedPartitionStream<String, KeyAndValue> keyedStream2 = source2.keyBy((KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key); NonKeyedPartitionStream<String> joinedStream = BuiltinFuncs.join(keyedStream1, keyedStream2, new TestJoinFunction()); joinedStream.toSink(new WrappedSink<>(new TestSink())); env.execute("testInnerJoinWithSameKey"); expectInAnyOrder( "key:0:0", "key:0:1", "key:0:2", "key:1:0", "key:1:1", "key:1:2", "key:2:0", "key:2:1", "key:2:2"); } /** * Test Join using {@link BuiltinFuncs#join(NonKeyedPartitionStream, KeySelector, * NonKeyedPartitionStream, KeySelector, JoinFunction)}. */ @Test void testJoinWithNonKeyedStream() throws Exception { NonKeyedPartitionStream<KeyAndValue> source1 = getSourceStream( Arrays.asList( KeyAndValue.of("key", 0), KeyAndValue.of("key", 1), KeyAndValue.of("key", 2)), "source1"); NonKeyedPartitionStream<KeyAndValue> source2 = getSourceStream( Arrays.asList( KeyAndValue.of("key", 0), KeyAndValue.of("key", 1), KeyAndValue.of("key", 2)), "source2"); NonKeyedPartitionStream<String> joinedStream = BuiltinFuncs.join( source1, (KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key, source2, (KeySelector<KeyAndValue, String>) keyAndValue -> keyAndValue.key, new TestJoinFunction()); joinedStream.toSink(new WrappedSink<>(new TestSink())); env.execute("testInnerJoinWithSameKey"); expectInAnyOrder( "key:0:0", "key:0:1", "key:0:2", "key:1:0", "key:1:1", "key:1:2", "key:2:0", "key:2:1", "key:2:2"); } @Test void testJoinWithTuple() throws Exception { final String resultPath = getTempDirPath("result"); NonKeyedPartitionStream<Tuple2<String, Integer>> source1 = env.fromSource( DataStreamV2SourceUtils.fromData( Arrays.asList( Tuple2.of("key", 0), Tuple2.of("key", 1), Tuple2.of("key", 2))), "source1"); NonKeyedPartitionStream<Tuple2<String, Integer>> source2 = env.fromSource( DataStreamV2SourceUtils.fromData( Arrays.asList( Tuple2.of("key", 0), Tuple2.of("key", 1), Tuple2.of("key", 2))), "source2"); NonKeyedPartitionStream<Tuple3<String, Integer, Integer>> joinedStream = BuiltinFuncs.join( source1, (KeySelector<Tuple2<String, Integer>, String>) elem -> elem.f0, source2, (KeySelector<Tuple2<String, Integer>, String>) elem -> elem.f0, new JoinFunction< Tuple2<String, Integer>, Tuple2<String, Integer>, Tuple3<String, Integer, Integer>>() { @Override public void processRecord( Tuple2<String, Integer> leftRecord, Tuple2<String, Integer> rightRecord, Collector<Tuple3<String, Integer, Integer>> output, RuntimeContext ctx) throws Exception { output.collect( Tuple3.of(leftRecord.f0, leftRecord.f1, rightRecord.f1)); } }); joinedStream.toSink( new WrappedSink<>( FileSink.<Tuple3<String, Integer, Integer>>forRowFormat( new Path(resultPath), new SimpleStringEncoder<>()) .withRollingPolicy( DefaultRollingPolicy.builder() .withMaxPartSize(MemorySize.ofMebiBytes(1)) .withRolloverInterval(Duration.ofSeconds(10)) .build()) .build())); env.execute("testJoinWithTuple"); compareResultsByLinesInMemory( "(key,0,0)\n" + "(key,0,1)\n" + "(key,0,2)\n" + "(key,1,0)\n" + "(key,1,1)\n" + "(key,1,2)\n" + "(key,2,0)\n" + "(key,2,1)\n" + "(key,2,2)\n", resultPath); } private static
JoinITCase
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/kotlin/Issue1750.java
{ "start": 1023, "end": 1561 }
class ____ extends ClassLoader { public ExtClassLoader() throws IOException { super(Thread.currentThread().getContextClassLoader()); { byte[] bytes; InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/Issue1750_ProcessBO.clazz"); bytes = IOUtils.toByteArray(is); is.close(); super.defineClass("Issue1750_ProcessBO", bytes, 0, bytes.length); } } } }
ExtClassLoader
java
apache__camel
components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/decorators/internal/SedaSegmentDecorator.java
{ "start": 876, "end": 1027 }
class ____ extends AbstractInternalSegmentDecorator { @Override public String getComponent() { return "seda"; } }
SedaSegmentDecorator
java
apache__dubbo
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TComponent.java
{ "start": 875, "end": 955 }
interface ____ { /** * render */ String rendering(); }
TComponent
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/authentication/event/AbstractAuthenticationFailureEvent.java
{ "start": 984, "end": 1433 }
class ____ extends AbstractAuthenticationEvent { private final AuthenticationException exception; public AbstractAuthenticationFailureEvent(Authentication authentication, AuthenticationException exception) { super(authentication); Assert.notNull(exception, "AuthenticationException is required"); this.exception = exception; } public AuthenticationException getException() { return this.exception; } }
AbstractAuthenticationFailureEvent
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JUnit4SetUpNotRunTest.java
{ "start": 2947, "end": 3571 }
class ____ extends BaseTestClass { @Override // BUG: Diagnostic contains: @Before public void setUp() {} } """) .doTest(); } @Test public void positiveCase_customBefore() { compilationHelper .addSourceLines( "JUnit4SetUpNotRunPositiveCaseCustomBefore.java", """ package com.google.errorprone.bugpatterns.testdata; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Slightly funky test case with a custom Before annotation */ @RunWith(JUnit4.class) public
J4OverriddenSetUpPublic
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/amazonbedrock/response/completion/AmazonBedrockChatCompletionResponse.java
{ "start": 997, "end": 1951 }
class ____ extends AmazonBedrockResponse { private final ConverseResponse result; public AmazonBedrockChatCompletionResponse(ConverseResponse responseResult) { this.result = responseResult; } @Override public InferenceServiceResults accept(AmazonBedrockRequest request) { if (request instanceof AmazonBedrockChatCompletionRequest asChatCompletionRequest) { return fromResponse(result); } throw new ElasticsearchException("unexpected request type [" + request.getClass() + "]"); } public static ChatCompletionResults fromResponse(ConverseResponse response) { var resultTexts = response.output() .message() .content() .stream() .map(ContentBlock::text) .map(ChatCompletionResults.Result::new) .toList(); return new ChatCompletionResults(resultTexts); } }
AmazonBedrockChatCompletionResponse
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/LockNotBeforeTryTest.java
{ "start": 8943, "end": 9482 }
class ____ implements Lock { private void test(Lock l) { lock(); l.lock(); try { } finally { unlock(); l.unlock(); } } } """) .doTest(); } @Test public void nonInvocationExpression() { compilationHelper .addSourceLines( "Test.java", """ import java.util.concurrent.locks.ReentrantLock; abstract
Test
java
apache__flink
flink-datastream/src/test/java/org/apache/flink/datastream/impl/operators/MockGlobalDecuplicateCountProcessFunction.java
{ "start": 1504, "end": 2735 }
class ____ implements OneInputStreamProcessFunction<Integer, Integer> { private final BroadcastStateDeclaration<Integer, Integer> broadcastStateDeclaration = StateDeclarations.mapStateBuilder( "broadcast-state", TypeDescriptors.INT, TypeDescriptors.INT) .buildBroadcast(); @Override public Set<StateDeclaration> usesStates() { return new HashSet<>(Collections.singletonList(broadcastStateDeclaration)); } @Override public void processRecord( Integer record, Collector<Integer> output, PartitionedContext<Integer> ctx) throws Exception { Optional<BroadcastState<Integer, Integer>> stateOptional = ctx.getStateManager().getStateOptional(broadcastStateDeclaration); if (!stateOptional.isPresent()) { throw new RuntimeException("State is not available"); } BroadcastState<Integer, Integer> state = stateOptional.get(); state.put(record, record); int len = 0; for (Map.Entry<Integer, Integer> entry : state.entries()) { len++; } output.collect(len); } }
MockGlobalDecuplicateCountProcessFunction
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.java
{ "start": 6383, "end": 6876 }
class ____ { public void doTest() { Client client = new Client(); String result = client.after(); } } """) .doTest(); } @Test public void staticMethod_explicitTypeParam() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.foo; import com.google.errorprone.annotations.InlineMe; public final
Caller
java
apache__maven
impl/maven-xml/src/main/java/org/apache/maven/internal/xml/XmlNodeBuilder.java
{ "start": 6494, "end": 6589 }
interface ____ { Object toInputLocation(XmlPullParser parser); } }
InputLocationBuilder
java
spring-projects__spring-boot
module/spring-boot-webtestclient/src/test/java/org/springframework/boot/webflux/test/autoconfigure/WebTestClientAutoConfigurationTests.java
{ "start": 8533, "end": 8694 }
class ____ { @Bean CodecCustomizer myCodecCustomizer() { return mock(CodecCustomizer.class); } } @SuppressWarnings("unused") static
CodecConfiguration
java
google__auto
value/src/main/java/com/google/auto/value/processor/AutoValueishProcessor.java
{ "start": 57579, "end": 58455 }
class ____ defines the annotation. The JLS says "Access is permitted only within the // body of a subclass": // https://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.6.2.1 // AutoValue_Foo is a top-level class, so an annotation on it cannot be in the body of a // subclass of anything. if (!getPackage(annotationElement).equals(getPackage(from)) && !typeUtils() .isSubtype(from.asType(), annotationElement.getEnclosingElement().asType())) { return false; } break; case DEFAULT: return getPackage(annotationElement).equals(getPackage(from)); default: return false; } return true; } /** * Returns the {@code @AutoValue} or {@code @AutoOneOf} type parameters, with a ? for every type. * If we have {@code @AutoValue abstract
that
java
redisson__redisson
redisson/src/main/java/org/redisson/api/search/index/GeoIndex.java
{ "start": 726, "end": 1416 }
interface ____ extends FieldIndex { /** * Defines the attribute associated to the field name * * @param as the associated attribute * @return options object */ GeoIndex as(String as); /** * Defines sort mode applied to the value of this attribute * * @param sortMode sort mode * @return options object */ GeoIndex sortMode(SortMode sortMode); /** * Defines to not index this attribute * * @return options object */ GeoIndex noIndex(); /** * Defines to index documents that don't contain this attribute * * @return options object */ GeoIndex indexMissing(); }
GeoIndex
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/filter/IgnoredTypesTest.java
{ "start": 740, "end": 915 }
class ____ { public int value = 13; public IgnoredType ignored; } // // And test for mix-in annotations @JsonIgnoreType static
NonIgnoredType
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/domain/sample/UserWithOptionalField.java
{ "start": 905, "end": 1761 }
class ____ { @Id @GeneratedValue private Long id; private String name; private String role; public UserWithOptionalField() { this.id = null; this.name = null; this.role = null; } public UserWithOptionalField(String name, @Nullable String role) { this(); this.name = name; this.role = role; } public Optional<String> getRole() { return Optional.ofNullable(this.role); } public void setRole(Optional<String> role) { this.role = role.orElse(null); } public Long getId() { return this.id; } public String getName() { return this.name; } public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } public String toString() { return "UserWithOptionalField(id=" + this.getId() + ", name=" + this.getName() + ", role=" + this.getRole() + ")"; } }
UserWithOptionalField
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/store/impl/ZKFederationStateStoreOpDurations.java
{ "start": 1703, "end": 8875 }
class ____ implements MetricsSource { @Metric("Duration for a add application homeSubcluster call") private MutableRate addAppHomeSubCluster; @Metric("Duration for a update application homeSubcluster call") private MutableRate updateAppHomeSubCluster; @Metric("Duration for a get application homeSubcluster call") private MutableRate getAppHomeSubCluster; @Metric("Duration for a get applications homeSubcluster call") private MutableRate getAppsHomeSubCluster; @Metric("Duration for a delete applications homeSubcluster call") private MutableRate deleteAppHomeSubCluster; @Metric("Duration for a register subCluster call") private MutableRate registerSubCluster; @Metric("Duration for a deregister subCluster call") private MutableRate deregisterSubCluster; @Metric("Duration for a subCluster Heartbeat call") private MutableRate subClusterHeartbeat; @Metric("Duration for a get SubCluster call") private MutableRate getSubCluster; @Metric("Duration for a get SubClusters call") private MutableRate getSubClusters; @Metric("Duration for a get PolicyConfiguration call") private MutableRate getPolicyConfiguration; @Metric("Duration for a set PolicyConfiguration call") private MutableRate setPolicyConfiguration; @Metric("Duration for a get PolicyConfigurations call") private MutableRate getPoliciesConfigurations; @Metric("Duration for a add reservation homeSubCluster call") private MutableRate addReservationHomeSubCluster; @Metric("Duration for a get reservation homeSubCluster call") private MutableRate getReservationHomeSubCluster; @Metric("Duration for a get reservations homeSubCluster call") private MutableRate getReservationsHomeSubCluster; @Metric("Duration for a delete reservation homeSubCluster call") private MutableRate deleteReservationHomeSubCluster; @Metric("Duration for a update reservation homeSubCluster call") private MutableRate updateReservationHomeSubCluster; @Metric("Duration for a store new master key call") private MutableRate storeNewMasterKey; @Metric("Duration for a remove new master key call") private MutableRate removeStoredMasterKey; @Metric("Duration for a get master key by delegation key call") private MutableRate getMasterKeyByDelegationKey; @Metric("Duration for a store new token call") private MutableRate storeNewToken; @Metric("Duration for a update stored token call") private MutableRate updateStoredToken; @Metric("Duration for a remove stored token call") private MutableRate removeStoredToken; @Metric("Duration for a get token by router store token call") private MutableRate getTokenByRouterStoreToken; protected static final MetricsInfo RECORD_INFO = info("ZKFederationStateStoreOpDurations", "Durations of ZKFederationStateStore calls"); private final MetricsRegistry registry; private static final ZKFederationStateStoreOpDurations INSTANCE = new ZKFederationStateStoreOpDurations(); public static ZKFederationStateStoreOpDurations getInstance() { return INSTANCE; } private ZKFederationStateStoreOpDurations() { registry = new MetricsRegistry(RECORD_INFO); registry.tag(RECORD_INFO, "ZKFederationStateStoreOpDurations"); MetricsSystem ms = DefaultMetricsSystem.instance(); if (ms != null) { ms.register(RECORD_INFO.name(), RECORD_INFO.description(), this); } } @Override public synchronized void getMetrics(MetricsCollector collector, boolean all) { registry.snapshot(collector.addRecord(registry.info()), all); } public void addAppHomeSubClusterDuration(long startTime, long endTime) { addAppHomeSubCluster.add(endTime - startTime); } public void addUpdateAppHomeSubClusterDuration(long startTime, long endTime) { updateAppHomeSubCluster.add(endTime - startTime); } public void addGetAppHomeSubClusterDuration(long startTime, long endTime) { getAppHomeSubCluster.add(endTime - startTime); } public void addGetAppsHomeSubClusterDuration(long startTime, long endTime) { getAppsHomeSubCluster.add(endTime - startTime); } public void addDeleteAppHomeSubClusterDuration(long startTime, long endTime) { deleteAppHomeSubCluster.add(endTime - startTime); } public void addRegisterSubClusterDuration(long startTime, long endTime) { registerSubCluster.add(endTime - startTime); } public void addDeregisterSubClusterDuration(long startTime, long endTime) { deregisterSubCluster.add(endTime - startTime); } public void addSubClusterHeartbeatDuration(long startTime, long endTime) { subClusterHeartbeat.add(endTime - startTime); } public void addGetSubClusterDuration(long startTime, long endTime) { getSubCluster.add(endTime - startTime); } public void addGetSubClustersDuration(long startTime, long endTime) { getSubClusters.add(endTime - startTime); } public void addGetPolicyConfigurationDuration(long startTime, long endTime) { getPolicyConfiguration.add(endTime - startTime); } public void addSetPolicyConfigurationDuration(long startTime, long endTime) { setPolicyConfiguration.add(endTime - startTime); } public void addGetPoliciesConfigurationsDuration(long startTime, long endTime) { getPoliciesConfigurations.add(endTime - startTime); } public void addReservationHomeSubClusterDuration(long startTime, long endTime) { addReservationHomeSubCluster.add(endTime - startTime); } public void addGetReservationHomeSubClusterDuration(long startTime, long endTime) { getReservationHomeSubCluster.add(endTime - startTime); } public void addGetReservationsHomeSubClusterDuration(long startTime, long endTime) { getReservationsHomeSubCluster.add(endTime - startTime); } public void addDeleteReservationHomeSubClusterDuration(long startTime, long endTime) { deleteReservationHomeSubCluster.add(endTime - startTime); } public void addUpdateReservationHomeSubClusterDuration(long startTime, long endTime) { updateReservationHomeSubCluster.add(endTime - startTime); } public void addStoreNewMasterKeyDuration(long startTime, long endTime) { storeNewMasterKey.add(endTime - startTime); } public void removeStoredMasterKeyDuration(long startTime, long endTime) { removeStoredMasterKey.add(endTime - startTime); } public void getMasterKeyByDelegationKeyDuration(long startTime, long endTime) { getMasterKeyByDelegationKey.add(endTime - startTime); } public void getStoreNewTokenDuration(long startTime, long endTime) { storeNewToken.add(endTime - startTime); } public void updateStoredTokenDuration(long startTime, long endTime) { updateStoredToken.add(endTime - startTime); } public void removeStoredTokenDuration(long startTime, long endTime) { removeStoredToken.add(endTime - startTime); } public void getTokenByRouterStoreTokenDuration(long startTime, long endTime) { getTokenByRouterStoreToken.add(endTime - startTime); } @VisibleForTesting protected ZKFederationStateStoreOpDurations resetOpDurations() { return new ZKFederationStateStoreOpDurations(); } }
ZKFederationStateStoreOpDurations
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/vectors/diskbbq/DocIdsWriter.java
{ "start": 1105, "end": 1333 }
class ____ used to write and read the doc ids in a compressed format. The format is optimized * for the number of bits per value (bpv) and the number of values. * * <p>It is copied from the BKD implementation. */ public final
is
java
spring-projects__spring-boot
module/spring-boot-hazelcast/src/main/java/org/springframework/boot/hazelcast/autoconfigure/HazelcastClientConfigAvailableCondition.java
{ "start": 2441, "end": 3579 }
class ____ { static @Nullable ConditionOutcome clientConfigOutcome(ConditionContext context, String propertyName, Builder builder) { String resourcePath = context.getEnvironment().getProperty(propertyName); Assert.state(resourcePath != null, "'resourcePath' must not be null"); Resource resource = context.getResourceLoader().getResource(resourcePath); if (!resource.exists()) { return ConditionOutcome.noMatch(builder.because("Hazelcast configuration does not exist")); } try (InputStream in = resource.getInputStream()) { boolean clientConfig = new ClientConfigRecognizer().isRecognized(new ConfigStream(in)); return new ConditionOutcome(clientConfig, existingConfigurationOutcome(resource, clientConfig)); } catch (Throwable ex) { return null; } } private static String existingConfigurationOutcome(Resource resource, boolean client) throws IOException { URL location = resource.getURL(); return client ? "Hazelcast client configuration detected at '" + location + "'" : "Hazelcast server configuration detected at '" + location + "'"; } } }
HazelcastClientValidation
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/PublisherResponseHandler.java
{ "start": 16100, "end": 16728 }
class ____ implements StreamingResponseCustomizer { private int status; public StatusCustomizer(int status) { this.status = status; } public StatusCustomizer() { } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } @Override public void customize(StreamingResponse<?> streamingResponse) { streamingResponse.setStatusCode(status); } }
StatusCustomizer
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/operations/SqlNodeToCallOperationTest.java
{ "start": 11024, "end": 11309 }
class ____ implements Procedure { public @DataTypeHint("ROW<i INT>") Row[] call( ProcedureContext procedureContext, @DataTypeHint("DECIMAL(10, 2)") BigDecimal decimal) { return null; } } private static
RowResultProcedure
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/mappingcontrol/MethodMapper.java
{ "start": 308, "end": 600 }
interface ____ { MethodMapper INSTANCE = Mappers.getMapper( MethodMapper.class ); @Mapping(target = "beerCount", source = "shelve") Fridge map(FridgeDTO in); default int map(ShelveDTO in) { return Integer.valueOf( in.getCoolBeer().getBeerCount() ); } }
MethodMapper
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ClassCanBeStaticTest.java
{ "start": 861, "end": 1348 }
class ____ { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ClassCanBeStatic.class, getClass()); @Test public void negativeCase() { compilationHelper .addSourceLines( "ClassCanBeStaticNegativeCases.java", """ package com.google.errorprone.bugpatterns.testdata; /** * @author alexloh@google.com (Alex Loh) */ public
ClassCanBeStaticTest
java
google__guava
android/guava/src/com/google/common/base/MoreObjects.java
{ "start": 4959, "end": 5125 }
class ____ {@link MoreObjects#toStringHelper}. * * @author Jason Lee * @since 18.0 (since 2.0 as {@code Objects.ToStringHelper}). */ public static final
for
java
apache__camel
core/camel-management/src/main/java/org/apache/camel/management/mbean/ManagedConsumer.java
{ "start": 1144, "end": 2114 }
class ____ extends ManagedService implements ManagedConsumerMBean { private final Consumer consumer; public ManagedConsumer(CamelContext context, Consumer consumer) { super(context, consumer); this.consumer = consumer; } public Consumer getConsumer() { return consumer; } @Override public String getEndpointUri() { return consumer.getEndpoint().getEndpointUri(); } @Override public Integer getInflightExchanges() { if (getRouteId() != null) { return getContext().getInflightRepository().size(getRouteId()); } else { return null; } } @Override public boolean isHostedService() { if (consumer instanceof HostedService hs) { return hs.isHostedService(); } return false; } @Override public boolean isRemoteEndpoint() { return consumer.getEndpoint().isRemote(); } }
ManagedConsumer
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/ChildValue.java
{ "start": 186, "end": 720 }
class ____ implements Child { private String name; public ChildValue() { } public ChildValue(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean equals(Object otherChild) { if ( this == otherChild ) { return true; } if ( !( otherChild instanceof ChildValue ) ) { return false; } return name.equals( ( ( ChildValue ) otherChild ).name ); } public int hashCode() { return name.hashCode(); } }
ChildValue
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/HttpEntityMethodArgumentResolver.java
{ "start": 1463, "end": 2643 }
class ____ extends AbstractMessageReaderArgumentResolver { public HttpEntityMethodArgumentResolver(List<HttpMessageReader<?>> readers, ReactiveAdapterRegistry registry) { super(readers, registry); } @Override public boolean supportsParameter(MethodParameter parameter) { return checkParameterTypeNoReactiveWrapper(parameter, type -> HttpEntity.class.equals(type) || RequestEntity.class.equals(type)); } @Override public Mono<Object> resolveArgument( MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) { Class<?> entityType = parameter.getParameterType(); return readBody(parameter.nested(), parameter, false, bindingContext, exchange) .map(body -> createEntity(body, entityType, exchange.getRequest())) .defaultIfEmpty(createEntity(null, entityType, exchange.getRequest())); } private Object createEntity(@Nullable Object body, Class<?> entityType, ServerHttpRequest request) { return (RequestEntity.class.equals(entityType) ? new RequestEntity<>(body, request.getHeaders(), request.getMethod(), request.getURI()) : new HttpEntity<>(body, request.getHeaders())); } }
HttpEntityMethodArgumentResolver
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java
{ "start": 35554, "end": 36579 }
class ____ { private VolumeApi api; @BeforeEach void setup() { this.api = DockerApiTests.this.dockerApi.volume(); } @Test @SuppressWarnings("NullAway") // Test null check void deleteWhenNameIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.delete(null, false)) .withMessage("'name' must not be null"); } @Test void deleteDeletesContainer() throws Exception { VolumeName name = VolumeName.of("test"); URI removeUri = new URI(VOLUMES_URL + "/test"); given(http().delete(removeUri)).willReturn(emptyResponse()); this.api.delete(name, false); then(http()).should().delete(removeUri); } @Test void deleteWhenForceIsTrueDeletesContainer() throws Exception { VolumeName name = VolumeName.of("test"); URI removeUri = new URI(VOLUMES_URL + "/test?force=1"); given(http().delete(removeUri)).willReturn(emptyResponse()); this.api.delete(name, true); then(http()).should().delete(removeUri); } } @Nested
VolumeDockerApiTests
java
spring-projects__spring-boot
module/spring-boot-data-jpa-test/src/main/java/org/springframework/boot/data/jpa/test/autoconfigure/DataJpaTest.java
{ "start": 3939, "end": 5620 }
interface ____ { /** * Properties in form {@literal key=value} that should be added to the Spring * {@link Environment} before the test runs. * @return the properties to add */ String[] properties() default {}; /** * If SQL output should be logged. * @return if SQL is logged */ @PropertyMapping("spring.jpa.show-sql") boolean showSql() default true; /** * The {@link BootstrapMode} for the test repository support. Defaults to * {@link BootstrapMode#DEFAULT}. * @return the {@link BootstrapMode} to use for testing the repository */ @PropertyMapping("spring.data.jpa.repositories.bootstrap-mode") BootstrapMode bootstrapMode() default BootstrapMode.DEFAULT; /** * Determines if default filtering should be used with * {@link SpringBootApplication @SpringBootApplication}. By default no beans are * included. * @see #includeFilters() * @see #excludeFilters() * @return if default filters should be used */ boolean useDefaultFilters() default true; /** * A set of include filters which can be used to add otherwise filtered beans to the * application context. * @return include filters to apply */ Filter[] includeFilters() default {}; /** * A set of exclude filters which can be used to filter beans that would otherwise be * added to the application context. * @return exclude filters to apply */ Filter[] excludeFilters() default {}; /** * Auto-configuration exclusions that should be applied for this test. * @return auto-configuration exclusions to apply */ @AliasFor(annotation = ImportAutoConfiguration.class, attribute = "exclude") Class<?>[] excludeAutoConfiguration() default {}; }
DataJpaTest
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/filter/HttpFilterResolver.java
{ "start": 1299, "end": 1923 }
interface ____<T extends AnnotationMetadataProvider> { /** * Resolves the initial list of filters. * @param context The context * @return The filters * @since 2.0 */ List<FilterEntry> resolveFilterEntries(T context); /** * Returns which filters should apply for the given request. * * @param request The request * @param filterEntries the filter entries * @return The list of filters */ List<GenericHttpFilter> resolveFilters(HttpRequest<?> request, List<FilterEntry> filterEntries); /** * A resolved filter entry. */
HttpFilterResolver
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java
{ "start": 59463, "end": 65603 }
class ____ { // Queue is used to ensure the sequence of commit Queue<OffsetCommitRequestState> unsentOffsetCommits = new LinkedList<>(); List<OffsetFetchRequestState> unsentOffsetFetches = new ArrayList<>(); List<OffsetFetchRequestState> inflightOffsetFetches = new ArrayList<>(); // Visible for testing boolean hasUnsentRequests() { return !unsentOffsetCommits.isEmpty() || !unsentOffsetFetches.isEmpty(); } /** * Add a commit request to the queue, so that it's sent out on the next call to * {@link #poll(long)}. This is used from all commits (sync, async, auto-commit). */ OffsetCommitRequestState addOffsetCommitRequest(OffsetCommitRequestState request) { log.debug("Enqueuing OffsetCommit request for offsets: {}", request.offsets); unsentOffsetCommits.add(request); return request; } /** * <p>Adding an offset fetch request to the outgoing buffer. If the same request was made, we chain the future * to the existing one. * * <p>If the request is new, it invokes a callback to remove itself from the {@code inflightOffsetFetches} * upon completion. */ private CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> addOffsetFetchRequest(final OffsetFetchRequestState request) { Optional<OffsetFetchRequestState> dupe = unsentOffsetFetches.stream().filter(r -> r.sameRequest(request)).findAny(); Optional<OffsetFetchRequestState> inflight = inflightOffsetFetches.stream().filter(r -> r.sameRequest(request)).findAny(); if (dupe.isPresent() || inflight.isPresent()) { log.debug("Duplicated unsent offset fetch request found for partitions: {}", request.requestedPartitions); dupe.orElseGet(inflight::get).chainFuture(request.future); } else { log.debug("Enqueuing offset fetch request for partitions: {}", request.requestedPartitions); this.unsentOffsetFetches.add(request); } return request.future; } /** * Clear {@code unsentOffsetCommits} and moves all the sendable request in {@code * unsentOffsetFetches} to the {@code inflightOffsetFetches} to bookkeep all the inflight * requests. Note: Sendable requests are determined by their timer as we are expecting * backoff on failed attempt. See {@link RequestState}. */ List<NetworkClientDelegate.UnsentRequest> drain(final long currentTimeMs) { // not ready to sent request List<OffsetCommitRequestState> unreadyCommitRequests = unsentOffsetCommits.stream() .filter(request -> !request.canSendRequest(currentTimeMs)) .collect(Collectors.toList()); failAndRemoveExpiredCommitRequests(); // Add all unsent offset commit requests to the unsentRequests list List<NetworkClientDelegate.UnsentRequest> unsentRequests = unsentOffsetCommits.stream() .filter(request -> request.canSendRequest(currentTimeMs)) .peek(request -> request.onSendAttempt(currentTimeMs)) .map(OffsetCommitRequestState::toUnsentRequest) .collect(Collectors.toCollection(ArrayList::new)); // Partition the unsent offset fetch requests into sendable and non-sendable lists Map<Boolean, List<OffsetFetchRequestState>> partitionedBySendability = unsentOffsetFetches.stream() .collect(Collectors.partitioningBy(request -> request.canSendRequest(currentTimeMs))); // Add all sendable offset fetch requests to the unsentRequests list and to the inflightOffsetFetches list for (OffsetFetchRequestState request : partitionedBySendability.get(true)) { request.onSendAttempt(currentTimeMs); unsentRequests.add(request.toUnsentRequest()); inflightOffsetFetches.add(request); } // Clear the unsent offset commit and fetch lists and add all non-sendable offset fetch requests to the unsentOffsetFetches list clearAll(); unsentOffsetFetches.addAll(partitionedBySendability.get(false)); unsentOffsetCommits.addAll(unreadyCommitRequests); return Collections.unmodifiableList(unsentRequests); } /** * Find the unsent commit requests that have expired, remove them and complete their * futures with a TimeoutException. */ private void failAndRemoveExpiredCommitRequests() { Queue<OffsetCommitRequestState> requestsToPurge = new LinkedList<>(unsentOffsetCommits); requestsToPurge.forEach(RetriableRequestState::maybeExpire); } private void clearAll() { unsentOffsetCommits.clear(); unsentOffsetFetches.clear(); } private List<NetworkClientDelegate.UnsentRequest> drainPendingCommits() { List<NetworkClientDelegate.UnsentRequest> res = unsentOffsetCommits.stream() .map(OffsetCommitRequestState::toUnsentRequest) .collect(Collectors.toCollection(ArrayList::new)); clearAll(); return res; } private void maybeFailOnCoordinatorFatalError() { coordinatorRequestManager.fatalError().ifPresent(error -> { log.warn("Failing all unsent commit requests and offset fetches because of coordinator fatal error. ", error); unsentOffsetCommits.forEach(request -> request.future.completeExceptionally(error)); unsentOffsetFetches.forEach(request -> request.future.completeExceptionally(error)); clearAll(); } ); } } /** * Encapsulates the state of auto-committing and manages the auto-commit timer. */ private static
PendingRequests
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java
{ "start": 5658, "end": 5741 }
interface ____ { // empty } public static
PackagePrivateEmptyInterface
java
reactor__reactor-core
reactor-core/src/test/java/reactor/test/MockUtils.java
{ "start": 1108, "end": 1217 }
class ____<T> extends ConnectableFlux<T> implements Scannable { } /** * An
TestScannableConnectableFlux
java
grpc__grpc-java
interop-testing/src/main/java/io/grpc/testing/integration/Http2Client.java
{ "start": 5980, "end": 9289 }
class ____ { private final int timeoutSeconds = 180; private final int responseSize = 314159; private final int payloadSize = 271828; private final SimpleRequest simpleRequest = SimpleRequest.newBuilder() .setResponseSize(responseSize) .setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[payloadSize]))) .build(); final SimpleResponse goldenResponse = SimpleResponse.newBuilder() .setPayload(Payload.newBuilder() .setBody(ByteString.copyFrom(new byte[responseSize]))) .build(); private void rstAfterHeader() throws Exception { try { blockingStub.unaryCall(simpleRequest); throw new AssertionError("Expected call to fail"); } catch (StatusRuntimeException ex) { assertRstStreamReceived(ex.getStatus()); } } private void rstAfterData() throws Exception { // Use async stub to verify data is received. RstStreamObserver responseObserver = new RstStreamObserver(); asyncStub.unaryCall(simpleRequest, responseObserver); if (!responseObserver.awaitCompletion(timeoutSeconds, TimeUnit.SECONDS)) { throw new AssertionError("Operation timed out"); } if (responseObserver.getError() == null) { throw new AssertionError("Expected call to fail"); } assertRstStreamReceived(Status.fromThrowable(responseObserver.getError())); if (responseObserver.getResponses().size() != 1) { throw new AssertionError("Expected one response"); } } private void rstDuringData() throws Exception { // Use async stub to verify no data is received. RstStreamObserver responseObserver = new RstStreamObserver(); asyncStub.unaryCall(simpleRequest, responseObserver); if (!responseObserver.awaitCompletion(timeoutSeconds, TimeUnit.SECONDS)) { throw new AssertionError("Operation timed out"); } if (responseObserver.getError() == null) { throw new AssertionError("Expected call to fail"); } assertRstStreamReceived(Status.fromThrowable(responseObserver.getError())); if (responseObserver.getResponses().size() != 0) { throw new AssertionError("Expected zero responses"); } } private void goAway() throws Exception { assertResponseEquals(blockingStub.unaryCall(simpleRequest), goldenResponse); TimeUnit.SECONDS.sleep(1); assertResponseEquals(blockingStub.unaryCall(simpleRequest), goldenResponse); } private void ping() throws Exception { assertResponseEquals(blockingStub.unaryCall(simpleRequest), goldenResponse); } private void maxStreams() throws Exception { final int numThreads = 10; // Preliminary call to ensure MAX_STREAMS setting is received by the client. assertResponseEquals(blockingStub.unaryCall(simpleRequest), goldenResponse); threadpool = MoreExecutors.listeningDecorator(newFixedThreadPool(numThreads)); List<ListenableFuture<?>> workerFutures = new ArrayList<>(); for (int i = 0; i < numThreads; i++) { workerFutures.add(threadpool.submit(new MaxStreamsWorker(i))); } ListenableFuture<?> f = Futures.allAsList(workerFutures); f.get(timeoutSeconds, TimeUnit.SECONDS); } private
Tester
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/enhance/spi/EnhancementContext.java
{ "start": 3817, "end": 4584 }
class ____ cannot be enhanced, * in particular when attribute names don't match field names. * @see <a href="https://hibernate.atlassian.net/browse/HHH-16572">HHH-16572</a> * @see <a href="https://hibernate.atlassian.net/browse/HHH-18833">HHH-18833</a> */ @Incubating default UnsupportedEnhancementStrategy getUnsupportedEnhancementStrategy() { return UnsupportedEnhancementStrategy.SKIP; } /** * Allows to force the use of a specific instance of BytecodeProvider to perform the enhancement. * @return When returning {code null} the default implementation will be used. Only return a different instance if * you need to override the default implementation. */ @Incubating default BytecodeProvider getBytecodeProvider() { return null; } }
that
java
apache__camel
components/camel-datasonnet/src/main/java/org/apache/camel/language/datasonnet/DatasonnetAnnotationExpressionFactory.java
{ "start": 1274, "end": 2978 }
class ____ extends DefaultAnnotationExpressionFactory { @Override public Expression createExpression( CamelContext camelContext, Annotation annotation, LanguageAnnotation languageAnnotation, Class<?> expressionReturnType) { String ds = getExpressionFromAnnotation(annotation); DatasonnetExpression answer = new DatasonnetExpression(ds); Class<?> resultType = getResultType(annotation); if (resultType.equals(Object.class)) { resultType = expressionReturnType; } String source = getSource(annotation); answer.setSource(ExpressionBuilder.singleInputExpression(source)); if (annotation instanceof Datasonnet) { Datasonnet ann = (Datasonnet) annotation; if (!ann.bodyMediaType().isEmpty()) { answer.setBodyMediaType(MediaType.valueOf(ann.bodyMediaType())); } if (!ann.outputMediaType().isEmpty()) { answer.setOutputMediaType(MediaType.valueOf(ann.outputMediaType())); } } return ExpressionBuilder.convertToExpression(answer, resultType); } protected Class<?> getResultType(Annotation annotation) { return (Class<?>) getAnnotationObjectValue(annotation, "resultType"); } protected String getSource(Annotation annotation) { String answer = null; try { answer = (String) getAnnotationObjectValue(annotation, "source"); } catch (Exception e) { // Do Nothing } if (answer != null && answer.isBlank()) { return null; } return answer; } }
DatasonnetAnnotationExpressionFactory
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/LcsArgs.java
{ "start": 1015, "end": 3008 }
class ____ { /** * Utility constructor. */ private Builder() { } /** * Creates new {@link LcsArgs} by keys. * * @return new {@link LcsArgs} with {@literal By KEYS} set. */ public static LcsArgs keys(String... keys) { return new LcsArgs().by(keys); } } /** * restrict the list of matches to the ones of a given minimal length. * * @return {@code this} {@link LcsArgs}. */ public LcsArgs minMatchLen(int minMatchLen) { this.minMatchLen = minMatchLen; return this; } /** * Request just the length of the match for results. * * @return {@code this} {@link LcsArgs}. */ public LcsArgs justLen() { justLen = true; return this; } /** * Request match len for results. * * @return {@code this} {@link LcsArgs}. */ public LcsArgs withMatchLen() { withMatchLen = true; return this; } /** * Request match position in each string for results. * * @return {@code this} {@link LcsArgs}. */ public LcsArgs withIdx() { withIdx = true; return this; } public LcsArgs by(String... keys) { LettuceAssert.notEmpty(keys, "Keys must not be empty"); this.keys = keys; return this; } public boolean isWithIdx() { return withIdx; } @Override public <K, V> void build(CommandArgs<K, V> args) { for (String key : keys) { args.add(key); } if (justLen) { args.add(CommandKeyword.LEN); } if (withIdx) { args.add(CommandKeyword.IDX); } if (minMatchLen > 0) { args.add(CommandKeyword.MINMATCHLEN); args.add(minMatchLen); } if (withMatchLen) { args.add(CommandKeyword.WITHMATCHLEN); } } }
Builder
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_331.java
{ "start": 1690, "end": 2156 }
class ____ { private Date date; private Calendar calendar; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Calendar getCalendar() { return calendar; } public void setCalendar(Calendar calendar) { this.calendar = calendar; } } }
Model
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/flush/DirtyFlushTest.java
{ "start": 2031, "end": 2216 }
class ____ { @Id int id; @Version int version; @OneToOne(mappedBy = "user") Profile profile; } @Entity(name = "Profile") @Table(name = "PROFILE_TABLE") public static
User
java
apache__camel
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/JettyEndpointSetHttpTraceTest.java
{ "start": 1410, "end": 2936 }
class ____ extends BaseJettyTest { @RegisterExtension protected AvailablePortFinder.Port portTraceOn = AvailablePortFinder.find(); @RegisterExtension protected AvailablePortFinder.Port portTraceOff = AvailablePortFinder.find(); @Test public void testTraceDisabled() throws Exception { HttpTrace trace = new HttpTrace("http://localhost:" + portTraceOff + "/myservice"); try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(trace)) { // TRACE shouldn't be allowed by default assertEquals(405, response.getCode()); trace.reset(); } } @Test public void testTraceEnabled() throws Exception { CloseableHttpClient client = HttpClients.createDefault(); HttpTrace trace = new HttpTrace("http://localhost:" + portTraceOn + "/myservice"); HttpResponse response = client.execute(trace); // TRACE is allowed assertEquals(200, response.getCode()); trace.reset(); client.close(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("jetty:http://localhost:" + portTraceOff + "/myservice").to("log:foo"); from("jetty:http://localhost:" + portTraceOn + "/myservice?traceEnabled=true").to("log:bar"); } }; } }
JettyEndpointSetHttpTraceTest
java
google__guava
guava/src/com/google/common/util/concurrent/ListeningExecutorService.java
{ "start": 1773, "end": 5624 }
interface ____ extends ExecutorService { /** * @return a {@code ListenableFuture} representing pending completion of the task * @throws RejectedExecutionException {@inheritDoc} */ @Override <T extends @Nullable Object> ListenableFuture<T> submit(Callable<T> task); /** * @return a {@code ListenableFuture} representing pending completion of the task * @throws RejectedExecutionException {@inheritDoc} */ @Override ListenableFuture<?> submit(Runnable task); /** * @return a {@code ListenableFuture} representing pending completion of the task * @throws RejectedExecutionException {@inheritDoc} */ @Override <T extends @Nullable Object> ListenableFuture<T> submit( Runnable task, @ParametricNullness T result); /** * {@inheritDoc} * * <p>All elements in the returned list must be {@link ListenableFuture} instances. The easiest * way to obtain a {@code List<ListenableFuture<T>>} from this method is an unchecked (but safe) * cast: * * <pre> * {@code @SuppressWarnings("unchecked") // guaranteed by invokeAll contract} * {@code List<ListenableFuture<T>> futures = (List) executor.invokeAll(tasks);} * </pre> * * @return A list of {@code ListenableFuture} instances representing the tasks, in the same * sequential order as produced by the iterator for the given task list, each of which has * completed. * @throws RejectedExecutionException {@inheritDoc} * @throws NullPointerException if any task is null */ @Override <T extends @Nullable Object> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException; /** * {@inheritDoc} * * <p>All elements in the returned list must be {@link ListenableFuture} instances. The easiest * way to obtain a {@code List<ListenableFuture<T>>} from this method is an unchecked (but safe) * cast: * * <pre> * {@code @SuppressWarnings("unchecked") // guaranteed by invokeAll contract} * {@code List<ListenableFuture<T>> futures = (List) executor.invokeAll(tasks, timeout, unit);} * </pre> * * @return a list of {@code ListenableFuture} instances representing the tasks, in the same * sequential order as produced by the iterator for the given task list. If the operation did * not time out, each task will have completed. If it did time out, some of these tasks will * not have completed. * @throws RejectedExecutionException {@inheritDoc} * @throws NullPointerException if any task is null */ @Override <T extends @Nullable Object> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException; /** * Duration-based overload of {@link #invokeAll(Collection, long, TimeUnit)}. * * @since 32.1.0 */ @J2ktIncompatible default <T extends @Nullable Object> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks, Duration timeout) throws InterruptedException { return invokeAll(tasks, toNanosSaturated(timeout), TimeUnit.NANOSECONDS); } /** * Duration-based overload of {@link #invokeAny(Collection, long, TimeUnit)}. * * @since 32.1.0 */ @J2ktIncompatible default <T extends @Nullable Object> T invokeAny( Collection<? extends Callable<T>> tasks, Duration timeout) throws InterruptedException, ExecutionException, TimeoutException { return invokeAny(tasks, toNanosSaturated(timeout), TimeUnit.NANOSECONDS); } /** * Duration-based overload of {@link #awaitTermination(long, TimeUnit)}. * * @since 32.1.0 */ @J2ktIncompatible default boolean awaitTermination(Duration timeout) throws InterruptedException { return awaitTermination(toNanosSaturated(timeout), TimeUnit.NANOSECONDS); } }
ListeningExecutorService
java
elastic__elasticsearch
libs/x-content/impl/src/test/java/org/elasticsearch/xcontent/internal/CborTests.java
{ "start": 940, "end": 2225 }
class ____ extends ESTestCase { public void testCBORBasedOnMajorObjectDetection() { // for this {"f "=> 5} perl encoder for example generates: byte[] bytes = new byte[] { (byte) 0xA1, (byte) 0x43, (byte) 0x66, (byte) 6f, (byte) 6f, (byte) 0x5 }; assertThat(XContentFactory.xContentType(bytes), equalTo(XContentType.CBOR)); // this if for {"foo" : 5} in python CBOR bytes = new byte[] { (byte) 0xA1, (byte) 0x63, (byte) 0x66, (byte) 0x6f, (byte) 0x6f, (byte) 0x5 }; assertThat(XContentFactory.xContentType(bytes), equalTo(XContentType.CBOR)); assertThat(((Number) XContentHelper.convertToMap(new BytesArray(bytes), true).v2().get("foo")).intValue(), equalTo(5)); // also make sure major type check doesn't collide with SMILE and JSON, just in case assertThat(CBORConstants.hasMajorType(CBORConstants.MAJOR_TYPE_OBJECT, SmileConstants.HEADER_BYTE_1), equalTo(false)); assertThat(CBORConstants.hasMajorType(CBORConstants.MAJOR_TYPE_OBJECT, (byte) '{'), equalTo(false)); assertThat(CBORConstants.hasMajorType(CBORConstants.MAJOR_TYPE_OBJECT, (byte) ' '), equalTo(false)); assertThat(CBORConstants.hasMajorType(CBORConstants.MAJOR_TYPE_OBJECT, (byte) '-'), equalTo(false)); } }
CborTests
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/disk/SeekableFileChannelInputViewTest.java
{ "start": 1589, "end": 6108 }
class ____ { @Test void testSeek() throws Exception { final int PAGE_SIZE = 16 * 1024; final int NUM_RECORDS = 120000; // integers across 7.x pages (7 pages = 114.688 bytes, 8 pages = 131.072 bytes) try (IOManager ioManager = new IOManagerAsync()) { MemoryManager memMan = MemoryManagerBuilder.newBuilder() .setMemorySize(4 * PAGE_SIZE) .setPageSize(PAGE_SIZE) .build(); List<MemorySegment> memory = new ArrayList<MemorySegment>(); memMan.allocatePages(new DummyInvokable(), memory, 4); FileIOChannel.ID channel = ioManager.createChannel(); BlockChannelWriter<MemorySegment> writer = ioManager.createBlockChannelWriter(channel); FileChannelOutputView out = new FileChannelOutputView(writer, memMan, memory, memMan.getPageSize()); // write some integers across 7.5 pages (7 pages = 114.688 bytes, 8 pages = 131.072 // bytes) for (int i = 0; i < NUM_RECORDS; i += 4) { out.writeInt(i); } // close for the first time, make sure all memory returns out.close(); assertThat(memMan.verifyEmpty()).isTrue(); memMan.allocatePages(new DummyInvokable(), memory, 4); SeekableFileChannelInputView in = new SeekableFileChannelInputView( ioManager, channel, memMan, memory, out.getBytesInLatestSegment()); // read first, complete for (int i = 0; i < NUM_RECORDS; i += 4) { assertThat(in.readInt()).isEqualTo(i); } assertThatThrownBy(in::readInt) .withFailMessage("should throw EOF exception") .isInstanceOf(EOFException.class); // seek to the middle of the 3rd page int i = 2 * PAGE_SIZE + PAGE_SIZE / 4; in.seek(i); for (; i < NUM_RECORDS; i += 4) { assertThat(in.readInt()).isEqualTo(i); } assertThatThrownBy(in::readInt) .withFailMessage("should throw EOF exception") .isInstanceOf(EOFException.class); // seek to the end i = 120000 - 4; in.seek(i); for (; i < NUM_RECORDS; i += 4) { assertThat(in.readInt()).isEqualTo(i); } assertThatThrownBy(in::readInt) .withFailMessage("should throw EOF exception") .isInstanceOf(EOFException.class); // seek to the beginning i = 0; in.seek(i); for (; i < NUM_RECORDS; i += 4) { assertThat(in.readInt()).isEqualTo(i); } assertThatThrownBy(in::readInt) .withFailMessage("should throw EOF exception") .isInstanceOf(EOFException.class); // seek to after a page i = PAGE_SIZE; in.seek(i); for (; i < NUM_RECORDS; i += 4) { assertThat(in.readInt()).isEqualTo(i); } assertThatThrownBy(in::readInt) .withFailMessage("should throw EOF exception") .isInstanceOf(EOFException.class); // seek to after a page i = 3 * PAGE_SIZE; in.seek(i); for (; i < NUM_RECORDS; i += 4) { assertThat(in.readInt()).isEqualTo(i); } assertThatThrownBy(in::readInt) .withFailMessage("should throw EOF exception") .isInstanceOf(EOFException.class); // seek to the end i = NUM_RECORDS; in.seek(i); assertThatThrownBy(in::readInt) .withFailMessage("should throw EOF exception") .isInstanceOf(EOFException.class); // seek out of bounds assertThatThrownBy(() -> in.seek(-10)) .withFailMessage("should throw an exception") .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> in.seek(NUM_RECORDS + 1)) .withFailMessage("should throw an exception") .isInstanceOf(IllegalArgumentException.class); } } }
SeekableFileChannelInputViewTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingsImpl.java
{ "start": 1130, "end": 4649 }
class ____ implements SelectableMappings { private final SelectableMapping[] selectableMappings; public SelectableMappingsImpl(SelectableMapping[] selectableMappings) { this.selectableMappings = selectableMappings; } private static void resolveJdbcMappings(List<JdbcMapping> jdbcMappings, MappingContext mapping, Type valueType) { final Type keyType = valueType instanceof EntityType entityType ? entityType.getIdentifierOrUniqueKeyType( mapping ) : valueType; if ( keyType instanceof CompositeType compositeType ) { for ( Type subtype : compositeType.getSubtypes() ) { resolveJdbcMappings( jdbcMappings, mapping, subtype ); } } else { jdbcMappings.add( (JdbcMapping) keyType ); } } public static SelectableMappings from( String containingTableExpression, Value value, int[] propertyOrder, MappingContext mappingContext, TypeConfiguration typeConfiguration, boolean[] insertable, boolean[] updateable, Dialect dialect, SqmFunctionRegistry sqmFunctionRegistry, RuntimeModelCreationContext creationContext) { return from( containingTableExpression, value, propertyOrder, null, mappingContext, typeConfiguration, insertable, updateable, dialect, sqmFunctionRegistry, creationContext ); } public static SelectableMappings from( String containingTableExpression, Value value, int[] propertyOrder, @Nullable SelectablePath parentSelectablePath, MappingContext mappingContext, TypeConfiguration typeConfiguration, boolean[] insertable, boolean[] updateable, Dialect dialect, SqmFunctionRegistry sqmFunctionRegistry, RuntimeModelCreationContext creationContext) { final List<JdbcMapping> jdbcMappings = new ArrayList<>(); resolveJdbcMappings( jdbcMappings, mappingContext, value.getType() ); final var selectables = value.getVirtualSelectables(); final var selectableMappings = new SelectableMapping[jdbcMappings.size()]; for ( int i = 0; i < selectables.size(); i++ ) { selectableMappings[propertyOrder[i]] = SelectableMappingImpl.from( containingTableExpression, selectables.get( i ), parentSelectablePath, jdbcMappings.get( propertyOrder[i] ), typeConfiguration, i < insertable.length && insertable[i], i < updateable.length && updateable[i], false, dialect, sqmFunctionRegistry, creationContext ); } return new SelectableMappingsImpl( selectableMappings ); } public static SelectableMappings from(EmbeddableMappingType embeddableMappingType) { final int propertySpan = embeddableMappingType.getNumberOfAttributeMappings(); final List<SelectableMapping> selectableMappings = arrayList( propertySpan ); embeddableMappingType.forEachAttributeMapping( (index, attributeMapping) -> attributeMapping.forEachSelectable( (columnIndex, selection) -> selectableMappings.add( selection ) ) ); return new SelectableMappingsImpl( selectableMappings.toArray( new SelectableMapping[0] ) ); } @Override public SelectableMapping getSelectable(int columnIndex) { return selectableMappings[columnIndex]; } @Override public int getJdbcTypeCount() { return selectableMappings.length; } @Override public int forEachSelectable(final int offset, final SelectableConsumer consumer) { for ( int i = 0; i < selectableMappings.length; i++ ) { consumer.accept( offset + i, selectableMappings[i] ); } return selectableMappings.length; } }
SelectableMappingsImpl
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/TestParametersNotInitializedTest.java
{ "start": 1641, "end": 2130 }
class ____ { @TestParameter public boolean foo; } """) .addOutputLines( "Test.java", """ import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(TestParameterInjector.class) public
Test
java
apache__spark
examples/src/main/java/org/apache/spark/examples/ml/JavaGaussianMixtureExample.java
{ "start": 1250, "end": 2110 }
class ____ { public static void main(String[] args) { // Creates a SparkSession SparkSession spark = SparkSession .builder() .appName("JavaGaussianMixtureExample") .getOrCreate(); // $example on$ // Loads data Dataset<Row> dataset = spark.read().format("libsvm").load("data/mllib/sample_kmeans_data.txt"); // Trains a GaussianMixture model GaussianMixture gmm = new GaussianMixture() .setK(2); GaussianMixtureModel model = gmm.fit(dataset); // Output the parameters of the mixture model for (int i = 0; i < model.getK(); i++) { System.out.printf("Gaussian %d:\nweight=%f\nmu=%s\nsigma=\n%s\n\n", i, model.weights()[i], model.gaussians()[i].mean(), model.gaussians()[i].cov()); } // $example off$ spark.stop(); } }
JavaGaussianMixtureExample
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/service/spi/Wrapped.java
{ "start": 517, "end": 1025 }
interface ____ { /** * Can this wrapped service be unwrapped as the indicated type? * * @param unwrapType The type to check. * * @return True/false. */ boolean isUnwrappableAs(Class<?> unwrapType); /** * Unproxy the service proxy * * @param unwrapType The java type as which to unwrap this instance. * * @return The unwrapped reference * * @throws UnknownUnwrapTypeException if the service cannot be unwrapped as the indicated type */ <T> T unwrap(Class<T> unwrapType); }
Wrapped
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/date/DateFieldTest5.java
{ "start": 325, "end": 2368 }
class ____ extends TestCase { public void test_codec() throws Exception { SerializeConfig mapping = new SerializeConfig(); V0 v = new V0(); v.setValue(new Date()); String text = JSON.toJSONString(v, mapping); Assert.assertEquals("{\"value\":" + v.getValue().getTime() + "}", text); } public void test_codec_no_asm() throws Exception { V0 v = new V0(); v.setValue(new Date()); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":" + v.getValue().getTime() + "}", text); } public void test_codec_asm() throws Exception { V0 v = new V0(); v.setValue(new Date()); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(true); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":" + v.getValue().getTime() + "}", text); } public void test_codec_null_asm() throws Exception { V0 v = new V0(); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(true); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":null}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v1.getValue(), v.getValue()); } public void test_codec_null_1() throws Exception { V0 v = new V0(); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero); Assert.assertEquals("{\"value\":null}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(null, v1.getValue()); } public static
DateFieldTest5
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/Lambda2EndpointBuilderFactory.java
{ "start": 1431, "end": 1559 }
interface ____ { /** * Builder for endpoint for the AWS Lambda component. */ public
Lambda2EndpointBuilderFactory
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MailEndpointBuilderFactory.java
{ "start": 44145, "end": 80760 }
interface ____ extends EndpointConsumerBuilder { default MailEndpointConsumerBuilder basic() { return (MailEndpointConsumerBuilder) this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a: <code>org.apache.camel.spi.ExceptionHandler</code> * type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a * <code>org.apache.camel.spi.ExceptionHandler</code> type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder exceptionHandler(String exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a: <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a * <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder exchangePattern(String exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Whether to fail processing the mail if the mail message contains * attachments with duplicate file names. If set to false, then the * duplicate attachment is skipped and a WARN is logged. If set to true, * then an exception is thrown failing to process the mail message. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param failOnDuplicateFileAttachment the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder failOnDuplicateFileAttachment(boolean failOnDuplicateFileAttachment) { doSetProperty("failOnDuplicateFileAttachment", failOnDuplicateFileAttachment); return this; } /** * Whether to fail processing the mail if the mail message contains * attachments with duplicate file names. If set to false, then the * duplicate attachment is skipped and a WARN is logged. If set to true, * then an exception is thrown failing to process the mail message. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param failOnDuplicateFileAttachment the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder failOnDuplicateFileAttachment(String failOnDuplicateFileAttachment) { doSetProperty("failOnDuplicateFileAttachment", failOnDuplicateFileAttachment); return this; } /** * Sets the maximum number of messages to consume during a poll. This * can be used to avoid overloading a mail server, if a mailbox folder * contains a lot of messages. The default value of -1 means no fetch * size and all messages will be consumed. Setting the value to 0 is a * special corner case, where Camel will not consume any messages at * all. * * The option is a: <code>int</code> type. * * Default: -1 * Group: consumer (advanced) * * @param fetchSize the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder fetchSize(int fetchSize) { doSetProperty("fetchSize", fetchSize); return this; } /** * Sets the maximum number of messages to consume during a poll. This * can be used to avoid overloading a mail server, if a mailbox folder * contains a lot of messages. The default value of -1 means no fetch * size and all messages will be consumed. Setting the value to 0 is a * special corner case, where Camel will not consume any messages at * all. * * The option will be converted to a <code>int</code> type. * * Default: -1 * Group: consumer (advanced) * * @param fetchSize the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder fetchSize(String fetchSize) { doSetProperty("fetchSize", fetchSize); return this; } /** * The folder to poll. * * The option is a: <code>java.lang.String</code> type. * * Default: INBOX * Group: consumer (advanced) * * @param folderName the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder folderName(String folderName) { doSetProperty("folderName", folderName); return this; } /** * Set this to 'uuid' to set a UUID for the filename of the attachment * if no filename was set. * * The option is a: <code>java.lang.String</code> type. * * Group: consumer (advanced) * * @param generateMissingAttachmentNames the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder generateMissingAttachmentNames(String generateMissingAttachmentNames) { doSetProperty("generateMissingAttachmentNames", generateMissingAttachmentNames); return this; } /** * Set the strategy to handle duplicate filenames of attachments never: * attachments that have a filename which is already present in the * attachments will be ignored unless failOnDuplicateFileAttachment is * set to true. uuidPrefix: this will prefix the duplicate attachment * filenames each with an uuid and underscore * (uuid_filename.fileextension). uuidSuffix: this will suffix the * duplicate attachment filenames each with an underscore and uuid * (filename_uuid.fileextension). * * The option is a: <code>java.lang.String</code> type. * * Group: consumer (advanced) * * @param handleDuplicateAttachmentNames the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder handleDuplicateAttachmentNames(String handleDuplicateAttachmentNames) { doSetProperty("handleDuplicateAttachmentNames", handleDuplicateAttachmentNames); return this; } /** * A pluggable MailUidGenerator that allows to use custom logic to * generate UUID of the mail message. * * The option is a: * <code>org.apache.camel.component.mail.MailUidGenerator</code> type. * * Group: consumer (advanced) * * @param mailUidGenerator the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder mailUidGenerator(org.apache.camel.component.mail.MailUidGenerator mailUidGenerator) { doSetProperty("mailUidGenerator", mailUidGenerator); return this; } /** * A pluggable MailUidGenerator that allows to use custom logic to * generate UUID of the mail message. * * The option will be converted to a * <code>org.apache.camel.component.mail.MailUidGenerator</code> type. * * Group: consumer (advanced) * * @param mailUidGenerator the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder mailUidGenerator(String mailUidGenerator) { doSetProperty("mailUidGenerator", mailUidGenerator); return this; } /** * Specifies whether Camel should map the received mail message to Camel * body/headers/attachments. If set to true, the body of the mail * message is mapped to the body of the Camel IN message, the mail * headers are mapped to IN headers, and the attachments to Camel IN * attachment message. If this option is set to false, then the IN * message contains a raw jakarta.mail.Message. You can retrieve this * raw message by calling * exchange.getIn().getBody(jakarta.mail.Message.class). * * The option is a: <code>boolean</code> type. * * Default: true * Group: consumer (advanced) * * @param mapMailMessage the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder mapMailMessage(boolean mapMailMessage) { doSetProperty("mapMailMessage", mapMailMessage); return this; } /** * Specifies whether Camel should map the received mail message to Camel * body/headers/attachments. If set to true, the body of the mail * message is mapped to the body of the Camel IN message, the mail * headers are mapped to IN headers, and the attachments to Camel IN * attachment message. If this option is set to false, then the IN * message contains a raw jakarta.mail.Message. You can retrieve this * raw message by calling * exchange.getIn().getBody(jakarta.mail.Message.class). * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: consumer (advanced) * * @param mapMailMessage the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder mapMailMessage(String mapMailMessage) { doSetProperty("mapMailMessage", mapMailMessage); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option is a: * <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. * * Group: consumer (advanced) * * @param pollStrategy the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder pollStrategy(org.apache.camel.spi.PollingConsumerPollStrategy pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option will be converted to a * <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. * * Group: consumer (advanced) * * @param pollStrategy the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder pollStrategy(String pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } /** * Refers to an MailBoxPostProcessAction for doing post processing tasks * on the mailbox once the normal processing ended. * * The option is a: * <code>org.apache.camel.component.mail.MailBoxPostProcessAction</code> * type. * * Group: consumer (advanced) * * @param postProcessAction the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder postProcessAction(org.apache.camel.component.mail.MailBoxPostProcessAction postProcessAction) { doSetProperty("postProcessAction", postProcessAction); return this; } /** * Refers to an MailBoxPostProcessAction for doing post processing tasks * on the mailbox once the normal processing ended. * * The option will be converted to a * <code>org.apache.camel.component.mail.MailBoxPostProcessAction</code> * type. * * Group: consumer (advanced) * * @param postProcessAction the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder postProcessAction(String postProcessAction) { doSetProperty("postProcessAction", postProcessAction); return this; } /** * Sets additional java mail properties, that will append/override any * default properties that are set based on all the other options. This * is useful if you need to add some special options but want to keep * the others as is. This is a multi-value option with prefix: mail. * * The option is a: <code>java.util.Properties</code> type. * The option is multivalued, and you can use the * additionalJavaMailProperties(String, Object) method to add a value * (call the method multiple times to set more values). * * Group: advanced * * @param key the option key * @param value the option value * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder additionalJavaMailProperties(String key, Object value) { doSetMultiValueProperty("additionalJavaMailProperties", "mail." + key, value); return this; } /** * Sets additional java mail properties, that will append/override any * default properties that are set based on all the other options. This * is useful if you need to add some special options but want to keep * the others as is. This is a multi-value option with prefix: mail. * * The option is a: <code>java.util.Properties</code> type. * The option is multivalued, and you can use the * additionalJavaMailProperties(String, Object) method to add a value * (call the method multiple times to set more values). * * Group: advanced * * @param values the values * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder additionalJavaMailProperties(Map values) { doSetMultiValueProperties("additionalJavaMailProperties", "mail.", values); return this; } /** * Specifies the key to an IN message header that contains an * alternative email body. For example, if you send emails in text/html * format and want to provide an alternative mail body for non-HTML * email clients, set the alternative mail body with this key as a * header. * * The option is a: <code>java.lang.String</code> type. * * Default: CamelMailAlternativeBody * Group: advanced * * @param alternativeBodyHeader the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder alternativeBodyHeader(String alternativeBodyHeader) { doSetProperty("alternativeBodyHeader", alternativeBodyHeader); return this; } /** * To use a custom AttachmentsContentTransferEncodingResolver to resolve * what content-type-encoding to use for attachments. * * The option is a: * <code>org.apache.camel.component.mail.AttachmentsContentTransferEncodingResolver</code> type. * * Group: advanced * * @param attachmentsContentTransferEncodingResolver the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder attachmentsContentTransferEncodingResolver(org.apache.camel.component.mail.AttachmentsContentTransferEncodingResolver attachmentsContentTransferEncodingResolver) { doSetProperty("attachmentsContentTransferEncodingResolver", attachmentsContentTransferEncodingResolver); return this; } /** * To use a custom AttachmentsContentTransferEncodingResolver to resolve * what content-type-encoding to use for attachments. * * The option will be converted to a * <code>org.apache.camel.component.mail.AttachmentsContentTransferEncodingResolver</code> type. * * Group: advanced * * @param attachmentsContentTransferEncodingResolver the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder attachmentsContentTransferEncodingResolver(String attachmentsContentTransferEncodingResolver) { doSetProperty("attachmentsContentTransferEncodingResolver", attachmentsContentTransferEncodingResolver); return this; } /** * The authenticator for login. If set then the password and username * are ignored. It can be used for tokens which can expire and therefore * must be read dynamically. * * The option is a: * <code>org.apache.camel.component.mail.MailAuthenticator</code> type. * * Group: advanced * * @param authenticator the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder authenticator(org.apache.camel.component.mail.MailAuthenticator authenticator) { doSetProperty("authenticator", authenticator); return this; } /** * The authenticator for login. If set then the password and username * are ignored. It can be used for tokens which can expire and therefore * must be read dynamically. * * The option will be converted to a * <code>org.apache.camel.component.mail.MailAuthenticator</code> type. * * Group: advanced * * @param authenticator the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder authenticator(String authenticator) { doSetProperty("authenticator", authenticator); return this; } /** * Sets the binding used to convert from a Camel message to and from a * Mail message. * * The option is a: * <code>org.apache.camel.component.mail.MailBinding</code> type. * * Group: advanced * * @param binding the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder binding(org.apache.camel.component.mail.MailBinding binding) { doSetProperty("binding", binding); return this; } /** * Sets the binding used to convert from a Camel message to and from a * Mail message. * * The option will be converted to a * <code>org.apache.camel.component.mail.MailBinding</code> type. * * Group: advanced * * @param binding the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder binding(String binding) { doSetProperty("binding", binding); return this; } /** * The connection timeout in milliseconds. * * The option is a: <code>int</code> type. * * Default: 30000 * Group: advanced * * @param connectionTimeout the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder connectionTimeout(int connectionTimeout) { doSetProperty("connectionTimeout", connectionTimeout); return this; } /** * The connection timeout in milliseconds. * * The option will be converted to a <code>int</code> type. * * Default: 30000 * Group: advanced * * @param connectionTimeout the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder connectionTimeout(String connectionTimeout) { doSetProperty("connectionTimeout", connectionTimeout); return this; } /** * The mail message content type. Use text/html for HTML mails. * * The option is a: <code>java.lang.String</code> type. * * Default: text/plain * Group: advanced * * @param contentType the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder contentType(String contentType) { doSetProperty("contentType", contentType); return this; } /** * Resolver to determine Content-Type for file attachments. * * The option is a: * <code>org.apache.camel.component.mail.ContentTypeResolver</code> * type. * * Group: advanced * * @param contentTypeResolver the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder contentTypeResolver(org.apache.camel.component.mail.ContentTypeResolver contentTypeResolver) { doSetProperty("contentTypeResolver", contentTypeResolver); return this; } /** * Resolver to determine Content-Type for file attachments. * * The option will be converted to a * <code>org.apache.camel.component.mail.ContentTypeResolver</code> * type. * * Group: advanced * * @param contentTypeResolver the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder contentTypeResolver(String contentTypeResolver) { doSetProperty("contentTypeResolver", contentTypeResolver); return this; } /** * Enable debug mode on the underlying mail framework. The SUN Mail * framework logs the debug messages to System.out by default. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param debugMode the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder debugMode(boolean debugMode) { doSetProperty("debugMode", debugMode); return this; } /** * Enable debug mode on the underlying mail framework. The SUN Mail * framework logs the debug messages to System.out by default. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param debugMode the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder debugMode(String debugMode) { doSetProperty("debugMode", debugMode); return this; } /** * To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter * headers. * * The option is a: * <code>org.apache.camel.spi.HeaderFilterStrategy</code> type. * * Group: advanced * * @param headerFilterStrategy the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder headerFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy headerFilterStrategy) { doSetProperty("headerFilterStrategy", headerFilterStrategy); return this; } /** * To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter * headers. * * The option will be converted to a * <code>org.apache.camel.spi.HeaderFilterStrategy</code> type. * * Group: advanced * * @param headerFilterStrategy the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder headerFilterStrategy(String headerFilterStrategy) { doSetProperty("headerFilterStrategy", headerFilterStrategy); return this; } /** * Option to let Camel ignore unsupported charset in the local JVM when * sending mails. If the charset is unsupported, then charset=XXX (where * XXX represents the unsupported charset) is removed from the * content-type, and it relies on the platform default instead. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param ignoreUnsupportedCharset the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder ignoreUnsupportedCharset(boolean ignoreUnsupportedCharset) { doSetProperty("ignoreUnsupportedCharset", ignoreUnsupportedCharset); return this; } /** * Option to let Camel ignore unsupported charset in the local JVM when * sending mails. If the charset is unsupported, then charset=XXX (where * XXX represents the unsupported charset) is removed from the * content-type, and it relies on the platform default instead. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param ignoreUnsupportedCharset the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder ignoreUnsupportedCharset(String ignoreUnsupportedCharset) { doSetProperty("ignoreUnsupportedCharset", ignoreUnsupportedCharset); return this; } /** * Option to let Camel ignore unsupported charset in the local JVM when * sending mails. If the charset is unsupported, then charset=XXX (where * XXX represents the unsupported charset) is removed from the * content-type, and it relies on the platform default instead. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param ignoreUriScheme the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder ignoreUriScheme(boolean ignoreUriScheme) { doSetProperty("ignoreUriScheme", ignoreUriScheme); return this; } /** * Option to let Camel ignore unsupported charset in the local JVM when * sending mails. If the charset is unsupported, then charset=XXX (where * XXX represents the unsupported charset) is removed from the * content-type, and it relies on the platform default instead. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param ignoreUriScheme the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder ignoreUriScheme(String ignoreUriScheme) { doSetProperty("ignoreUriScheme", ignoreUriScheme); return this; } /** * Sets the java mail options. Will clear any default properties and * only use the properties provided for this method. * * The option is a: <code>java.util.Properties</code> type. * * Group: advanced * * @param javaMailProperties the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder javaMailProperties(Properties javaMailProperties) { doSetProperty("javaMailProperties", javaMailProperties); return this; } /** * Sets the java mail options. Will clear any default properties and * only use the properties provided for this method. * * The option will be converted to a <code>java.util.Properties</code> * type. * * Group: advanced * * @param javaMailProperties the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder javaMailProperties(String javaMailProperties) { doSetProperty("javaMailProperties", javaMailProperties); return this; } /** * Specifies the mail session that camel should use for all mail * interactions. Useful in scenarios where mail sessions are created and * managed by some other resource, such as a JavaEE container. When * using a custom mail session, then the hostname and port from the mail * session will be used (if configured on the session). * * The option is a: <code>jakarta.mail.Session</code> type. * * Group: advanced * * @param session the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder session(jakarta.mail.Session session) { doSetProperty("session", session); return this; } /** * Specifies the mail session that camel should use for all mail * interactions. Useful in scenarios where mail sessions are created and * managed by some other resource, such as a JavaEE container. When * using a custom mail session, then the hostname and port from the mail * session will be used (if configured on the session). * * The option will be converted to a <code>jakarta.mail.Session</code> * type. * * Group: advanced * * @param session the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder session(String session) { doSetProperty("session", session); return this; } /** * Whether to use disposition inline or attachment. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param useInlineAttachments the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder useInlineAttachments(boolean useInlineAttachments) { doSetProperty("useInlineAttachments", useInlineAttachments); return this; } /** * Whether to use disposition inline or attachment. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param useInlineAttachments the value to set * @return the dsl builder */ default AdvancedMailEndpointConsumerBuilder useInlineAttachments(String useInlineAttachments) { doSetProperty("useInlineAttachments", useInlineAttachments); return this; } } /** * Builder for endpoint producers for the IMAP component. */ public
AdvancedMailEndpointConsumerBuilder
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1790/Issue1790Mapper.java
{ "start": 507, "end": 683 }
interface ____ { Issue1790Mapper INSTANCE = Mappers.getMapper( Issue1790Mapper.class ); void toExistingCar(@MappingTarget Target target, Source source); }
Issue1790Mapper
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionProvidedImpl.java
{ "start": 638, "end": 3755 }
class ____ extends AbstractLogicalConnectionImplementor { private transient Connection providedConnection; private final boolean initiallyAutoCommit; private boolean closed; public LogicalConnectionProvidedImpl(Connection providedConnection, ResourceRegistry resourceRegistry) { this.resourceRegistry = resourceRegistry; if ( providedConnection == null ) { throw new IllegalArgumentException( "Provided Connection cannot be null" ); } this.providedConnection = providedConnection; this.initiallyAutoCommit = determineInitialAutoCommitMode( providedConnection ); } private LogicalConnectionProvidedImpl(boolean closed, boolean initiallyAutoCommit) { this.resourceRegistry = new ResourceRegistryStandardImpl(); this.closed = closed; this.initiallyAutoCommit = initiallyAutoCommit; } @Override public PhysicalConnectionHandlingMode getConnectionHandlingMode() { return IMMEDIATE_ACQUISITION_AND_HOLD; } @Override public boolean isOpen() { return !closed; } @Override public Connection close() { CONNECTION_LOGGER.closingLogicalConnection(); getResourceRegistry().releaseResources(); try { return providedConnection; } finally { providedConnection = null; closed = true; CONNECTION_LOGGER.logicalConnectionClosed(); } } @Override public boolean isPhysicallyConnected() { return providedConnection != null; } @Override public Connection getPhysicalConnection() { errorIfClosed(); return providedConnection; } @Override public void serialize(ObjectOutputStream oos) throws IOException { oos.writeBoolean( closed ); oos.writeBoolean( initiallyAutoCommit ); } public static LogicalConnectionProvidedImpl deserialize( ObjectInputStream ois) throws IOException, ClassNotFoundException { final boolean isClosed = ois.readBoolean(); final boolean initiallyAutoCommit = ois.readBoolean(); return new LogicalConnectionProvidedImpl( isClosed, initiallyAutoCommit ); } @Override public Connection manualDisconnect() { errorIfClosed(); try { resourceRegistry.releaseResources(); return providedConnection; } finally { providedConnection = null; } } @Override public void manualReconnect(Connection connection) { errorIfClosed(); if ( connection == null ) { throw new IllegalArgumentException( "cannot reconnect using a null connection" ); } else if ( connection == providedConnection ) { // likely an unmatched reconnect call (no matching disconnect call) CONNECTION_LOGGER.reconnectingSameConnectionAlreadyConnected(); } else if ( providedConnection != null ) { throw new IllegalArgumentException( "Cannot reconnect to a new user-supplied connection because currently connected; must disconnect before reconnecting." ); } providedConnection = connection; CONNECTION_LOGGER.manuallyReconnectedLogicalConnection(); } @Override protected Connection getConnectionForTransactionManagement() { return providedConnection; } @Override protected void afterCompletion() { afterTransaction(); resetConnection( initiallyAutoCommit ); } }
LogicalConnectionProvidedImpl
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/TestInstanceLifecycleTests.java
{ "start": 49722, "end": 49910 }
class ____ { InnerTestCase() { incrementInstanceCount(InnerTestCase.class); } @Test void test1() { } @Test void test2() { } } } private static
InnerTestCase
java
apache__hadoop
hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestRegexCopyFilter.java
{ "start": 1205, "end": 3539 }
class ____ { @Test public void testShouldCopyTrue() { List<Pattern> filters = new ArrayList<>(); filters.add(Pattern.compile("user")); RegexCopyFilter regexCopyFilter = new RegexCopyFilter("fakeFile"); regexCopyFilter.setFilters(filters); Path shouldCopyPath = new Path("/user/bar"); assertTrue(regexCopyFilter.shouldCopy(shouldCopyPath)); } @Test public void testShouldCopyFalse() { List<Pattern> filters = new ArrayList<>(); filters.add(Pattern.compile(".*test.*")); RegexCopyFilter regexCopyFilter = new RegexCopyFilter("fakeFile"); regexCopyFilter.setFilters(filters); Path shouldNotCopyPath = new Path("/user/testing"); assertFalse(regexCopyFilter.shouldCopy(shouldNotCopyPath)); } @Test public void testShouldCopyWithMultipleFilters() { List<Pattern> filters = new ArrayList<>(); filters.add(Pattern.compile(".*test.*")); filters.add(Pattern.compile("/user/b.*")); filters.add(Pattern.compile(".*_SUCCESS")); List<Path> toCopy = getTestPaths(); int shouldCopyCount = 0; RegexCopyFilter regexCopyFilter = new RegexCopyFilter("fakeFile"); regexCopyFilter.setFilters(filters); for (Path path: toCopy) { if (regexCopyFilter.shouldCopy(path)) { shouldCopyCount++; } } assertEquals(2, shouldCopyCount); } @Test public void testShouldExcludeAll() { List<Pattern> filters = new ArrayList<>(); filters.add(Pattern.compile(".*test.*")); filters.add(Pattern.compile("/user/b.*")); filters.add(Pattern.compile(".*")); // exclude everything List<Path> toCopy = getTestPaths(); int shouldCopyCount = 0; RegexCopyFilter regexCopyFilter = new RegexCopyFilter("fakeFile"); regexCopyFilter.setFilters(filters); for (Path path: toCopy) { if (regexCopyFilter.shouldCopy(path)) { shouldCopyCount++; } } assertEquals(0, shouldCopyCount); } private List<Path> getTestPaths() { List<Path> toCopy = new ArrayList<>(); toCopy.add(new Path("/user/bar")); toCopy.add(new Path("/user/foo/_SUCCESS")); toCopy.add(new Path("/hive/test_data")); toCopy.add(new Path("test")); toCopy.add(new Path("/user/foo/bar")); toCopy.add(new Path("/mapred/.staging_job")); return toCopy; } }
TestRegexCopyFilter
java
apache__rocketmq
tools/src/test/java/org/apache/rocketmq/tools/command/consumer/ConsumerProgressSubCommandTest.java
{ "start": 1545, "end": 3404 }
class ____ { private ServerResponseMocker brokerMocker; private ServerResponseMocker nameServerMocker; @Before public void before() { brokerMocker = startOneBroker(); nameServerMocker = NameServerMocker.startByDefaultConf(brokerMocker.listenPort()); } @After public void after() { brokerMocker.shutdown(); nameServerMocker.shutdown(); } @Ignore @Test public void testExecute() throws SubCommandException { ConsumerProgressSubCommand cmd = new ConsumerProgressSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-g default-group", String.format("-n localhost:%d", nameServerMocker.listenPort())}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new DefaultParser()); cmd.execute(commandLine, options, null); } private ServerResponseMocker startOneBroker() { ConsumeStats consumeStats = new ConsumeStats(); HashMap<MessageQueue, OffsetWrapper> offsetTable = new HashMap<>(); MessageQueue messageQueue = new MessageQueue(); messageQueue.setBrokerName("mockBrokerName"); messageQueue.setQueueId(1); messageQueue.setBrokerName("mockTopicName"); OffsetWrapper offsetWrapper = new OffsetWrapper(); offsetWrapper.setBrokerOffset(1); offsetWrapper.setConsumerOffset(1); offsetWrapper.setLastTimestamp(System.currentTimeMillis()); offsetTable.put(messageQueue, offsetWrapper); consumeStats.setOffsetTable(offsetTable); // start broker return ServerResponseMocker.startServer(consumeStats.encode()); } }
ConsumerProgressSubCommandTest
java
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/AnnotationLiteralGenerator.java
{ "start": 8955, "end": 9135 }
class ____ type. * Also generates a static initializer that assigns the default value of those * annotation members to the generated fields. * * @param cc the
array
java
apache__camel
test-infra/camel-test-infra-arangodb/src/test/java/org/apache/camel/test/infra/arangodb/services/ArangoDBService.java
{ "start": 974, "end": 1046 }
interface ____ extends TestService, ArangoDBInfraService { }
ArangoDBService
java
apache__camel
components/camel-azure/camel-azure-key-vault/src/generated/java/org/apache/camel/component/azure/key/vault/KeyVaultEndpointConfigurer.java
{ "start": 742, "end": 4370 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { KeyVaultEndpoint target = (KeyVaultEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "clientid": case "clientId": target.getConfiguration().setClientId(property(camelContext, java.lang.String.class, value)); return true; case "clientsecret": case "clientSecret": target.getConfiguration().setClientSecret(property(camelContext, java.lang.String.class, value)); return true; case "credentialtype": case "credentialType": target.getConfiguration().setCredentialType(property(camelContext, org.apache.camel.component.azure.key.vault.CredentialType.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "operation": target.getConfiguration().setOperation(property(camelContext, org.apache.camel.component.azure.key.vault.KeyVaultOperation.class, value)); return true; case "secretclient": case "secretClient": target.getConfiguration().setSecretClient(property(camelContext, com.azure.security.keyvault.secrets.SecretClient.class, value)); return true; case "tenantid": case "tenantId": target.getConfiguration().setTenantId(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public String[] getAutowiredNames() { return new String[]{"secretClient"}; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "clientid": case "clientId": return java.lang.String.class; case "clientsecret": case "clientSecret": return java.lang.String.class; case "credentialtype": case "credentialType": return org.apache.camel.component.azure.key.vault.CredentialType.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "operation": return org.apache.camel.component.azure.key.vault.KeyVaultOperation.class; case "secretclient": case "secretClient": return com.azure.security.keyvault.secrets.SecretClient.class; case "tenantid": case "tenantId": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { KeyVaultEndpoint target = (KeyVaultEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "clientid": case "clientId": return target.getConfiguration().getClientId(); case "clientsecret": case "clientSecret": return target.getConfiguration().getClientSecret(); case "credentialtype": case "credentialType": return target.getConfiguration().getCredentialType(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "operation": return target.getConfiguration().getOperation(); case "secretclient": case "secretClient": return target.getConfiguration().getSecretClient(); case "tenantid": case "tenantId": return target.getConfiguration().getTenantId(); default: return null; } } }
KeyVaultEndpointConfigurer
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/impl/MetricsRecordFiltered.java
{ "start": 1183, "end": 2453 }
class ____ extends AbstractMetricsRecord { private final MetricsRecord delegate; private final MetricsFilter filter; MetricsRecordFiltered(MetricsRecord delegate, MetricsFilter filter) { this.delegate = delegate; this.filter = filter; } @Override public long timestamp() { return delegate.timestamp(); } @Override public String name() { return delegate.name(); } @Override public String description() { return delegate.description(); } @Override public String context() { return delegate.context(); } @Override public Collection<MetricsTag> tags() { return delegate.tags(); } @Override public Iterable<AbstractMetric> metrics() { return new Iterable<AbstractMetric>() { final Iterator<AbstractMetric> it = delegate.metrics().iterator(); @Override public Iterator<AbstractMetric> iterator() { return new AbstractIterator<AbstractMetric>() { @Override public AbstractMetric computeNext() { while (it.hasNext()) { AbstractMetric next = it.next(); if (filter.accepts(next.name())) { return next; } } return endOfData(); } }; } }; } }
MetricsRecordFiltered
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingWithSecondaryTable.java
{ "start": 4867, "end": 5543 }
class ____ { @Id @GeneratedValue private Integer id; private String name; @OneToMany(mappedBy = "topLevel", cascade = { CascadeType.ALL }, orphanRemoval = true) private List<GeographicArea> geographicAreas = new ArrayList<>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public List<GeographicArea> getGeographicAreas() { return geographicAreas; } public void setGeographicAreas(List<GeographicArea> geographicAreas) { this.geographicAreas = geographicAreas; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
TopLevelEntity
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/cluster/ClusterServiceSelectorTest.java
{ "start": 12096, "end": 12719 }
class ____ extends AbstractCamelClusterView { public DummyClusterServiceView(CamelClusterService cluster, String namespace) { super(cluster, namespace); } @Override public Optional<CamelClusterMember> getLeader() { return Optional.empty(); } @Override public CamelClusterMember getLocalMember() { return new DummyClusterServiceMember(false, true); } @Override public List<CamelClusterMember> getMembers() { return Collections.emptyList(); } private final
DummyClusterServiceView
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/impl/transports/TransportLoader.java
{ "start": 580, "end": 1742 }
class ____ { public static Transport epoll() { try { EpollTransport impl = new EpollTransport(); boolean available = impl.isAvailable(); Throwable unavailabilityCause = impl.unavailabilityCause(); return new TransportInternal("epoll", available, unavailabilityCause, impl); } catch (Throwable ignore) { // Jar not here } return null; } public static Transport io_uring() { try { IoUringTransport impl = new IoUringTransport(); boolean available = impl.isAvailable(); Throwable unavailabilityCause = impl.unavailabilityCause(); return new TransportInternal("io_uring", available, unavailabilityCause, impl); } catch (Throwable ignore) { // Jar not here } return null; } public static Transport kqueue() { try { KQueueTransport impl = new KQueueTransport(); boolean available = impl.isAvailable(); Throwable unavailabilityCause = impl.unavailabilityCause(); return new TransportInternal("kqueue", available, unavailabilityCause, impl); } catch (Throwable ignore) { // Jar not here } return null; } }
TransportLoader
java
netty__netty
handler/src/main/java/io/netty/handler/pcap/PcapWriter.java
{ "start": 904, "end": 3853 }
class ____ implements Closeable { /** * Logger */ private static final InternalLogger logger = InternalLoggerFactory.getInstance(PcapWriter.class); private final PcapWriteHandler pcapWriteHandler; /** * Reference declared so that we can use this as mutex in clean way. */ private final OutputStream outputStream; /** * This uses {@link OutputStream} for writing Pcap data. * * @throws IOException If {@link OutputStream#write(byte[])} throws an exception */ PcapWriter(PcapWriteHandler pcapWriteHandler) throws IOException { this.pcapWriteHandler = pcapWriteHandler; outputStream = pcapWriteHandler.outputStream(); // If OutputStream is not shared then we have to write Global Header. if (pcapWriteHandler.writePcapGlobalHeader() && !pcapWriteHandler.sharedOutputStream()) { PcapHeaders.writeGlobalHeader(pcapWriteHandler.outputStream()); } } /** * Write Packet in Pcap OutputStream. * * @param packetHeaderBuf Packer Header {@link ByteBuf} * @param packet Packet * @throws IOException If {@link OutputStream#write(byte[])} throws an exception */ void writePacket(ByteBuf packetHeaderBuf, ByteBuf packet) throws IOException { if (pcapWriteHandler.state() == State.CLOSED) { logger.debug("Pcap Write attempted on closed PcapWriter"); } long timestamp = System.currentTimeMillis(); PcapHeaders.writePacketHeader( packetHeaderBuf, (int) (timestamp / 1000L), (int) (timestamp % 1000L * 1000L), packet.readableBytes(), packet.readableBytes() ); if (pcapWriteHandler.sharedOutputStream()) { synchronized (outputStream) { packetHeaderBuf.readBytes(outputStream, packetHeaderBuf.readableBytes()); packet.readBytes(outputStream, packet.readableBytes()); } } else { packetHeaderBuf.readBytes(outputStream, packetHeaderBuf.readableBytes()); packet.readBytes(outputStream, packet.readableBytes()); } } @Override public String toString() { return "PcapWriter{" + "outputStream=" + outputStream + '}'; } @Override public void close() throws IOException { if (pcapWriteHandler.state() == State.CLOSED) { logger.debug("PcapWriter is already closed"); } else { if (pcapWriteHandler.sharedOutputStream()) { synchronized (outputStream) { outputStream.flush(); } } else { outputStream.flush(); outputStream.close(); } pcapWriteHandler.markClosed(); logger.debug("PcapWriter is now closed"); } } }
PcapWriter
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/executiongraph/BlockingResultPartitionReleaseTest.java
{ "start": 6297, "end": 6718 }
class ____ extends NoOpJobMasterPartitionTracker { private final List<ResultPartitionID> releasedPartitions = new ArrayList<>(); @Override public void stopTrackingAndReleasePartitions( Collection<ResultPartitionID> resultPartitionIds, boolean releaseOnShuffleMaster) { releasedPartitions.addAll(checkNotNull(resultPartitionIds)); } } }
TestingPartitionTracker
java
alibaba__nacos
test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/NamingAuthCoreITCase.java
{ "start": 1911, "end": 5678 }
class ____ extends AuthBase { @LocalServerPort private int port; private NamingService namingService; @BeforeEach void init() throws Exception { super.init(port); } @AfterEach public void destroy() { super.destroy(); } @Test void writeWithReadPermission() throws Exception { properties.put(PropertyKeyConst.USERNAME, username1); properties.put(PropertyKeyConst.PASSWORD, password1); namingService = NacosFactory.createNamingService(properties); try { namingService.registerInstance("test.1", "1.2.3.4", 80); fail(); } catch (NacosException e) { NacosException cause = (NacosException) e.getCause(); assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode()); } try { namingService.deregisterInstance("test.1", "1.2.3.4", 80); fail(); } catch (NacosException e) { NacosException cause = (NacosException) e.getCause(); assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode()); } namingService.shutDown(); } @Test void readWithReadPermission() throws Exception { properties.put(PropertyKeyConst.USERNAME, username2); properties.put(PropertyKeyConst.PASSWORD, password2); NamingService namingService1 = NacosFactory.createNamingService(properties); namingService1.registerInstance("test.1", "1.2.3.4", 80); TimeUnit.SECONDS.sleep(5L); properties.put(PropertyKeyConst.USERNAME, username1); properties.put(PropertyKeyConst.PASSWORD, password1); namingService = NacosFactory.createNamingService(properties); List<Instance> list = namingService.getAllInstances("test.1"); assertEquals(1, list.size()); namingService1.shutDown(); namingService.shutDown(); } @Test void writeWithWritePermission() throws Exception { properties.put(PropertyKeyConst.USERNAME, username2); properties.put(PropertyKeyConst.PASSWORD, password2); namingService = NacosFactory.createNamingService(properties); namingService.registerInstance("test.1", "1.2.3.4", 80); TimeUnit.SECONDS.sleep(5L); namingService.deregisterInstance("test.1", "1.2.3.4", 80); namingService.shutDown(); } @Test void readWithWritePermission() throws Exception { properties.put(PropertyKeyConst.USERNAME, username2); properties.put(PropertyKeyConst.PASSWORD, password2); namingService = NacosFactory.createNamingService(properties); namingService.registerInstance("test.1", "1.2.3.4", 80); TimeUnit.SECONDS.sleep(5L); try { namingService.getAllInstances("test.1"); fail(); } catch (NacosException e) { NacosException cause = (NacosException) e.getCause(); assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode()); } namingService.shutDown(); } @Test void readWriteWithFullPermission() throws Exception { properties.put(PropertyKeyConst.USERNAME, username3); properties.put(PropertyKeyConst.PASSWORD, password3); namingService = NacosFactory.createNamingService(properties); namingService.registerInstance("test.1", "1.2.3.4", 80); TimeUnit.SECONDS.sleep(5L); List<Instance> list = namingService.getAllInstances("test.1"); assertEquals(1, list.size()); namingService.shutDown(); } }
NamingAuthCoreITCase
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/iterables/Iterables_assertNullOrEmpty_Test.java
{ "start": 1416, "end": 2873 }
class ____ extends IterablesBaseTest { @Test void should_pass_if_actual_is_null() { iterables.assertNullOrEmpty(someInfo(), null); } @Test void should_pass_if_actual_is_empty() { iterables.assertNullOrEmpty(someInfo(), emptyList()); } @Test void should_fail_if_actual_has_elements() { AssertionInfo info = someInfo(); Collection<String> actual = newArrayList("Yoda"); Throwable error = catchThrowable(() -> iterables.assertNullOrEmpty(info, actual)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeNullOrEmpty(actual)); } @Test void should_pass_if_actual_is_null_whatever_custom_comparison_strategy_is() { iterablesWithCaseInsensitiveComparisonStrategy.assertNullOrEmpty(someInfo(), null); } @Test void should_pass_if_actual_is_empty_whatever_custom_comparison_strategy_is() { iterablesWithCaseInsensitiveComparisonStrategy.assertNullOrEmpty(someInfo(), emptyList()); } @Test void should_fail_if_actual_has_elements_whatever_custom_comparison_strategy_is() { AssertionInfo info = someInfo(); Collection<String> actual = newArrayList("Yoda"); Throwable error = catchThrowable(() -> iterablesWithCaseInsensitiveComparisonStrategy.assertNullOrEmpty(info, actual)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeNullOrEmpty(actual)); } }
Iterables_assertNullOrEmpty_Test
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesSource.java
{ "start": 1298, "end": 1949 }
class ____ references them. When both types * are in the same module, the annotation processor can automatically discover full * metadata as long as the source is available. * <p> * Use this annotation when metadata for types located outside the module is needed: * <ol> * <li>Nested types annotated by {@code @NestedConfigurationProperty}</li> * <li>Base classes that a {@code @ConfigurationProperties}-annotated type extends * from</li> * </ol> * <p> * In the example below, {@code ServerProperties} is located in module "A" and * {@code Host} in module "B":<pre><code class="java"> * &#064;ConfigurationProperties("example.server") *
that
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/collection/bag/PersistentBagContainsTest.java
{ "start": 2767, "end": 3530 }
class ____ { @Id @GeneratedValue private Long id; private String name; @ManyToOne private Order order; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( !( o instanceof Item ) ) { return false; } Item item = (Item) o; return Objects.equals( getName(), item.getName() ); } @Override public int hashCode() { return Objects.hash( getName() ); } } }
Item
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/util/DualClassComparator.java
{ "start": 751, "end": 839 }
class ____ the actual and expected components. * * @author Alessandro Modolo */ public
of
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/main/java/io/quarkus/rest/client/reactive/deployment/ClientRedirectHandler.java
{ "start": 1570, "end": 6919 }
class ____ implements ResteasyReactiveResponseRedirectHandler { * public URI handle(Response var1, RestClientRequestContext var2) { * // simply call the static method of interface * return SomeService.map(var1); * } * * } * </pre> */ GeneratedClassResult generateResponseExceptionMapper(AnnotationInstance instance) { if (!DotNames.CLIENT_REDIRECT_HANDLER.equals(instance.name())) { throw new IllegalArgumentException( "'clientRedirectHandlerInstance' must be an instance of " + DotNames.CLIENT_REDIRECT_HANDLER); } MethodInfo targetMethod = null; boolean isValid = false; if (instance.target().kind() == AnnotationTarget.Kind.METHOD) { targetMethod = instance.target().asMethod(); if (ignoreAnnotation(targetMethod)) { return null; } if ((targetMethod.flags() & Modifier.STATIC) != 0) { String returnTypeClassName = targetMethod.returnType().name().toString(); try { boolean returnsUri = URI.class.isAssignableFrom( Class.forName(returnTypeClassName, false, Thread.currentThread().getContextClassLoader())); if (returnsUri) { isValid = true; } } catch (ClassNotFoundException ignored) { } } } if (!isValid) { String message = DotNames.CLIENT_REDIRECT_HANDLER + " is only supported on static methods of REST Client interfaces that take 'jakarta.ws.rs.core.Response'" + " as a single parameter and return 'java.net.URI'."; if (targetMethod != null) { message += " Offending instance is '" + targetMethod.declaringClass().name().toString() + "#" + targetMethod.name() + "'"; } throw new IllegalStateException(message); } StringBuilder sigBuilder = new StringBuilder(); sigBuilder.append(targetMethod.name()).append("_").append(targetMethod.returnType().name().toString()); for (Type i : targetMethod.parameterTypes()) { sigBuilder.append(i.name().toString()); } int priority = Priorities.USER; AnnotationValue priorityAnnotationValue = instance.value("priority"); if (priorityAnnotationValue != null) { priority = priorityAnnotationValue.asInt(); } ClassInfo restClientInterfaceClassInfo = targetMethod.declaringClass(); String generatedClassName = restClientInterfaceClassInfo.name().toString() + "_" + targetMethod.name() + "_" + "ResponseRedirectHandler" + "_" + HashUtil.sha1(sigBuilder.toString()); try (ClassCreator cc = ClassCreator.builder().classOutput(classOutput).className(generatedClassName) .interfaces(ResteasyReactiveResponseRedirectHandler.class).build()) { MethodCreator handle = cc.getMethodCreator("handle", URI.class, Response.class); LinkedHashMap<String, ResultHandle> targetMethodParams = new LinkedHashMap<>(); for (Type paramType : targetMethod.parameterTypes()) { ResultHandle targetMethodParamHandle; if (paramType.name().equals(ResteasyReactiveDotNames.RESPONSE)) { targetMethodParamHandle = handle.getMethodParam(0); } else { String message = DotNames.CLIENT_EXCEPTION_MAPPER + " can only take parameters of type '" + ResteasyReactiveDotNames.RESPONSE + "' or '" + DotNames.METHOD + "'" + " Offending instance is '" + targetMethod.declaringClass().name().toString() + "#" + targetMethod.name() + "'"; throw new IllegalStateException(message); } targetMethodParams.put(paramType.name().toString(), targetMethodParamHandle); } ResultHandle resultHandle = handle.invokeStaticInterfaceMethod( MethodDescriptor.ofMethod( restClientInterfaceClassInfo.name().toString(), targetMethod.name(), targetMethod.returnType().name().toString(), targetMethodParams.keySet().toArray(EMPTY_STRING_ARRAY)), targetMethodParams.values().toArray(EMPTY_RESULT_HANDLES_ARRAY)); handle.returnValue(resultHandle); if (priority != Priorities.USER) { MethodCreator getPriority = cc.getMethodCreator("getPriority", int.class); getPriority.returnValue(getPriority.load(priority)); } } return new GeneratedClassResult(restClientInterfaceClassInfo.name().toString(), generatedClassName, priority); } private static boolean ignoreAnnotation(MethodInfo methodInfo) { // ignore the annotation if it's placed on a Kotlin companion class // this is not a problem since the Kotlin compiler will also place the annotation the static method
SomeService_map_ResponseRedirectHandler_a8fb70beeef2a54b80151484d109618eed381626